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