764ffb215a600ab252272963fbcdd7cb12a0e773
[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 $attr = $meta->get_attribute($_);
123         my $is_mouse = $meta->isa('Mouse::Meta::Role');
124         my $spec = { %{ $is_mouse ? $attr : $attr->original_options } };
125
126         if ($spec->{isa}) {
127
128           my $get_constraint = do {
129             my $pkg = $is_mouse
130                         ? 'Mouse::Util::TypeConstraints'
131                         : 'Moose::Util::TypeConstraints';
132             _load_module($pkg);
133             $pkg->can('find_or_create_isa_type_constraint');
134           };
135
136           my $tc = $get_constraint->($spec->{isa});
137           my $check = $tc->_compiled_type_constraint;
138
139           $spec->{isa} = sub {
140             &$check or die "Type constraint failed for $_[0]"
141           };
142
143           if ($spec->{coerce}) {
144
145              # Mouse has _compiled_type_coercion straight on the TC object
146              $spec->{coerce} = $tc->${\(
147                $tc->can('coercion')||sub { $_[0] }
148              )}->_compiled_type_coercion;
149           }
150         }
151         $spec;
152       }), $meta->get_attribute_list
153     ];
154     my $mods = $INFO{$role}{modifiers} = [];
155     foreach my $type (qw(before after around)) {
156       # Mouse pokes its own internals so we have to fall back to doing
157       # the same thing in the absence of the Moose API method
158       my $map = $meta->${\(
159         $meta->can("get_${type}_method_modifiers_map")
160         or sub { shift->{"${type}_method_modifiers"} }
161       )};
162       foreach my $method (keys %$map) {
163         foreach my $mod (@{$map->{$method}}) {
164           push @$mods, [ $type => $method => $mod ];
165         }
166       }
167     }
168     require Class::Method::Modifiers if @$mods;
169     $INFO{$role}{inhaled_from_moose} = 1;
170   }
171 }
172
173 sub _maybe_make_accessors {
174   my ($self, $role, $target) = @_;
175   my $m;
176   if ($INFO{$role}{inhaled_from_moose}
177       or $INC{"Moo.pm"}
178       and $m = Moo->_accessor_maker_for($target)
179       and ref($m) ne 'Method::Generate::Accessor') {
180     $self->_make_accessors($role, $target);
181   }
182 }
183
184 sub _make_accessors_if_moose {
185   my ($self, $role, $target) = @_;
186   if ($INFO{$role}{inhaled_from_moose}) {
187     $self->_make_accessors($role, $target);
188   }
189 }
190
191 sub _make_accessors {
192   my ($self, $role, $target) = @_;
193   my $acc_gen = ($Moo::MAKERS{$target}{accessor} ||= do {
194     require Method::Generate::Accessor;
195     Method::Generate::Accessor->new
196   });
197   my $con_gen = $Moo::MAKERS{$target}{constructor};
198   my @attrs = @{$INFO{$role}{attributes}||[]};
199   while (my ($name, $spec) = splice @attrs, 0, 2) {
200     # needed to ensure we got an index for an arrayref based generator
201     if ($con_gen) {
202       $spec = $con_gen->all_attribute_specs->{$name};
203     }
204     $acc_gen->generate_method($target, $name, $spec);
205   }
206 }
207
208 sub apply_roles_to_package {
209   my ($me, $to, @roles) = @_;
210   foreach my $role (@roles) {
211       $me->_inhale_if_moose($role);
212   }
213   $me->SUPER::apply_roles_to_package($to, @roles);
214 }
215
216 sub apply_single_role_to_package {
217   my ($me, $to, $role) = @_;
218   die "${role} is not a Moo::Role" unless my $info = $INFO{$role};
219   $me->_inhale_if_moose($role);
220   $me->_handle_constructor($to, $INFO{$role}{attributes});
221   $me->_maybe_make_accessors($role, $to);
222   $me->SUPER::apply_single_role_to_package($to, $role);
223 }
224
225 sub create_class_with_roles {
226   my ($me, $superclass, @roles) = @_;
227
228   my $new_name = join(
229     '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
230   );
231
232   return $new_name if $Role::Tiny::COMPOSED{class}{$new_name};
233
234   foreach my $role (@roles) {
235       $me->_inhale_if_moose($role);
236   }
237
238   my $m;
239   if ($INC{"Moo.pm"}
240       and $m = Moo->_accessor_maker_for($superclass)
241       and ref($m) ne 'Method::Generate::Accessor') {
242     # old fashioned way time.
243     *{_getglob("${new_name}::ISA")} = [ $superclass ];
244     $me->apply_roles_to_package($new_name, @roles);
245     return $new_name;
246   }
247
248   require Sub::Quote;
249
250   $me->SUPER::create_class_with_roles($superclass, @roles);
251
252   foreach my $role (@roles) {
253     die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
254   }
255
256   $Moo::MAKERS{$new_name} = {};
257
258   $me->_handle_constructor(
259     $new_name, [ map @{$INFO{$_}{attributes}||[]}, @roles ]
260   );
261
262   return $new_name;
263 }
264
265 sub apply_roles_to_object {
266   my ($me, $object, @roles) = @_;
267   my $new = $me->SUPER::apply_roles_to_object($object, @roles);
268   if ($INC{'Moo.pm'}
269       and my $m = Moo->_accessor_maker_for(ref $new)
270       and my $con_gen = Moo->_constructor_maker_for(ref $new)) {
271     require Sub::Quote;
272
273     my $specs = $con_gen->all_attribute_specs;
274     my %attrs = map { @{$INFO{$_}{attributes}||[]} } @roles;
275
276     my $assign = '';
277     my %captures;
278     foreach my $name ( keys %attrs ) {
279       my $spec = $specs->{$name};
280       if ($m->has_eager_default($name, $spec)) {
281         my ($has, $has_cap)
282           = $m->generate_simple_has('$_[0]', $name, $spec);
283         my ($code, $pop_cap)
284           = $m->generate_use_default('$_[0]', $name, $spec, $has);
285
286         $assign .= $code;
287         @captures{keys %$has_cap, keys %$pop_cap}
288           = (values %$has_cap, values %$pop_cap);
289       }
290     }
291     Sub::Quote::quote_sub($assign, \%captures)->($new);
292   }
293   return $new;
294 }
295
296 sub _composable_package_for {
297   my ($self, $role) = @_;
298   my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
299   return $composed_name if $Role::Tiny::COMPOSED{role}{$composed_name};
300   $self->_make_accessors_if_moose($role, $composed_name);
301   $self->SUPER::_composable_package_for($role);
302 }
303
304 sub _install_single_modifier {
305   my ($me, @args) = @_;
306   _install_modifier(@args);
307 }
308
309 sub _handle_constructor {
310   my ($me, $to, $attr_info) = @_;
311   return unless $attr_info && @$attr_info;
312   if ($INFO{$to}) {
313     push @{$INFO{$to}{attributes}||=[]}, @$attr_info;
314   } else {
315     # only fiddle with the constructor if the target is a Moo class
316     if ($INC{"Moo.pm"}
317         and my $con = Moo->_constructor_maker_for($to)) {
318       # shallow copy of the specs since the constructor will assign an index
319       $con->register_attribute_specs(map ref() ? { %$_ } : $_, @$attr_info);
320     }
321   }
322 }
323
324 1;
325
326 =head1 NAME
327
328 Moo::Role - Minimal Object Orientation support for Roles
329
330 =head1 SYNOPSIS
331
332  package My::Role;
333
334  use Moo::Role;
335
336  sub foo { ... }
337
338  sub bar { ... }
339
340  has baz => (
341    is => 'ro',
342  );
343
344  1;
345
346 And elsewhere:
347
348  package Some::Class;
349
350  use Moo;
351
352  # bar gets imported, but not foo
353  with('My::Role');
354
355  sub foo { ... }
356
357  1;
358
359 =head1 DESCRIPTION
360
361 C<Moo::Role> builds upon L<Role::Tiny>, so look there for most of the
362 documentation on how this works.  The main addition here is extra bits to make
363 the roles more "Moosey;" which is to say, it adds L</has>.
364
365 =head1 IMPORTED SUBROUTINES
366
367 See L<Role::Tiny/IMPORTED SUBROUTINES> for all the other subroutines that are
368 imported by this module.
369
370 =head2 has
371
372  has attr => (
373    is => 'ro',
374  );
375
376 Declares an attribute for the class to be composed into.  See
377 L<Moo/has> for all options.
378
379 =head1 SUPPORT
380
381 See L<Moo> for support and contact information.
382
383 =head1 AUTHORS
384
385 See L<Moo> for authors.
386
387 =head1 COPYRIGHT AND LICENSE
388
389 See L<Moo> for the copyright and license.