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