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