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