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