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