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