reset handlemoose state on mutation
[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 import {
14   my $target = caller;
15   my ($me) = @_;
16   strictures->import;
17   return if $INFO{$target}; # already exported into this package
18   # get symbol table reference
19   my $stash = do { no strict 'refs'; \%{"${target}::"} };
20   _install_coderef "${target}::has" => "Moo::Role::has" => sub {
21     my ($name, %spec) = @_;
22     ($INFO{$target}{accessor_maker} ||= do {
23       require Method::Generate::Accessor;
24       Method::Generate::Accessor->new
25     })->generate_method($target, $name, \%spec);
26     push @{$INFO{$target}{attributes}||=[]}, $name, \%spec;
27     $me->_maybe_reset_handlemoose($target);
28   };
29   # install before/after/around subs
30   foreach my $type (qw(before after around)) {
31     *{_getglob "${target}::${type}"} = sub {
32       require Class::Method::Modifiers;
33       push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
34       $me->_maybe_reset_handlemoose($target);
35     };
36   }
37   *{_getglob "${target}::requires"} = sub {
38     push @{$INFO{$target}{requires}||=[]}, @_;
39     $me->_maybe_reset_handlemoose($target);
40   };
41   *{_getglob "${target}::with"} = sub {
42     $me->apply_roles_to_package($target, @_);
43     $me->_maybe_reset_handlemoose($target);
44   };
45   # grab all *non-constant* (stash slot is not a scalarref) subs present
46   # in the symbol table and store their refaddrs (no need to forcibly
47   # inflate constant subs into real subs) - also add '' to here (this
48   # is used later) with a map to the coderefs in case of copying or re-use
49   my @not_methods = ('', map { *$_{CODE}||() } grep !ref($_), values %$stash);
50   @{$INFO{$target}{not_methods}={}}{@not_methods} = @not_methods;
51   # a role does itself
52   $Role::Tiny::APPLIED_TO{$target} = { $target => undef };
53
54   if ($INC{'Moo/HandleMoose.pm'}) {
55     Moo::HandleMoose::inject_fake_metaclass_for($target);
56   }
57 }
58
59 sub _maybe_reset_handlemoose {
60   my ($class, $target) = @_;
61   if ($INC{"Moo/HandleMoose.pm"}) {
62     Moo::HandleMoose::maybe_reinject_fake_metaclass_for($target);
63   }
64 }
65
66 sub _inhale_if_moose {
67   my ($self, $role) = @_;
68   _load_module($role);
69   if (!$INFO{$role} and $INC{"Moose.pm"}) {
70     if (my $meta = Class::MOP::class_of($role)) {
71       $INFO{$role}{methods} = {
72         map +($_ => $role->can($_)),
73           grep !$meta->get_method($_)->isa('Class::MOP::Method::Meta'),
74             $meta->get_method_list
75       };
76       $Role::Tiny::APPLIED_TO{$role} = {
77         map +($_->name => 1), $meta->calculate_all_roles
78       };
79       $INFO{$role}{requires} = [ $meta->get_required_method_list ];
80       $INFO{$role}{attributes} = [
81         map +($_ => $meta->get_attribute($_)), $meta->get_attribute_list
82       ];
83       my $mods = $INFO{$role}{modifiers} = [];
84       foreach my $type (qw(before after around)) {
85         my $map = $meta->${\"get_${type}_method_modifiers_map"};
86         foreach my $method (keys %$map) {
87           foreach my $mod (@{$map->{$method}}) {
88             push @$mods, [ $type => $method => $mod ];
89           }
90         }
91       }
92       require Class::Method::Modifiers if @$mods;
93       $INFO{$role}{inhaled_from_moose} = 1;
94     }
95   }
96 }
97
98 sub _maybe_make_accessors {
99   my ($self, $role, $target) = @_;
100   my $m;
101   if ($INFO{$role}{inhaled_from_moose}
102       or $m = Moo->_accessor_maker_for($target)
103       and ref($m) ne 'Method::Generate::Accessor') {
104     $self->_make_accessors($role, $target);
105   }
106 }
107
108 sub _make_accessors_if_moose {
109   my ($self, $role, $target) = @_;
110   if ($INFO{$role}{inhaled_from_moose}) {
111     $self->_make_accessors($role, $target);
112   }
113 }
114
115 sub _make_accessors {
116   my ($self, $role, $target) = @_;
117   my $acc_gen = ($Moo::MAKERS{$target}{accessor} ||= do {
118     require Method::Generate::Accessor;
119     Method::Generate::Accessor->new
120   });
121   my $con_gen = $Moo::MAKERS{$target}{constructor};
122   my @attrs = @{$INFO{$role}{attributes}||[]};
123   while (my ($name, $spec) = splice @attrs, 0, 2) {
124     # needed to ensure we got an index for an arrayref based generator
125     if ($con_gen) {
126       $spec = $con_gen->all_attribute_specs->{$name};
127     }
128     $acc_gen->generate_method($target, $name, $spec);
129   }
130 }
131
132 sub apply_roles_to_package {
133   my ($me, $to, @roles) = @_;
134   $me->_inhale_if_moose($_) for @roles;
135   $me->SUPER::apply_roles_to_package($to, @roles);
136 }
137
138 sub apply_single_role_to_package {
139   my ($me, $to, $role) = @_;
140   $me->_inhale_if_moose($role);
141   $me->_handle_constructor($to, $INFO{$role}{attributes});
142   $me->_maybe_make_accessors($role, $to);
143   $me->SUPER::apply_single_role_to_package($to, $role);
144 }
145
146 sub create_class_with_roles {
147   my ($me, $superclass, @roles) = @_;
148
149   my $new_name = join(
150     '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
151   );
152
153   return $new_name if $Role::Tiny::COMPOSED{class}{$new_name};
154
155   $me->_inhale_if_moose($_) for @roles;
156
157   my $m;
158   if ($m = Moo->_accessor_maker_for($superclass)
159       and ref($m) ne 'Method::Generate::Accessor') {
160     # old fashioned way time.
161     *{_getglob("${new_name}::ISA")} = [ $superclass ];
162     $me->apply_roles_to_package($new_name, @roles);
163     return $new_name;
164   }
165
166   require Sub::Quote;
167
168   $me->SUPER::create_class_with_roles($superclass, @roles);
169
170   foreach my $role (@roles) {
171     die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
172   }
173
174   $Moo::MAKERS{$new_name} = {};
175
176   $me->_handle_constructor(
177     $new_name, [ map @{$INFO{$_}{attributes}||[]}, @roles ], $superclass
178   );
179
180   return $new_name;
181 }
182
183 sub _composable_package_for {
184   my ($self, $role) = @_;
185   my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
186   return $composed_name if $Role::Tiny::COMPOSED{role}{$composed_name};
187   $self->_make_accessors_if_moose($role, $composed_name);
188   $self->SUPER::_composable_package_for($role);
189 }
190
191 sub _install_single_modifier {
192   my ($me, @args) = @_;
193   _install_modifier(@args);
194 }
195
196 sub _handle_constructor {
197   my ($me, $to, $attr_info, $superclass) = @_;
198   return unless $attr_info && @$attr_info;
199   if ($INFO{$to}) {
200     push @{$INFO{$to}{attributes}||=[]}, @$attr_info;
201   } else {
202     # only fiddle with the constructor if the target is a Moo class
203     if ($INC{"Moo.pm"}
204         and my $con = Moo->_constructor_maker_for($to, $superclass)) {
205       # shallow copy of the specs since the constructor will assign an index
206       $con->register_attribute_specs(map ref() ? { %$_ } : $_, @$attr_info);
207     }
208   }
209 }
210
211 1;
212
213 =head1 NAME
214
215 Moo::Role - Minimal Object Orientation support for Roles
216
217 =head1 SYNOPSIS
218
219  package My::Role;
220
221  use Moo::Role;
222
223  sub foo { ... }
224
225  sub bar { ... }
226
227  has baz => (
228    is => 'ro',
229  );
230
231  1;
232
233 else where
234
235  package Some::Class;
236
237  use Moo;
238
239  # bar gets imported, but not foo
240  with('My::Role');
241
242  sub foo { ... }
243
244  1;
245
246 =head1 DESCRIPTION
247
248 C<Moo::Role> builds upon L<Role::Tiny>, so look there for most of the
249 documentation on how this works.  The main addition here is extra bits to make
250 the roles more "Moosey;" which is to say, it adds L</has>.
251
252 =head1 IMPORTED SUBROUTINES
253
254 See L<Role::Tiny/IMPORTED SUBROUTINES> for all the other subroutines that are
255 imported by this module.
256
257 =head2 has
258
259  has attr => (
260    is => 'ro',
261  );
262
263 Declares an attribute for the class to be composed into.  See
264 L<Moo/has> for all options.
265
266 =head1 AUTHORS
267
268 See L<Moo> for authors.
269
270 =head1 COPYRIGHT AND LICENSE
271
272 See L<Moo> for the copyright and license.
273
274 =cut