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