fix compatibility with subclasses that override apply_single_role_to_package
[gitmo/Role-Tiny.git] / lib / Role / Tiny.pm
1 package Role::Tiny;
2
3 sub _getglob { \*{$_[0]} }
4 sub _getstash { \%{"$_[0]::"} }
5
6 use strict;
7 use warnings FATAL => 'all';
8
9 our $VERSION = '1.002005'; # 1.2.5
10 $VERSION = eval $VERSION;
11
12 our %INFO;
13 our %APPLIED_TO;
14 our %COMPOSED;
15 our %COMPOSITE_INFO;
16
17 # Module state workaround totally stolen from Zefram's Module::Runtime.
18
19 BEGIN {
20   *_WORK_AROUND_BROKEN_MODULE_STATE = "$]" < 5.009 ? sub(){1} : sub(){0};
21 }
22
23 sub Role::Tiny::__GUARD__::DESTROY {
24   delete $INC{$_[0]->[0]} if @{$_[0]};
25 }
26
27 sub _load_module {
28   (my $proto = $_[0]) =~ s/::/\//g;
29   $proto .= '.pm';
30   return 1 if $INC{$proto};
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])||{}};
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;
38   return 1;
39 }
40
41 sub import {
42   my $target = caller;
43   my $me = shift;
44   strict->import;
45   warnings->import(FATAL => 'all');
46   return if $INFO{$target}; # already exported into this package
47   $INFO{$target}{is_role} = 1;
48   # get symbol table reference
49   my $stash = _getstash($target);
50   # install before/after/around subs
51   foreach my $type (qw(before after around)) {
52     *{_getglob "${target}::${type}"} = sub {
53       require Class::Method::Modifiers;
54       push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
55       return;
56     };
57   }
58   *{_getglob "${target}::requires"} = sub {
59     push @{$INFO{$target}{requires}||=[]}, @_;
60     return;
61   };
62   *{_getglob "${target}::with"} = sub {
63     $me->apply_roles_to_package($target, @_);
64     return;
65   };
66   # grab all *non-constant* (stash slot is not a scalarref) subs present
67   # in the symbol table and store their refaddrs (no need to forcibly
68   # inflate constant subs into real subs) with a map to the coderefs in
69   # case of copying or re-use
70   my @not_methods = (map { *$_{CODE}||() } grep !ref($_), values %$stash);
71   @{$INFO{$target}{not_methods}={}}{@not_methods} = @not_methods;
72   # a role does itself
73   $APPLIED_TO{$target} = { $target => undef };
74 }
75
76 sub role_application_steps {
77   qw(_install_methods _install_modifiers _check_requires _copy_applied_list);
78 }
79
80 sub apply_single_role_to_package {
81   my ($me, $to, $role) = @_;
82   return if our $SKIP_APPLY;
83
84   _load_module($role);
85
86   die "This is apply_role_to_package" if ref($to);
87   die "${role} is not a Role::Tiny" unless $INFO{$role};
88
89   foreach my $step ($me->role_application_steps) {
90     $me->$step($to, $role);
91   }
92 }
93
94 sub _copy_applied_list {
95   my ($me, $to, $role) = @_;
96   # copy our role list into the target's
97   @{$APPLIED_TO{$to}||={}}{keys %{$APPLIED_TO{$role}}} = ();
98 }
99
100 sub apply_roles_to_object {
101   my ($me, $object, @roles) = @_;
102   die "No roles supplied!" unless @roles;
103   my $class = ref($object);
104   bless($object, $me->create_class_with_roles($class, @roles));
105   $object;
106 }
107
108 sub create_class_with_roles {
109   my ($me, $superclass, @roles) = @_;
110
111   die "No roles supplied!" unless @roles;
112
113   _load_module($superclass);
114   {
115     my %seen;
116     $seen{$_}++ for @roles;
117     if (my @dupes = grep $seen{$_} > 1, @roles) {
118       die "Duplicated roles: ".join(', ', @dupes);
119     }
120   }
121
122   my $new_name = join(
123     '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
124   );
125
126   return $new_name if $COMPOSED{class}{$new_name};
127
128   foreach my $role (@roles) {
129     _load_module($role);
130     die "${role} is not a Role::Tiny" unless $INFO{$role};
131   }
132
133   if ($] >= 5.010) {
134     require mro;
135   } else {
136     require MRO::Compat;
137   }
138
139   my %conflicts = %{$me->_composite_info_for(@roles)->{conflicts}};
140   if (keys %conflicts) {
141     my $fail = 
142       join "\n",
143         map {
144           "Method name conflict for '$_' between roles "
145           ."'".join(' and ', sort values %{$conflicts{$_}})."'"
146           .", cannot apply these simultaneously to an object."
147         } keys %conflicts;
148     die $fail;
149   }
150
151   my @composable = map $me->_composable_package_for($_), reverse @roles;
152
153   *{_getglob("${new_name}::ISA")} = [ @composable, $superclass ];
154
155   my @info = map $INFO{$_}, @roles;
156
157   $me->_check_requires(
158     $new_name, $compose_name,
159     do { my %h; @h{map @{$_->{requires}||[]}, @info} = (); keys %h }
160   );
161
162   @{$APPLIED_TO{$new_name}||={}}{
163     map keys %{$APPLIED_TO{$_}}, @roles
164   } = ();
165
166   $COMPOSED{class}{$new_name} = 1;
167   return $new_name;
168 }
169
170 # preserved for compat, and apply_roles_to_package calls it to allow an
171 # updated Role::Tiny to use a non-updated Moo::Role
172
173 sub apply_role_to_package { shift->apply_single_role_to_package(@_) }
174
175 sub apply_roles_to_package {
176   my ($me, $to, @roles) = @_;
177
178   return $me->apply_role_to_package($to, $roles[0]) if @roles == 1;
179
180   my %conflicts = %{$me->_composite_info_for(@roles)->{conflicts}};
181   delete $conflicts{$_} for keys %{ $me->_concrete_methods_of($to) };
182   if (keys %conflicts) {
183     my $fail = 
184       join "\n",
185         map {
186           "Due to a method name conflict between roles "
187           ."'".join(' and ', sort values %{$conflicts{$_}})."'"
188           .", the method '$_' must be implemented by '${to}'"
189         } keys %conflicts;
190     die $fail;
191   }
192
193   # the if guard here is essential since otherwise we accidentally create
194   # a $INFO for something that isn't a Role::Tiny (or Moo::Role) because
195   # autovivification hates us and wants us to die()
196   if ($INFO{$to}) {
197     delete $INFO{$to}{methods}; # reset since we're about to add methods
198   }
199   foreach my $step ($me->role_application_steps) {
200     foreach my $role (@roles) {
201       $me->$step($to, $role);
202     }
203   }
204   # backcompat: allow subclasses to use apply_single_role_to_package
205   # to apply changes.  set a local var so ours does nothing.
206   local our $SKIP_APPLY = 1;
207   foreach my $role (@roles) {
208     $me->apply_single_role_to_package($to, $role);
209   }
210   $APPLIED_TO{$to}{join('|',@roles)} = 1;
211 }
212
213 sub _composite_info_for {
214   my ($me, @roles) = @_;
215   $COMPOSITE_INFO{join('|', sort @roles)} ||= do {
216     foreach my $role (@roles) {
217       _load_module($role);
218     }
219     my %methods;
220     foreach my $role (@roles) {
221       my $this_methods = $me->_concrete_methods_of($role);
222       $methods{$_}{$this_methods->{$_}} = $role for keys %$this_methods;
223     }
224     delete $methods{$_} for grep keys(%{$methods{$_}}) == 1, keys %methods;
225     +{ conflicts => \%methods }
226   };
227 }
228
229 sub _composable_package_for {
230   my ($me, $role) = @_;
231   my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
232   return $composed_name if $COMPOSED{role}{$composed_name};
233   $me->_install_methods($composed_name, $role);
234   my $base_name = $composed_name.'::_BASE';
235   # Not using _getglob, since setting @ISA via the typeglob breaks
236   # inheritance on 5.10.0 if the stash has previously been accessed an
237   # then a method called on the class (in that order!), which
238   # ->_install_methods (with the help of ->_install_does) ends up doing.
239   { no strict 'refs'; @{"${composed_name}::ISA"} = ( $base_name ); }
240   my $modifiers = $INFO{$role}{modifiers}||[];
241   my @mod_base;
242   foreach my $modified (
243     do { my %h; @h{map $_->[1], @$modifiers} = (); keys %h }
244   ) {
245     push @mod_base, "sub ${modified} { shift->next::method(\@_) }";
246   }
247   my $e;
248   {
249     local $@;
250     eval(my $code = join "\n", "package ${base_name};", @mod_base);
251     $e = "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
252   }
253   die $e if $e;
254   $me->_install_modifiers($composed_name, $role);
255   $COMPOSED{role}{$composed_name} = 1;
256   return $composed_name;
257 }
258
259 sub _check_requires {
260   my ($me, $to, $name) = @_;
261   return unless my @requires = @{$INFO{$name}{requires}||[]};
262   if (my @requires_fail = grep !$to->can($_), @requires) {
263     # role -> role, add to requires, role -> class, error out
264     if (my $to_info = $INFO{$to}) {
265       push @{$to_info->{requires}||=[]}, @requires_fail;
266     } else {
267       die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
268     }
269   }
270 }
271
272 sub _concrete_methods_of {
273   my ($me, $role) = @_;
274   my $info = $INFO{$role};
275   # grab role symbol table
276   my $stash = _getstash($role);
277   # reverse so our keys become the values (captured coderefs) in case
278   # they got copied or re-used since
279   my $not_methods = { reverse %{$info->{not_methods}||{}} };
280   $info->{methods} ||= +{
281     # grab all code entries that aren't in the not_methods list
282     map {
283       my $code = *{$stash->{$_}}{CODE};
284       ( ! $code or exists $not_methods->{$code} ) ? () : ($_ => $code)
285     } grep !ref($stash->{$_}), keys %$stash
286   };
287 }
288
289 sub methods_provided_by {
290   my ($me, $role) = @_;
291   die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
292   (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
293 }
294
295 sub _install_methods {
296   my ($me, $to, $role) = @_;
297
298   my $info = $INFO{$role};
299
300   my $methods = $me->_concrete_methods_of($role);
301
302   # grab target symbol table
303   my $stash = _getstash($to);
304
305   # determine already extant methods of target
306   my %has_methods;
307   @has_methods{grep
308     +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
309     keys %$stash
310   } = ();
311
312   foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
313     no warnings 'once';
314     *{_getglob "${to}::${i}"} = $methods->{$i};
315   }
316   
317   $me->_install_does($to);
318 }
319
320 sub _install_modifiers {
321   my ($me, $to, $name) = @_;
322   return unless my $modifiers = $INFO{$name}{modifiers};
323   if (my $info = $INFO{$to}) {
324     push @{$info->{modifiers}}, @{$modifiers||[]};
325   } else {
326     foreach my $modifier (@{$modifiers||[]}) {
327       $me->_install_single_modifier($to, @$modifier);
328     }
329   }
330 }
331
332 my $vcheck_error;
333
334 sub _install_single_modifier {
335   my ($me, @args) = @_;
336   defined($vcheck_error) or $vcheck_error = do {
337     local $@;
338     eval { Class::Method::Modifiers->VERSION(1.05); 1 }
339       ? 0
340       : $@
341   };
342   $vcheck_error and die $vcheck_error;
343   Class::Method::Modifiers::install_modifier(@args);
344 }
345
346 my $FALLBACK = sub { 0 };
347 sub _install_does {
348   my ($me, $to) = @_;
349   
350   # only add does() method to classes
351   return if $INFO{$to};
352   
353   # add does() only if they don't have one
354   *{_getglob "${to}::does"} = \&does_role unless $to->can('does');
355   
356   return if ($to->can('DOES') and $to->can('DOES') != (UNIVERSAL->can('DOES') || 0));
357   
358   my $existing = $to->can('DOES') || $to->can('isa') || $FALLBACK;
359   my $new_sub = sub {
360     my ($proto, $role) = @_;
361     Role::Tiny::does_role($proto, $role) or $proto->$existing($role);
362   };
363   no warnings 'redefine';
364   *{_getglob "${to}::DOES"} = $new_sub;
365 }
366
367 sub does_role {
368   my ($proto, $role) = @_;
369   if ($] >= 5.010) {
370     require mro;
371   } else {
372     require MRO::Compat;
373   }
374   foreach my $class (@{mro::get_linear_isa(ref($proto)||$proto)}) {
375     return 1 if exists $APPLIED_TO{$class}{$role};
376   }
377   return 0;
378 }
379
380 sub is_role {
381   my ($me, $role) = @_;
382   return !!$INFO{$role};
383 }
384
385 1;
386
387 =encoding utf-8
388
389 =head1 NAME
390
391 Role::Tiny - Roles. Like a nouvelle cuisine portion size slice of Moose.
392
393 =head1 SYNOPSIS
394
395  package Some::Role;
396
397  use Role::Tiny;
398
399  sub foo { ... }
400
401  sub bar { ... }
402
403  around baz => sub { ... }
404
405  1;
406
407 else where
408
409  package Some::Class;
410
411  use Role::Tiny::With;
412
413  # bar gets imported, but not foo
414  with 'Some::Role';
415
416  sub foo { ... }
417
418  # baz is wrapped in the around modifier by Class::Method::Modifiers
419  sub baz { ... }
420
421  1;
422
423 If you wanted attributes as well, look at L<Moo::Role>.
424
425 =head1 DESCRIPTION
426
427 C<Role::Tiny> is a minimalist role composition tool.
428
429 =head1 ROLE COMPOSITION
430
431 Role composition can be thought of as much more clever and meaningful multiple
432 inheritance.  The basics of this implementation of roles is:
433
434 =over 2
435
436 =item *
437
438 If a method is already defined on a class, that method will not be composed in
439 from the role.
440
441 =item *
442
443 If a method that the role L</requires> to be implemented is not implemented,
444 role application will fail loudly.
445
446 =back
447
448 Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
449 composition is the other way around, where the class wins. If multiple roles
450 are applied in a single call (single with statement), then if any of their
451 provided methods clash, an exception is raised unless the class provides
452 a method since this conflict indicates a potential problem.
453
454 =head1 IMPORTED SUBROUTINES
455
456 =head2 requires
457
458  requires qw(foo bar);
459
460 Declares a list of methods that must be defined to compose role.
461
462 =head2 with
463
464  with 'Some::Role1';
465
466  with 'Some::Role1', 'Some::Role2';
467
468 Composes another role into the current role (or class via L<Role::Tiny::With>).
469
470 If you have conflicts and want to resolve them in favour of Some::Role1 you
471 can instead write: 
472
473  with 'Some::Role1';
474  with 'Some::Role2';
475
476 If you have conflicts and want to resolve different conflicts in favour of
477 different roles, please refactor your codebase.
478
479 =head2 before
480
481  before foo => sub { ... };
482
483 See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
484 documentation.
485
486 Note that since you are not required to use method modifiers,
487 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
488 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
489 both L<Class::Method::Modifiers> and L<Role::Tiny>.
490
491 =head2 around
492
493  around foo => sub { ... };
494
495 See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
496 documentation.
497
498 Note that since you are not required to use method modifiers,
499 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
500 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
501 both L<Class::Method::Modifiers> and L<Role::Tiny>.
502
503 =head2 after
504
505  after foo => sub { ... };
506
507 See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
508 documentation.
509
510 Note that since you are not required to use method modifiers,
511 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
512 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
513 both L<Class::Method::Modifiers> and L<Role::Tiny>.
514
515 =head1 SUBROUTINES
516
517 =head2 does_role
518
519  if (Role::Tiny::does_role($foo, 'Some::Role')) {
520    ...
521  }
522
523 Returns true if class has been composed with role.
524
525 This subroutine is also installed as ->does on any class a Role::Tiny is
526 composed into unless that class already has an ->does method, so
527
528   if ($foo->does('Some::Role')) {
529     ...
530   }
531
532 will work for classes but to test a role, one must use ::does_role directly.
533
534 Additionally, Role::Tiny will override the standard Perl C<DOES> method
535 for your class. However, if C<any> class in your class' inheritance
536 hierarchy provides C<DOES>, then Role::Tiny will not override it.
537
538 =head1 METHODS
539
540 =head2 apply_roles_to_package
541
542  Role::Tiny->apply_roles_to_package(
543    'Some::Package', 'Some::Role', 'Some::Other::Role'
544  );
545
546 Composes role with package.  See also L<Role::Tiny::With>.
547
548 =head2 apply_roles_to_object
549
550  Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
551
552 Composes roles in order into object directly.  Object is reblessed into the
553 resulting class.
554
555 =head2 create_class_with_roles
556
557  Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
558
559 Creates a new class based on base, with the roles composed into it in order.
560 New class is returned.
561
562 =head2 is_role
563
564  Role::Tiny->is_role('Some::Role1')
565
566 Returns true if the given package is a role.
567
568 =head1 SEE ALSO
569
570 L<Role::Tiny> is the attribute-less subset of L<Moo::Role>; L<Moo::Role> is
571 a meta-protocol-less subset of the king of role systems, L<Moose::Role>.
572
573 If you don't want method modifiers and do want to be forcibly restricted
574 to a single role application per class, Ovid's L<Role::Basic> exists. But
575 Stevan Little (the L<Moose> author) and I don't find the additional
576 restrictions to be amazingly helpful in most cases; L<Role::Basic>'s choices
577 are more a guide to what you should prefer doing, to our mind, rather than
578 something that needs to be enforced.
579
580 =head1 AUTHOR
581
582 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
583
584 =head1 CONTRIBUTORS
585
586 dg - David Leadbeater (cpan:DGL) <dgl@dgl.cx>
587
588 frew - Arthur Axel "fREW" Schmidt (cpan:FREW) <frioux@gmail.com>
589
590 hobbs - Andrew Rodland (cpan:ARODLAND) <arodland@cpan.org>
591
592 jnap - John Napiorkowski (cpan:JJNAPIORK) <jjn1056@yahoo.com>
593
594 ribasushi - Peter Rabbitson (cpan:RIBASUSHI) <ribasushi@cpan.org>
595
596 chip - Chip Salzenberg (cpan:CHIPS) <chip@pobox.com>
597
598 ajgb - Alex J. G. Burzyński (cpan:AJGB) <ajgb@cpan.org>
599
600 doy - Jesse Luehrs (cpan:DOY) <doy at tozt dot net>
601
602 perigrin - Chris Prather (cpan:PERIGRIN) <chris@prather.org>
603
604 Mithaldu - Christian Walde (cpan:MITHALDU) <walde.christian@googlemail.com>
605
606 ilmari - Dagfinn Ilmari Mannsåker (cpan:ILMARI) <ilmari@ilmari.org>
607
608 tobyink - Toby Inkster (cpan:TOBYINK) <tobyink@cpan.org>
609
610 =head1 COPYRIGHT
611
612 Copyright (c) 2010-2012 the Role::Tiny L</AUTHOR> and L</CONTRIBUTORS>
613 as listed above.
614
615 =head1 LICENSE
616
617 This library is free software and may be distributed under the same terms
618 as perl itself.
619
620 =cut