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