clean up composition handling
[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
e2722751 9our $VERSION = '1.000001'; # 1.0.1
c334a5c1 10$VERSION = eval $VERSION;
11
ab3370e7 12our %INFO;
13our %APPLIED_TO;
1947330a 14our %COMPOSED;
671b5a88 15our %UNION_INFO;
ab3370e7 16
cf62c989 17# Module state workaround totally stolen from Zefram's Module::Runtime.
18
19BEGIN {
20 *_WORK_AROUND_BROKEN_MODULE_STATE = "$]" < 5.009 ? sub(){1} : sub(){0};
21}
22
23sub Role::Tiny::__GUARD__::DESTROY {
24 delete $INC{$_[0]->[0]} if @{$_[0]};
25}
5e03b55c 26
fb5074f6 27sub _load_module {
fb5074f6 28 (my $proto = $_[0]) =~ s/::/\//g;
cf62c989 29 $proto .= '.pm';
30 return 1 if $INC{$proto};
5e03b55c 31 # can't just ->can('can') because a sub-package Foo::Bar::Baz
32 # creates a 'Baz::' key in Foo::Bar's symbol table
33 return 1 if grep !/::$/, keys %{_getstash($_[0])||{}};
cf62c989 34 my $guard = _WORK_AROUND_BROKEN_MODULE_STATE
35 && bless([ $proto ], 'Role::Tiny::__GUARD__');
36 require $proto;
37 pop @$guard if _WORK_AROUND_BROKEN_MODULE_STATE;
fb5074f6 38 return 1;
39}
40
ab3370e7 41sub import {
42 my $target = caller;
a1164a0b 43 my $me = shift;
3ca7ff56 44 strict->import;
45 warnings->import(FATAL => 'all');
1ba11455 46 return if $INFO{$target}; # already exported into this package
ab3370e7 47 # get symbol table reference
48 my $stash = do { no strict 'refs'; \%{"${target}::"} };
49 # install before/after/around subs
50 foreach my $type (qw(before after around)) {
5a247406 51 *{_getglob "${target}::${type}"} = sub {
7568ba55 52 require Class::Method::Modifiers;
ab3370e7 53 push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
54 };
55 }
5a247406 56 *{_getglob "${target}::requires"} = sub {
ab3370e7 57 push @{$INFO{$target}{requires}||=[]}, @_;
58 };
5a247406 59 *{_getglob "${target}::with"} = sub {
60dfe768 60 $me->apply_union_of_roles_to_package($target, @_);
96d3f07a 61 };
7b8177f8 62 # grab all *non-constant* (stash slot is not a scalarref) subs present
ab3370e7 63 # in the symbol table and store their refaddrs (no need to forcibly
64 # inflate constant subs into real subs) - also add '' to here (this
65 # is used later)
66 @{$INFO{$target}{not_methods}={}}{
faa9ce11 67 '', map { *$_{CODE}||() } grep !ref($_), values %$stash
ab3370e7 68 } = ();
69 # a role does itself
70 $APPLIED_TO{$target} = { $target => undef };
71}
72
73sub apply_role_to_package {
369a4c50 74 my ($me, $to, $role) = @_;
1947330a 75
fb5074f6 76 _load_module($role);
77
ab3370e7 78 die "This is apply_role_to_package" if ref($to);
1947330a 79 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
80
81 $me->_check_requires($to, $role, @{$info->{requires}||[]});
82
83 $me->_install_methods($to, $role);
84
85 $me->_install_modifiers($to, $info->{modifiers});
86
87 # only add does() method to classes and only if they don't have one
88 if (not $INFO{$to} and not $to->can('does')) {
89 *{_getglob "${to}::does"} = \&does_role;
90 }
91
1947330a 92 # copy our role list into the target's
93 @{$APPLIED_TO{$to}||={}}{keys %{$APPLIED_TO{$role}}} = ();
94}
95
96sub apply_roles_to_object {
97 my ($me, $object, @roles) = @_;
98 die "No roles supplied!" unless @roles;
99 my $class = ref($object);
100 bless($object, $me->create_class_with_roles($class, @roles));
101 $object;
102}
103
104sub create_class_with_roles {
105 my ($me, $superclass, @roles) = @_;
106
fb5074f6 107 die "No roles supplied!" unless @roles;
108
c69190f1 109 my $new_name = join(
110 '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
111 );
112
1947330a 113 return $new_name if $COMPOSED{class}{$new_name};
114
115 foreach my $role (@roles) {
fb5074f6 116 _load_module($role);
29dde8ba 117 die "${role} is not a Role::Tiny" unless $INFO{$role};
1947330a 118 }
119
786e5ba0 120 if ($] >= 5.010) {
7568ba55 121 require mro;
b1eebd55 122 } else {
7568ba55 123 require MRO::Compat;
b1eebd55 124 }
1947330a 125
126 my @composable = map $me->_composable_package_for($_), reverse @roles;
127
128 *{_getglob("${new_name}::ISA")} = [ @composable, $superclass ];
129
29dde8ba 130 my @info = map $INFO{$_}, @roles;
1947330a 131
132 $me->_check_requires(
133 $new_name, $compose_name,
134 do { my %h; @h{map @{$_->{requires}||[]}, @info} = (); keys %h }
135 );
1947330a 136
137 *{_getglob "${new_name}::does"} = \&does_role unless $new_name->can('does');
138
139 @{$APPLIED_TO{$new_name}||={}}{
140 map keys %{$APPLIED_TO{$_}}, @roles
141 } = ();
142
143 $COMPOSED{class}{$new_name} = 1;
144 return $new_name;
145}
146
60dfe768 147sub apply_union_of_roles_to_package {
148 my ($me, $to, @roles) = @_;
149
150 return $me->apply_role_to_package($to, $roles[0]) if @roles == 1;
151
671b5a88 152 my %conflicts = %{$me->_union_info_for(@roles)->{conflicts}};
153 delete $conflicts{$_} for $me->_concrete_methods_of($to);
154 if (keys %conflicts) {
60dfe768 155 my $fail =
156 join "\n",
671b5a88 157 map {
158 "Due to a method name conflict between roles "
159 ."'".join(' and ', sort values %{$conflicts{$_}})."'"
160 .", the method '$_' must be implemented by '${to}'"
161 } keys %conflicts;
162 die $fail;
60dfe768 163 }
164 $me->apply_role_to_package($to, $_) for @roles;
671b5a88 165 $APPLIED_TO{$to}{join('|',@roles)} = 1;
166}
167
168sub _union_info_for {
169 my ($me, @roles) = @_;
170 $UNION_INFO{join('|',@roles)} ||= do {
171 _load_module($_) for @roles;
172 my %methods;
173 foreach my $role (@roles) {
174 my $this_methods = $me->_concrete_methods_of($role);
175 $methods{$_}{$this_methods->{$_}} = $role for keys %$this_methods;
176 }
177 delete $methods{$_} for grep keys(%{$methods{$_}}) == 1, keys %methods;
178 +{ conflicts => \%methods }
179 };
60dfe768 180}
181
1947330a 182sub _composable_package_for {
183 my ($me, $role) = @_;
184 my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
185 return $composed_name if $COMPOSED{role}{$composed_name};
186 $me->_install_methods($composed_name, $role);
187 my $base_name = $composed_name.'::_BASE';
188 *{_getglob("${composed_name}::ISA")} = [ $base_name ];
189 my $modifiers = $INFO{$role}{modifiers}||[];
b1eebd55 190 my @mod_base;
1947330a 191 foreach my $modified (
192 do { my %h; @h{map $_->[1], @$modifiers} = (); keys %h }
193 ) {
b1eebd55 194 push @mod_base, "sub ${modified} { shift->next::method(\@_) }";
1947330a 195 }
385f5087 196 my $e;
59812c87 197 {
198 local $@;
199 eval(my $code = join "\n", "package ${base_name};", @mod_base);
385f5087 200 $e = "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
59812c87 201 }
385f5087 202 die $e if $e;
1947330a 203 $me->_install_modifiers($composed_name, $modifiers);
204 $COMPOSED{role}{$composed_name} = 1;
205 return $composed_name;
206}
207
208sub _check_requires {
209 my ($me, $to, $name, @requires) = @_;
210 if (my @requires_fail = grep !$to->can($_), @requires) {
211 # role -> role, add to requires, role -> class, error out
212 if (my $to_info = $INFO{$to}) {
213 push @{$to_info->{requires}||=[]}, @requires_fail;
214 } else {
215 die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
216 }
217 }
218}
219
4db3a740 220sub _concrete_methods_of {
221 my ($me, $role) = @_;
1947330a 222 my $info = $INFO{$role};
60dfe768 223 # grab role symbol table
224 my $stash = do { no strict 'refs'; \%{"${role}::"}};
225 my $not_methods = $info->{not_methods};
226 +{
227 # grab all code entries that aren't in the not_methods list
228 map {
229 my $code = *{$stash->{$_}}{CODE};
230 # rely on the '' key we added in import for "no code here"
231 exists $not_methods->{$code||''} ? () : ($_ => $code)
232 } grep !ref($stash->{$_}), keys %$stash
ab3370e7 233 };
4db3a740 234}
235
236sub methods_provided_by {
237 my ($me, $role) = @_;
238 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
239 (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
240}
241
242sub _install_methods {
243 my ($me, $to, $role) = @_;
244
245 my $info = $INFO{$role};
246
247 my $methods = $me->_concrete_methods_of($role);
1947330a 248
ab3370e7 249 # grab target symbol table
250 my $stash = do { no strict 'refs'; \%{"${to}::"}};
1947330a 251
ab3370e7 252 # determine already extant methods of target
253 my %has_methods;
254 @has_methods{grep
faa9ce11 255 +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
ab3370e7 256 keys %$stash
257 } = ();
ab3370e7 258
1947330a 259 foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
ab3370e7 260 no warnings 'once';
5a247406 261 *{_getglob "${to}::${i}"} = $methods->{$i};
ab3370e7 262 }
1947330a 263}
ab3370e7 264
1947330a 265sub _install_modifiers {
266 my ($me, $to, $modifiers) = @_;
dccea57d 267 if (my $info = $INFO{$to}) {
268 push @{$info->{modifiers}}, @{$modifiers||[]};
269 } else {
270 foreach my $modifier (@{$modifiers||[]}) {
271 $me->_install_single_modifier($to, @$modifier);
272 }
96d3f07a 273 }
ab3370e7 274}
275
dccea57d 276sub _install_single_modifier {
277 my ($me, @args) = @_;
278 Class::Method::Modifiers::install_modifier(@args);
279}
280
ab3370e7 281sub does_role {
390ac406 282 my ($proto, $role) = @_;
283 return exists $APPLIED_TO{ref($proto)||$proto}{$role};
ab3370e7 284}
285
2861;
5febcf4d 287
0b6e5fff 288=head1 NAME
289
70061353 290Role::Tiny - Roles. Like a nouvelle cuisine portion size slice of Moose.
5febcf4d 291
292=head1 SYNOPSIS
293
294 package Some::Role;
295
296 use Role::Tiny;
297
298 sub foo { ... }
299
300 sub bar { ... }
301
adcb6c3d 302 around baz => sub { ... }
303
5febcf4d 304 1;
305
306else where
307
308 package Some::Class;
309
a1164a0b 310 use Role::Tiny::With;
5febcf4d 311
312 # bar gets imported, but not foo
a1164a0b 313 with 'Some::Role';
5febcf4d 314
315 sub foo { ... }
316
adcb6c3d 317 # baz is wrapped in the around modifier by Class::Method::Modifiers
318 sub baz { ... }
319
5febcf4d 320 1;
321
adcb6c3d 322If you wanted attributes as well, look at L<Moo::Role>.
323
5febcf4d 324=head1 DESCRIPTION
325
326C<Role::Tiny> is a minimalist role composition tool.
327
328=head1 ROLE COMPOSITION
329
330Role composition can be thought of as much more clever and meaningful multiple
331inheritance. The basics of this implementation of roles is:
332
333=over 2
334
335=item *
336
337If a method is already defined on a class, that method will not be composed in
338from the role.
339
340=item *
341
342If a method that the role L</requires> to be implemented is not implemented,
343role application will fail loudly.
344
0d39f9d3 345=back
346
5febcf4d 347Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
348composition is the other way around, where first wins. In a more complete
349system (see L<Moose>) roles are checked to see if they clash. The goal of this
350is to be much simpler, hence disallowing composition of multiple roles at once.
351
352=head1 METHODS
353
354=head2 apply_role_to_package
355
369a4c50 356 Role::Tiny->apply_role_to_package('Some::Package', 'Some::Role');
5febcf4d 357
a1164a0b 358Composes role with package. See also L<Role::Tiny::With>.
5febcf4d 359
360=head2 apply_roles_to_object
361
362 Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
363
364Composes roles in order into object directly. Object is reblessed into the
365resulting class.
366
367=head2 create_class_with_roles
368
369 Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
370
371Creates a new class based on base, with the roles composed into it in order.
372New class is returned.
373
54e4000d 374=head1 SUBROUTINES
5febcf4d 375
376=head2 does_role
377
54e4000d 378 if (Role::Tiny::does_role($foo, 'Some::Role')) {
5febcf4d 379 ...
380 }
381
382Returns true if class has been composed with role.
383
54e4000d 384This subroutine is also installed as ->does on any class a Role::Tiny is
385composed into unless that class already has an ->does method, so
386
e4aa82b1 387 if ($foo->does('Some::Role')) {
54e4000d 388 ...
389 }
390
391will work for classes but to test a role, one must use ::does_role directly
392
5febcf4d 393=head1 IMPORTED SUBROUTINES
394
395=head2 requires
396
397 requires qw(foo bar);
398
399Declares a list of methods that must be defined to compose role.
400
401=head2 with
402
403 with 'Some::Role1';
404 with 'Some::Role2';
405
406Composes another role into the current role. Only one role may be composed in
407at a time to allow the code to remain as simple as possible.
408
409=head2 before
410
411 before foo => sub { ... };
412
413See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
414documentation.
415
adcb6c3d 416Note that since you are not required to use method modifiers,
417L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
418a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
419both L<Class::Method::Modifiers> and L<Role::Tiny>.
420
5febcf4d 421=head2 around
422
423 around foo => sub { ... };
424
425See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
426documentation.
427
adcb6c3d 428Note that since you are not required to use method modifiers,
429L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
430a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
431both L<Class::Method::Modifiers> and L<Role::Tiny>.
432
5febcf4d 433=head2 after
434
435 after foo => sub { ... };
436
437See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
438documentation.
439
adcb6c3d 440Note that since you are not required to use method modifiers,
441L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
442a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
443both L<Class::Method::Modifiers> and L<Role::Tiny>.
444
445=head1 SEE ALSO
446
447L<Role::Tiny> is the attribute-less subset of L<Moo::Role>; L<Moo::Role> is
448a meta-protocol-less subset of the king of role systems, L<Moose::Role>.
449
450If you don't want method modifiers and do want to be forcibly restricted
451to a single role application per class, Ovid's L<Role::Basic> exists. But
452Stevan Little (the L<Moose> author) and I are both still convinced that
453he's Doing It Wrong.
454
c334a5c1 455=head1 AUTHOR
456
457mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
458
459=head1 CONTRIBUTORS
460
461dg - David Leadbeater (cpan:DGL) <dgl@dgl.cx>
462
463frew - Arthur Axel "fREW" Schmidt (cpan:FREW) <frioux@gmail.com>
464
465hobbs - Andrew Rodland (cpan:ARODLAND) <arodland@cpan.org>
466
467jnap - John Napiorkowski (cpan:JJNAPIORK) <jjn1056@yahoo.com>
468
469ribasushi - Peter Rabbitson (cpan:RIBASUSHI) <ribasushi@cpan.org>
470
471chip - Chip Salzenberg (cpan:CHIPS) <chip@pobox.com>
472
473ajgb - Alex J. G. BurzyƄski (cpan:AJGB) <ajgb@cpan.org>
474
475doy - Jesse Luehrs (cpan:DOY) <doy at tozt dot net>
476
477perigrin - Chris Prather (cpan:PERIGRIN) <chris@prather.org>
478
479=head1 COPYRIGHT
40f3e3aa 480
c334a5c1 481Copyright (c) 2010-2012 the Role::Tiny L</AUTHOR> and L</CONTRIBUTORS>
482as listed above.
40f3e3aa 483
c334a5c1 484=head1 LICENSE
40f3e3aa 485
c334a5c1 486This library is free software and may be distributed under the same terms
487as perl itself.
40f3e3aa 488
489=cut