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