more consistent method arguments and extra protection against autovivification
[gitmo/Moo.git] / lib / Moo / Role.pm
CommitLineData
d245e471 1package Moo::Role;
2
3use strictures 1;
4use Moo::_Utils;
7a9263a9 5use Role::Tiny ();
d245e471 6use base qw(Role::Tiny);
7
a047096b 8require Moo::sification;
9
d245e471 10BEGIN { *INFO = \%Role::Tiny::INFO }
11
12our %INFO;
1e84d6ac 13our %APPLY_DEFAULTS;
d245e471 14
108f8ddc 15sub _install_tracked {
16 my ($target, $name, $code) = @_;
17 $INFO{$target}{exports}{$name} = $code;
18 _install_coderef "${target}::${name}" => "Moo::Role::${name}" => $code;
19}
20
d245e471 21sub import {
22 my $target = caller;
6c49212f 23 my ($me) = @_;
d245e471 24 strictures->import;
1791ba32 25 if ($Moo::MAKERS{$target} and $Moo::MAKERS{$target}{is_class}) {
26 die "Cannot import Moo::Role into a Moo class";
27 }
fa93bfb2 28 $INFO{$target} ||= {};
d245e471 29 # get symbol table reference
30 my $stash = do { no strict 'refs'; \%{"${target}::"} };
108f8ddc 31 _install_tracked $target => has => sub {
1d17c7c1 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 }
d245e471 43 };
6c49212f 44 # install before/after/around subs
45 foreach my $type (qw(before after around)) {
108f8ddc 46 _install_tracked $target => $type => sub {
6c49212f 47 require Class::Method::Modifiers;
48 push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
49 $me->_maybe_reset_handlemoose($target);
50 };
51 }
108f8ddc 52 _install_tracked $target => requires => sub {
6c49212f 53 push @{$INFO{$target}{requires}||=[]}, @_;
54 $me->_maybe_reset_handlemoose($target);
55 };
108f8ddc 56 _install_tracked $target => with => sub {
6c49212f 57 $me->apply_roles_to_package($target, @_);
58 $me->_maybe_reset_handlemoose($target);
59 };
fa93bfb2 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');
6c49212f 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
7f9775b1 72 if ($INC{'Moo/HandleMoose.pm'}) {
73 Moo::HandleMoose::inject_fake_metaclass_for($target);
74 }
6c49212f 75}
76
fa93bfb2 77# duplicate from Moo::Object
78sub meta {
79 require Moo::HandleMoose::FakeMetaClass;
80 my $class = ref($_[0])||$_[0];
81 bless({ name => $class }, 'Moo::HandleMoose::FakeMetaClass');
82}
83
108f8ddc 84sub unimport {
85 my $target = caller;
86 _unimport_coderefs($target, $INFO{$target});
87}
88
6c49212f 89sub _maybe_reset_handlemoose {
90 my ($class, $target) = @_;
91 if ($INC{"Moo/HandleMoose.pm"}) {
92 Moo::HandleMoose::maybe_reinject_fake_metaclass_for($target);
93 }
d245e471 94}
95
a84066c7 96sub _inhale_if_moose {
97 my ($self, $role) = @_;
98 _load_module($role);
c100c04c 99 my $meta;
100 if (!$INFO{$role}
101 and (
102 $INC{"Moose.pm"}
103 and $meta = Class::MOP::class_of($role)
c316ebe5 104 and $meta->isa('Moose::Meta::Role')
c100c04c 105 )
106 or (
96b09f21 107 Mouse::Util->can('find_meta')
c100c04c 108 and $meta = Mouse::Util::find_meta($role)
c316ebe5 109 and $meta->isa('Mouse::Meta::Role')
c100c04c 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} = [
a668eb67 122 map +($_ => do {
358c29e1 123 my $attr = $meta->get_attribute($_);
124 my $is_mouse = $meta->isa('Mouse::Meta::Role');
125 my $spec = { %{ $is_mouse ? $attr : $attr->original_options } };
f96bb37c 126
a668eb67 127 if ($spec->{isa}) {
f96bb37c 128
129 my $get_constraint = do {
358c29e1 130 my $pkg = $is_mouse
f96bb37c 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});
a668eb67 138 my $check = $tc->_compiled_type_constraint;
f96bb37c 139
140 $spec->{isa} = sub {
141 &$check or die "Type constraint failed for $_[0]"
142 };
143
a668eb67 144 if ($spec->{coerce}) {
f96bb37c 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;
a668eb67 150 }
151 }
152 $spec;
153 }), $meta->get_attribute_list
c100c04c 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 ];
a84066c7 166 }
167 }
a84066c7 168 }
c100c04c 169 require Class::Method::Modifiers if @$mods;
170 $INFO{$role}{inhaled_from_moose} = 1;
a84066c7 171 }
172}
173
a41e15c3 174sub _maybe_make_accessors {
5d4eb6e9 175 my ($self, $target, $role) = @_;
a41e15c3 176 my $m;
5d4eb6e9 177 if ($INFO{$role} && $INFO{$role}{inhaled_from_moose}
e9290d4a 178 or $INC{"Moo.pm"}
179 and $m = Moo->_accessor_maker_for($target)
a41e15c3 180 and ref($m) ne 'Method::Generate::Accessor') {
5d4eb6e9 181 $self->_make_accessors($target, $role);
a41e15c3 182 }
183}
184
a84066c7 185sub _make_accessors_if_moose {
5d4eb6e9 186 my ($self, $target, $role) = @_;
187 if ($INFO{$role} && $INFO{$role}{inhaled_from_moose}) {
188 $self->_make_accessors($target, $role);
a41e15c3 189 }
190}
191
192sub _make_accessors {
5d4eb6e9 193 my ($self, $target, $role) = @_;
a41e15c3 194 my $acc_gen = ($Moo::MAKERS{$target}{accessor} ||= do {
195 require Method::Generate::Accessor;
196 Method::Generate::Accessor->new
197 });
db10ae2d 198 my $con_gen = $Moo::MAKERS{$target}{constructor};
a41e15c3 199 my @attrs = @{$INFO{$role}{attributes}||[]};
200 while (my ($name, $spec) = splice @attrs, 0, 2) {
db10ae2d 201 # needed to ensure we got an index for an arrayref based generator
202 if ($con_gen) {
203 $spec = $con_gen->all_attribute_specs->{$name};
204 }
a41e15c3 205 $acc_gen->generate_method($target, $name, $spec);
a84066c7 206 }
207}
208
4a79464d 209sub apply_roles_to_package {
210 my ($me, $to, @roles) = @_;
141b507a 211 foreach my $role (@roles) {
212 $me->_inhale_if_moose($role);
213 }
4a79464d 214 $me->SUPER::apply_roles_to_package($to, @roles);
215}
216
6893ea30 217sub apply_single_role_to_package {
369a4c50 218 my ($me, $to, $role) = @_;
a84066c7 219 $me->_inhale_if_moose($role);
8420a97e 220 die "${role} is not a Moo::Role" unless my $info = $INFO{$role};
5d4eb6e9 221 $me->_handle_constructor($to, $role);
222 $me->_maybe_make_accessors($to, $role);
a41e15c3 223 $me->SUPER::apply_single_role_to_package($to, $role);
d245e471 224}
225
226sub create_class_with_roles {
227 my ($me, $superclass, @roles) = @_;
228
c69190f1 229 my $new_name = join(
230 '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
231 );
232
d245e471 233 return $new_name if $Role::Tiny::COMPOSED{class}{$new_name};
234
141b507a 235 foreach my $role (@roles) {
236 $me->_inhale_if_moose($role);
237 }
a84066c7 238
64284a1b 239 my $m;
e9290d4a 240 if ($INC{"Moo.pm"}
241 and $m = Moo->_accessor_maker_for($superclass)
64284a1b 242 and ref($m) ne 'Method::Generate::Accessor') {
243 # old fashioned way time.
244 *{_getglob("${new_name}::ISA")} = [ $superclass ];
245 $me->apply_roles_to_package($new_name, @roles);
246 return $new_name;
247 }
248
faa9ce11 249 require Sub::Quote;
d245e471 250
251 $me->SUPER::create_class_with_roles($superclass, @roles);
252
253 foreach my $role (@roles) {
5d4eb6e9 254 die "${role} is not a Role::Tiny" unless $INFO{$role};
d245e471 255 }
256
c69190f1 257 $Moo::MAKERS{$new_name} = {};
258
5d4eb6e9 259 $me->_handle_constructor($new_name, $_) for @roles;
d245e471 260
261 return $new_name;
262}
263
fe0d87fb 264sub apply_roles_to_object {
265 my ($me, $object, @roles) = @_;
266 my $new = $me->SUPER::apply_roles_to_object($object, @roles);
fe0d87fb 267
1e84d6ac 268 my $apply_defaults = $APPLY_DEFAULTS{ref $new} ||= do {
fe0d87fb 269 my %attrs = map { @{$INFO{$_}{attributes}||[]} } @roles;
270
1e84d6ac 271 if ($INC{'Moo.pm'}
272 and keys %attrs
273 and my $con_gen = Moo->_constructor_maker_for(ref $new)
274 and my $m = Moo->_accessor_maker_for(ref $new)) {
275 require Sub::Quote;
276
277 my $specs = $con_gen->all_attribute_specs;
278
279 my $assign = '';
280 my %captures;
281 foreach my $name ( keys %attrs ) {
282 my $spec = $specs->{$name};
283 if ($m->has_eager_default($name, $spec)) {
284 my ($has, $has_cap)
285 = $m->generate_simple_has('$_[0]', $name, $spec);
286 my ($code, $pop_cap)
287 = $m->generate_use_default('$_[0]', $name, $spec, $has);
288
289 $assign .= $code;
290 @captures{keys %$has_cap, keys %$pop_cap}
291 = (values %$has_cap, values %$pop_cap);
292 }
fe0d87fb 293 }
1e84d6ac 294 Sub::Quote::quote_sub($assign, \%captures);
fe0d87fb 295 }
1e84d6ac 296 else {
297 sub {};
298 }
299 };
300 $new->$apply_defaults;
fe0d87fb 301 return $new;
302}
303
a84066c7 304sub _composable_package_for {
305 my ($self, $role) = @_;
306 my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
307 return $composed_name if $Role::Tiny::COMPOSED{role}{$composed_name};
5d4eb6e9 308 $self->_make_accessors_if_moose($composed_name, $role);
a84066c7 309 $self->SUPER::_composable_package_for($role);
310}
311
dccea57d 312sub _install_single_modifier {
313 my ($me, @args) = @_;
314 _install_modifier(@args);
d245e471 315}
316
317sub _handle_constructor {
5d4eb6e9 318 my ($me, $to, $role) = @_;
319 my $attr_info = $INFO{$role} && $INFO{$role}{attributes};
57d402ef 320 return unless $attr_info && @$attr_info;
d245e471 321 if ($INFO{$to}) {
57d402ef 322 push @{$INFO{$to}{attributes}||=[]}, @$attr_info;
d245e471 323 } else {
324 # only fiddle with the constructor if the target is a Moo class
325 if ($INC{"Moo.pm"}
8dee08c1 326 and my $con = Moo->_constructor_maker_for($to)) {
a41e15c3 327 # shallow copy of the specs since the constructor will assign an index
57d402ef 328 $con->register_attribute_specs(map ref() ? { %$_ } : $_, @$attr_info);
d245e471 329 }
330 }
331}
332
3331;
bce933ec 334
0b6e5fff 335=head1 NAME
336
337Moo::Role - Minimal Object Orientation support for Roles
bce933ec 338
339=head1 SYNOPSIS
340
341 package My::Role;
342
343 use Moo::Role;
344
345 sub foo { ... }
346
347 sub bar { ... }
348
349 has baz => (
350 is => 'ro',
351 );
352
353 1;
354
52e8f144 355And elsewhere:
bce933ec 356
357 package Some::Class;
358
359 use Moo;
360
361 # bar gets imported, but not foo
362 with('My::Role');
363
364 sub foo { ... }
365
366 1;
367
368=head1 DESCRIPTION
369
370C<Moo::Role> builds upon L<Role::Tiny>, so look there for most of the
371documentation on how this works. The main addition here is extra bits to make
372the roles more "Moosey;" which is to say, it adds L</has>.
373
374=head1 IMPORTED SUBROUTINES
375
376See L<Role::Tiny/IMPORTED SUBROUTINES> for all the other subroutines that are
377imported by this module.
378
379=head2 has
380
381 has attr => (
382 is => 'ro',
383 );
384
385Declares an attribute for the class to be composed into. See
386L<Moo/has> for all options.
40f3e3aa 387
072d158f 388=head1 SUPPORT
389
1108b2e2 390See L<Moo> for support and contact information.
072d158f 391
40f3e3aa 392=head1 AUTHORS
393
394See L<Moo> for authors.
395
396=head1 COPYRIGHT AND LICENSE
397
398See L<Moo> for the copyright and license.