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