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