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