fix bug where constants containing a reference weren't handled correctly
[gitmo/Role-Tiny.git] / lib / Role / Tiny.pm
CommitLineData
ab3370e7 1package Role::Tiny;
2
119014a7 3sub _getglob { \*{$_[0]} }
5e03b55c 4sub _getstash { \%{"$_[0]::"} }
119014a7 5
b1eebd55 6use strict;
7use warnings FATAL => 'all';
ab3370e7 8
9our %INFO;
10our %APPLIED_TO;
1947330a 11our %COMPOSED;
ab3370e7 12
5e03b55c 13# inlined from Moo::_Utils - update that first.
14
fb5074f6 15sub _load_module {
fb5074f6 16 (my $proto = $_[0]) =~ s/::/\//g;
5e03b55c 17 return 1 if $INC{"${proto}.pm"};
18 # can't just ->can('can') because a sub-package Foo::Bar::Baz
19 # creates a 'Baz::' key in Foo::Bar's symbol table
20 return 1 if grep !/::$/, keys %{_getstash($_[0])||{}};
59812c87 21 { local $@; require "${proto}.pm"; }
fb5074f6 22 return 1;
23}
24
ab3370e7 25sub import {
26 my $target = caller;
a1164a0b 27 my $me = shift;
de3d4906 28 strictures->import;
1ba11455 29 return if $INFO{$target}; # already exported into this package
ab3370e7 30 # get symbol table reference
31 my $stash = do { no strict 'refs'; \%{"${target}::"} };
32 # install before/after/around subs
33 foreach my $type (qw(before after around)) {
5a247406 34 *{_getglob "${target}::${type}"} = sub {
59812c87 35 { local $@; require Class::Method::Modifiers; }
ab3370e7 36 push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
37 };
38 }
5a247406 39 *{_getglob "${target}::requires"} = sub {
ab3370e7 40 push @{$INFO{$target}{requires}||=[]}, @_;
41 };
5a247406 42 *{_getglob "${target}::with"} = sub {
43 die "Only one role supported at a time by with" if @_ > 1;
369a4c50 44 $me->apply_role_to_package($target, $_[0]);
96d3f07a 45 };
2f57f81a 46 # grab all *non-constant* (ref eq 'SCALAR'/'REF') subs present
ab3370e7 47 # in the symbol table and store their refaddrs (no need to forcibly
48 # inflate constant subs into real subs) - also add '' to here (this
49 # is used later)
50 @{$INFO{$target}{not_methods}={}}{
2f57f81a 51 '', map { *$_{CODE}||() } grep !(ref =~ /^(?:SCALAR|REF)$/), values %$stash
ab3370e7 52 } = ();
53 # a role does itself
54 $APPLIED_TO{$target} = { $target => undef };
55}
56
57sub apply_role_to_package {
369a4c50 58 my ($me, $to, $role) = @_;
1947330a 59
fb5074f6 60 _load_module($role);
61
ab3370e7 62 die "This is apply_role_to_package" if ref($to);
1947330a 63 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
64
65 $me->_check_requires($to, $role, @{$info->{requires}||[]});
66
67 $me->_install_methods($to, $role);
68
69 $me->_install_modifiers($to, $info->{modifiers});
70
71 # only add does() method to classes and only if they don't have one
72 if (not $INFO{$to} and not $to->can('does')) {
73 *{_getglob "${to}::does"} = \&does_role;
74 }
75
1947330a 76 # copy our role list into the target's
77 @{$APPLIED_TO{$to}||={}}{keys %{$APPLIED_TO{$role}}} = ();
78}
79
80sub apply_roles_to_object {
81 my ($me, $object, @roles) = @_;
82 die "No roles supplied!" unless @roles;
83 my $class = ref($object);
84 bless($object, $me->create_class_with_roles($class, @roles));
85 $object;
86}
87
88sub create_class_with_roles {
89 my ($me, $superclass, @roles) = @_;
90
fb5074f6 91 die "No roles supplied!" unless @roles;
92
c69190f1 93 my $new_name = join(
94 '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
95 );
96
1947330a 97 return $new_name if $COMPOSED{class}{$new_name};
98
99 foreach my $role (@roles) {
fb5074f6 100 _load_module($role);
1947330a 101 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
102 }
103
786e5ba0 104 if ($] >= 5.010) {
59812c87 105 { local $@; require mro; }
b1eebd55 106 } else {
59812c87 107 { local $@; require MRO::Compat; }
b1eebd55 108 }
1947330a 109
110 my @composable = map $me->_composable_package_for($_), reverse @roles;
111
112 *{_getglob("${new_name}::ISA")} = [ @composable, $superclass ];
113
114 my @info = map +($INFO{$_} ? $INFO{$_} : ()), @roles;
115
116 $me->_check_requires(
117 $new_name, $compose_name,
118 do { my %h; @h{map @{$_->{requires}||[]}, @info} = (); keys %h }
119 );
1947330a 120
121 *{_getglob "${new_name}::does"} = \&does_role unless $new_name->can('does');
122
123 @{$APPLIED_TO{$new_name}||={}}{
124 map keys %{$APPLIED_TO{$_}}, @roles
125 } = ();
126
127 $COMPOSED{class}{$new_name} = 1;
128 return $new_name;
129}
130
131sub _composable_package_for {
132 my ($me, $role) = @_;
133 my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
134 return $composed_name if $COMPOSED{role}{$composed_name};
135 $me->_install_methods($composed_name, $role);
136 my $base_name = $composed_name.'::_BASE';
137 *{_getglob("${composed_name}::ISA")} = [ $base_name ];
138 my $modifiers = $INFO{$role}{modifiers}||[];
b1eebd55 139 my @mod_base;
1947330a 140 foreach my $modified (
141 do { my %h; @h{map $_->[1], @$modifiers} = (); keys %h }
142 ) {
b1eebd55 143 push @mod_base, "sub ${modified} { shift->next::method(\@_) }";
1947330a 144 }
59812c87 145 {
146 local $@;
147 eval(my $code = join "\n", "package ${base_name};", @mod_base);
148 die "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
149 }
1947330a 150 $me->_install_modifiers($composed_name, $modifiers);
151 $COMPOSED{role}{$composed_name} = 1;
152 return $composed_name;
153}
154
155sub _check_requires {
156 my ($me, $to, $name, @requires) = @_;
157 if (my @requires_fail = grep !$to->can($_), @requires) {
158 # role -> role, add to requires, role -> class, error out
159 if (my $to_info = $INFO{$to}) {
160 push @{$to_info->{requires}||=[]}, @requires_fail;
161 } else {
162 die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
163 }
164 }
165}
166
4db3a740 167sub _concrete_methods_of {
168 my ($me, $role) = @_;
1947330a 169 my $info = $INFO{$role};
4db3a740 170 $info->{methods} ||= do {
ab3370e7 171 # grab role symbol table
172 my $stash = do { no strict 'refs'; \%{"${role}::"}};
173 my $not_methods = $info->{not_methods};
174 +{
175 # grab all code entries that aren't in the not_methods list
176 map {
934ea2c1 177 my $code = *{$stash->{$_}}{CODE};
178 # rely on the '' key we added in import for "no code here"
179 exists $not_methods->{$code||''} ? () : ($_ => $code)
2f57f81a 180 } grep !(ref($stash->{$_}) =~ /^(?:SCALAR|REF)$/), keys %$stash
ab3370e7 181 };
182 };
4db3a740 183}
184
185sub methods_provided_by {
186 my ($me, $role) = @_;
187 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
188 (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
189}
190
191sub _install_methods {
192 my ($me, $to, $role) = @_;
193
194 my $info = $INFO{$role};
195
196 my $methods = $me->_concrete_methods_of($role);
1947330a 197
ab3370e7 198 # grab target symbol table
199 my $stash = do { no strict 'refs'; \%{"${to}::"}};
1947330a 200
ab3370e7 201 # determine already extant methods of target
202 my %has_methods;
203 @has_methods{grep
2f57f81a 204 +((ref($stash->{$_}) =~ /^(?:SCALAR|REF)$/) || (*{$stash->{$_}}{CODE})),
ab3370e7 205 keys %$stash
206 } = ();
ab3370e7 207
1947330a 208 foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
ab3370e7 209 no warnings 'once';
5a247406 210 *{_getglob "${to}::${i}"} = $methods->{$i};
ab3370e7 211 }
1947330a 212}
ab3370e7 213
1947330a 214sub _install_modifiers {
215 my ($me, $to, $modifiers) = @_;
dccea57d 216 if (my $info = $INFO{$to}) {
217 push @{$info->{modifiers}}, @{$modifiers||[]};
218 } else {
219 foreach my $modifier (@{$modifiers||[]}) {
220 $me->_install_single_modifier($to, @$modifier);
221 }
96d3f07a 222 }
ab3370e7 223}
224
dccea57d 225sub _install_single_modifier {
226 my ($me, @args) = @_;
227 Class::Method::Modifiers::install_modifier(@args);
228}
229
ab3370e7 230sub does_role {
390ac406 231 my ($proto, $role) = @_;
232 return exists $APPLIED_TO{ref($proto)||$proto}{$role};
ab3370e7 233}
234
2351;
5febcf4d 236
0b6e5fff 237=head1 NAME
238
239Role::Tiny - Roles. Like a nouvelle cusine portion size slice of Moose.
5febcf4d 240
241=head1 SYNOPSIS
242
243 package Some::Role;
244
245 use Role::Tiny;
246
247 sub foo { ... }
248
249 sub bar { ... }
250
251 1;
252
253else where
254
255 package Some::Class;
256
a1164a0b 257 use Role::Tiny::With;
5febcf4d 258
259 # bar gets imported, but not foo
a1164a0b 260 with 'Some::Role';
5febcf4d 261
262 sub foo { ... }
263
264 1;
265
266=head1 DESCRIPTION
267
268C<Role::Tiny> is a minimalist role composition tool.
269
270=head1 ROLE COMPOSITION
271
272Role composition can be thought of as much more clever and meaningful multiple
273inheritance. The basics of this implementation of roles is:
274
275=over 2
276
277=item *
278
279If a method is already defined on a class, that method will not be composed in
280from the role.
281
282=item *
283
284If a method that the role L</requires> to be implemented is not implemented,
285role application will fail loudly.
286
0d39f9d3 287=back
288
5febcf4d 289Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
290composition is the other way around, where first wins. In a more complete
291system (see L<Moose>) roles are checked to see if they clash. The goal of this
292is to be much simpler, hence disallowing composition of multiple roles at once.
293
294=head1 METHODS
295
296=head2 apply_role_to_package
297
369a4c50 298 Role::Tiny->apply_role_to_package('Some::Package', 'Some::Role');
5febcf4d 299
a1164a0b 300Composes role with package. See also L<Role::Tiny::With>.
5febcf4d 301
302=head2 apply_roles_to_object
303
304 Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
305
306Composes roles in order into object directly. Object is reblessed into the
307resulting class.
308
309=head2 create_class_with_roles
310
311 Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
312
313Creates a new class based on base, with the roles composed into it in order.
314New class is returned.
315
54e4000d 316=head1 SUBROUTINES
5febcf4d 317
318=head2 does_role
319
54e4000d 320 if (Role::Tiny::does_role($foo, 'Some::Role')) {
5febcf4d 321 ...
322 }
323
324Returns true if class has been composed with role.
325
54e4000d 326This subroutine is also installed as ->does on any class a Role::Tiny is
327composed into unless that class already has an ->does method, so
328
329 if ($foo->does_role('Some::Role')) {
330 ...
331 }
332
333will work for classes but to test a role, one must use ::does_role directly
334
5febcf4d 335=head1 IMPORTED SUBROUTINES
336
337=head2 requires
338
339 requires qw(foo bar);
340
341Declares a list of methods that must be defined to compose role.
342
343=head2 with
344
345 with 'Some::Role1';
346 with 'Some::Role2';
347
348Composes another role into the current role. Only one role may be composed in
349at a time to allow the code to remain as simple as possible.
350
351=head2 before
352
353 before foo => sub { ... };
354
355See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
356documentation.
357
358=head2 around
359
360 around foo => sub { ... };
361
362See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
363documentation.
364
365=head2 after
366
367 after foo => sub { ... };
368
369See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
370documentation.
371
40f3e3aa 372=head1 AUTHORS
373
374See L<Moo> for authors.
375
376=head1 COPYRIGHT AND LICENSE
377
378See L<Moo> for the copyright and license.
379
380=cut