convert isa and coerce info from external role attributes
[gitmo/Moo.git] / lib / Moo / Role.pm
1 package Moo::Role;
2
3 use strictures 1;
4 use Moo::_Utils;
5 use base qw(Role::Tiny);
6
7 require Moo::sification;
8
9 BEGIN { *INFO = \%Role::Tiny::INFO }
10
11 our %INFO;
12
13 sub _install_tracked {
14   my ($target, $name, $code) = @_;
15   $INFO{$target}{exports}{$name} = $code;
16   _install_coderef "${target}::${name}" => "Moo::Role::${name}" => $code;
17 }
18
19 sub import {
20   my $target = caller;
21   my ($me) = @_;
22   strictures->import;
23   return if $INFO{$target}; # already exported into this package
24   $INFO{$target} = {};
25   # get symbol table reference
26   my $stash = do { no strict 'refs'; \%{"${target}::"} };
27   _install_tracked $target => has => sub {
28     my ($name, %spec) = @_;
29     ($INFO{$target}{accessor_maker} ||= do {
30       require Method::Generate::Accessor;
31       Method::Generate::Accessor->new
32     })->generate_method($target, $name, \%spec);
33     push @{$INFO{$target}{attributes}||=[]}, $name, \%spec;
34     $me->_maybe_reset_handlemoose($target);
35   };
36   # install before/after/around subs
37   foreach my $type (qw(before after around)) {
38     _install_tracked $target => $type => sub {
39       require Class::Method::Modifiers;
40       push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
41       $me->_maybe_reset_handlemoose($target);
42     };
43   }
44   _install_tracked $target => requires => sub {
45     push @{$INFO{$target}{requires}||=[]}, @_;
46     $me->_maybe_reset_handlemoose($target);
47   };
48   _install_tracked $target => with => sub {
49     $me->apply_roles_to_package($target, @_);
50     $me->_maybe_reset_handlemoose($target);
51   };
52   # grab all *non-constant* (stash slot is not a scalarref) subs present
53   # in the symbol table and store their refaddrs (no need to forcibly
54   # inflate constant subs into real subs) - also add '' to here (this
55   # is used later) with a map to the coderefs in case of copying or re-use
56   my @not_methods = ('', map { *$_{CODE}||() } grep !ref($_), values %$stash);
57   @{$INFO{$target}{not_methods}={}}{@not_methods} = @not_methods;
58   # a role does itself
59   $Role::Tiny::APPLIED_TO{$target} = { $target => undef };
60
61   if ($INC{'Moo/HandleMoose.pm'}) {
62     Moo::HandleMoose::inject_fake_metaclass_for($target);
63   }
64 }
65
66 sub unimport {
67   my $target = caller;
68   _unimport_coderefs($target, $INFO{$target});
69 }
70
71 sub _maybe_reset_handlemoose {
72   my ($class, $target) = @_;
73   if ($INC{"Moo/HandleMoose.pm"}) {
74     Moo::HandleMoose::maybe_reinject_fake_metaclass_for($target);
75   }
76 }
77
78 sub _inhale_if_moose {
79   my ($self, $role) = @_;
80   _load_module($role);
81   my $meta;
82   if (!$INFO{$role}
83       and (
84         $INC{"Moose.pm"}
85         and $meta = Class::MOP::class_of($role)
86       )
87       or (
88         $INC{"Mouse.pm"}
89         and $meta = Mouse::Util::find_meta($role)
90      )
91   ) {
92     $INFO{$role}{methods} = {
93       map +($_ => $role->can($_)),
94         grep !$meta->get_method($_)->isa('Class::MOP::Method::Meta'),
95           $meta->get_method_list
96     };
97     $Role::Tiny::APPLIED_TO{$role} = {
98       map +($_->name => 1), $meta->calculate_all_roles
99     };
100     $INFO{$role}{requires} = [ $meta->get_required_method_list ];
101     $INFO{$role}{attributes} = [
102       map +($_ => do {
103         my $spec = { %{$meta->get_attribute($_)} };
104         if ($spec->{isa}) {
105           require Moose::Util::TypeConstraints;
106           my $tc = Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($spec->{isa});
107           my $check = $tc->_compiled_type_constraint;
108           $spec->{isa} = sub { &$check or die "Type constraint failed for $_[0]" };
109           if ($spec->{coerce}) {
110              $spec->{coerce} = $tc->coercion->_compiled_type_coercion;
111           }
112         }
113         $spec;
114       }), $meta->get_attribute_list
115     ];
116     my $mods = $INFO{$role}{modifiers} = [];
117     foreach my $type (qw(before after around)) {
118       # Mouse pokes its own internals so we have to fall back to doing
119       # the same thing in the absence of the Moose API method
120       my $map = $meta->${\(
121         $meta->can("get_${type}_method_modifiers_map")
122         or sub { shift->{"${type}_method_modifiers"} }
123       )};
124       foreach my $method (keys %$map) {
125         foreach my $mod (@{$map->{$method}}) {
126           push @$mods, [ $type => $method => $mod ];
127         }
128       }
129     }
130     require Class::Method::Modifiers if @$mods;
131     $INFO{$role}{inhaled_from_moose} = 1;
132   }
133 }
134
135 sub _maybe_make_accessors {
136   my ($self, $role, $target) = @_;
137   my $m;
138   if ($INFO{$role}{inhaled_from_moose}
139       or $INC{"Moo.pm"}
140       and $m = Moo->_accessor_maker_for($target)
141       and ref($m) ne 'Method::Generate::Accessor') {
142     $self->_make_accessors($role, $target);
143   }
144 }
145
146 sub _make_accessors_if_moose {
147   my ($self, $role, $target) = @_;
148   if ($INFO{$role}{inhaled_from_moose}) {
149     $self->_make_accessors($role, $target);
150   }
151 }
152
153 sub _make_accessors {
154   my ($self, $role, $target) = @_;
155   my $acc_gen = ($Moo::MAKERS{$target}{accessor} ||= do {
156     require Method::Generate::Accessor;
157     Method::Generate::Accessor->new
158   });
159   my $con_gen = $Moo::MAKERS{$target}{constructor};
160   my @attrs = @{$INFO{$role}{attributes}||[]};
161   while (my ($name, $spec) = splice @attrs, 0, 2) {
162     # needed to ensure we got an index for an arrayref based generator
163     if ($con_gen) {
164       $spec = $con_gen->all_attribute_specs->{$name};
165     }
166     $acc_gen->generate_method($target, $name, $spec);
167   }
168 }
169
170 sub apply_roles_to_package {
171   my ($me, $to, @roles) = @_;
172   $me->_inhale_if_moose($_) for @roles;
173   $me->SUPER::apply_roles_to_package($to, @roles);
174 }
175
176 sub apply_single_role_to_package {
177   my ($me, $to, $role) = @_;
178   $me->_inhale_if_moose($role);
179   $me->_handle_constructor($to, $INFO{$role}{attributes});
180   $me->_maybe_make_accessors($role, $to);
181   $me->SUPER::apply_single_role_to_package($to, $role);
182 }
183
184 sub create_class_with_roles {
185   my ($me, $superclass, @roles) = @_;
186
187   my $new_name = join(
188     '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
189   );
190
191   return $new_name if $Role::Tiny::COMPOSED{class}{$new_name};
192
193   $me->_inhale_if_moose($_) for @roles;
194
195   my $m;
196   if ($INC{"Moo.pm"}
197       and $m = Moo->_accessor_maker_for($superclass)
198       and ref($m) ne 'Method::Generate::Accessor') {
199     # old fashioned way time.
200     *{_getglob("${new_name}::ISA")} = [ $superclass ];
201     $me->apply_roles_to_package($new_name, @roles);
202     return $new_name;
203   }
204
205   require Sub::Quote;
206
207   $me->SUPER::create_class_with_roles($superclass, @roles);
208
209   foreach my $role (@roles) {
210     die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
211   }
212
213   $Moo::MAKERS{$new_name} = {};
214
215   $me->_handle_constructor(
216     $new_name, [ map @{$INFO{$_}{attributes}||[]}, @roles ], $superclass
217   );
218
219   return $new_name;
220 }
221
222 sub _composable_package_for {
223   my ($self, $role) = @_;
224   my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
225   return $composed_name if $Role::Tiny::COMPOSED{role}{$composed_name};
226   $self->_make_accessors_if_moose($role, $composed_name);
227   $self->SUPER::_composable_package_for($role);
228 }
229
230 sub _install_single_modifier {
231   my ($me, @args) = @_;
232   _install_modifier(@args);
233 }
234
235 sub _handle_constructor {
236   my ($me, $to, $attr_info, $superclass) = @_;
237   return unless $attr_info && @$attr_info;
238   if ($INFO{$to}) {
239     push @{$INFO{$to}{attributes}||=[]}, @$attr_info;
240   } else {
241     # only fiddle with the constructor if the target is a Moo class
242     if ($INC{"Moo.pm"}
243         and my $con = Moo->_constructor_maker_for($to, $superclass)) {
244       # shallow copy of the specs since the constructor will assign an index
245       $con->register_attribute_specs(map ref() ? { %$_ } : $_, @$attr_info);
246     }
247   }
248 }
249
250 1;
251
252 =head1 NAME
253
254 Moo::Role - Minimal Object Orientation support for Roles
255
256 =head1 SYNOPSIS
257
258  package My::Role;
259
260  use Moo::Role;
261
262  sub foo { ... }
263
264  sub bar { ... }
265
266  has baz => (
267    is => 'ro',
268  );
269
270  1;
271
272 else where
273
274  package Some::Class;
275
276  use Moo;
277
278  # bar gets imported, but not foo
279  with('My::Role');
280
281  sub foo { ... }
282
283  1;
284
285 =head1 DESCRIPTION
286
287 C<Moo::Role> builds upon L<Role::Tiny>, so look there for most of the
288 documentation on how this works.  The main addition here is extra bits to make
289 the roles more "Moosey;" which is to say, it adds L</has>.
290
291 =head1 IMPORTED SUBROUTINES
292
293 See L<Role::Tiny/IMPORTED SUBROUTINES> for all the other subroutines that are
294 imported by this module.
295
296 =head2 has
297
298  has attr => (
299    is => 'ro',
300  );
301
302 Declares an attribute for the class to be composed into.  See
303 L<Moo/has> for all options.
304
305 =head1 AUTHORS
306
307 See L<Moo> for authors.
308
309 =head1 COPYRIGHT AND LICENSE
310
311 See L<Moo> for the copyright and license.
312
313 =cut