3 sub _getglob { \*{$_[0]} }
4 sub _getstash { \%{"$_[0]::"} }
7 use warnings FATAL => 'all';
9 our $VERSION = '1.003002';
10 $VERSION = eval $VERSION;
17 # Module state workaround totally stolen from Zefram's Module::Runtime.
20 *_WORK_AROUND_BROKEN_MODULE_STATE = "$]" < 5.009 ? sub(){1} : sub(){0};
21 *_MRO_MODULE = "$]" < 5.010 ? sub(){"MRO/Compat.pm"} : sub(){"mro.pm"};
24 sub Role::Tiny::__GUARD__::DESTROY {
25 delete $INC{$_[0]->[0]} if @{$_[0]};
29 (my $proto = $_[0]) =~ s/::/\//g;
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__');
38 pop @$guard if _WORK_AROUND_BROKEN_MODULE_STATE;
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 => @_ ];
59 *{_getglob "${target}::requires"} = sub {
60 push @{$INFO{$target}{requires}||=[]}, @_;
63 *{_getglob "${target}::with"} = sub {
64 $me->apply_roles_to_package($target, @_);
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;
74 $APPLIED_TO{$target} = { $target => undef };
77 sub role_application_steps {
78 qw(_install_methods _check_requires _install_modifiers _copy_applied_list);
81 sub apply_single_role_to_package {
82 my ($me, $to, $role) = @_;
86 die "This is apply_role_to_package" if ref($to);
87 die "${role} is not a Role::Tiny" unless $me->is_role($role);
89 foreach my $step ($me->role_application_steps) {
90 $me->$step($to, $role);
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}}} = ();
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));
109 my $role_suffix = 'A000';
110 sub _composite_name {
111 my ($me, $superclass, @roles) = @_;
114 '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
117 if (length($new_name) > 252) {
118 $new_name = $COMPOSED{abbrev}{$new_name}
119 ||= substr($new_name, 0, 250 - length $role_suffix).'__'.$role_suffix++;
121 return wantarray ? ($new_name, $compose_name) : $new_name;
124 sub create_class_with_roles {
125 my ($me, $superclass, @roles) = @_;
127 die "No roles supplied!" unless @roles;
129 _load_module($superclass);
132 $seen{$_}++ for @roles;
133 if (my @dupes = grep $seen{$_} > 1, @roles) {
134 die "Duplicated roles: ".join(', ', @dupes);
138 my ($new_name, $compose_name) = $me->_composite_name($superclass, @roles);
140 return $new_name if $COMPOSED{class}{$new_name};
142 foreach my $role (@roles) {
144 die "${role} is not a Role::Tiny" unless $me->is_role($role);
147 require(_MRO_MODULE);
149 my $composite_info = $me->_composite_info_for(@roles);
150 my %conflicts = %{$composite_info->{conflicts}};
151 if (keys %conflicts) {
155 "Method name conflict for '$_' between roles "
156 ."'".join(' and ', sort values %{$conflicts{$_}})."'"
157 .", cannot apply these simultaneously to an object."
162 my @composable = map $me->_composable_package_for($_), reverse @roles;
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 {
170 !grep $_->can($method) && !$COMPOSED{role}{$_}{modifiers_only}{$method},
172 } @{$composite_info->{requires}};
174 $me->_check_requires(
175 $superclass, $compose_name, \@requires
178 *{_getglob("${new_name}::ISA")} = [ @composable, $superclass ];
180 @{$APPLIED_TO{$new_name}||={}}{
181 map keys %{$APPLIED_TO{$_}}, @roles
184 $COMPOSED{class}{$new_name} = 1;
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
191 sub apply_role_to_package { shift->apply_single_role_to_package(@_) }
193 sub apply_roles_to_package {
194 my ($me, $to, @roles) = @_;
196 return $me->apply_role_to_package($to, $roles[0]) if @roles == 1;
198 my %conflicts = %{$me->_composite_info_for(@roles)->{conflicts}};
199 my @have = grep $to->can($_), keys %conflicts;
200 delete @conflicts{@have};
202 if (keys %conflicts) {
206 "Due to a method name conflict between roles "
207 ."'".join(' and ', sort values %{$conflicts{$_}})."'"
208 .", the method '$_' must be implemented by '${to}'"
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;
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()
226 delete $INFO{$to}{methods}; # reset since we're about to add methods
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
240 foreach my $role (@roles) {
241 $me->apply_single_role_to_package($to, $role);
245 foreach my $step ($me->role_application_steps) {
246 foreach my $role (@roles) {
247 $me->$step($to, $role);
251 $APPLIED_TO{$to}{join('|',@roles)} = 1;
254 sub _composite_info_for {
255 my ($me, @roles) = @_;
256 $COMPOSITE_INFO{join('|', sort @roles)} ||= do {
257 foreach my $role (@roles) {
261 foreach my $role (@roles) {
262 my $this_methods = $me->_concrete_methods_of($role);
263 $methods{$_}{$this_methods->{$_}} = $role for keys %$this_methods;
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] }
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}||[];
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(\@_) }";
296 eval(my $code = join "\n", "package ${base_name};", @mod_base);
297 $e = "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
300 $me->_install_modifiers($composed_name, $role);
301 $COMPOSED{role}{$composed_name} = {
302 modifiers_only => { map { $_ => 1 } @modifiers },
304 return $composed_name;
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;
315 die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
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
331 my $code = *{$stash->{$_}}{CODE};
332 ( ! $code or exists $not_methods->{$code} ) ? () : ($_ => $code)
333 } grep !ref($stash->{$_}), keys %$stash
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}||[]});
343 sub _install_methods {
344 my ($me, $to, $role) = @_;
346 my $info = $INFO{$role};
348 my $methods = $me->_concrete_methods_of($role);
350 # grab target symbol table
351 my $stash = _getstash($to);
353 # determine already extant methods of target
356 +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
360 foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
362 my $glob = _getglob "${to}::${i}";
363 *$glob = $methods->{$i};
365 # overloads using method names have the method stored in the scalar slot
366 # and &overload::nil in the code slot.
369 && defined &overload::nil
370 && $methods->{$i} == \&overload::nil;
372 my $overload = ${ *{_getglob "${role}::${i}"}{SCALAR} };
374 unless defined $overload;
379 $me->_install_does($to);
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||[]};
388 foreach my $modifier (@{$modifiers||[]}) {
389 $me->_install_single_modifier($to, @$modifier);
396 sub _install_single_modifier {
397 my ($me, @args) = @_;
398 defined($vcheck_error) or $vcheck_error = do {
400 eval { Class::Method::Modifiers->VERSION(1.05); 1 }
404 $vcheck_error and die $vcheck_error;
405 Class::Method::Modifiers::install_modifier(@args);
408 my $FALLBACK = sub { 0 };
412 # only add does() method to classes
413 return if $me->is_role($to);
415 # add does() only if they don't have one
416 *{_getglob "${to}::does"} = \&does_role unless $to->can('does');
419 if $to->can('DOES') and $to->can('DOES') != (UNIVERSAL->can('DOES') || 0);
421 my $existing = $to->can('DOES') || $to->can('isa') || $FALLBACK;
423 my ($proto, $role) = @_;
424 Role::Tiny::does_role($proto, $role) or $proto->$existing($role);
426 no warnings 'redefine';
427 *{_getglob "${to}::DOES"} = $new_sub;
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};
440 my ($me, $role) = @_;
441 return !!($INFO{$role} && $INFO{$role}{is_role});
451 Role::Tiny - Roles. Like a nouvelle cuisine portion size slice of Moose.
463 around baz => sub { ... }
471 use Role::Tiny::With;
473 # bar gets imported, but not foo
478 # baz is wrapped in the around modifier by Class::Method::Modifiers
483 If you wanted attributes as well, look at L<Moo::Role>.
487 C<Role::Tiny> is a minimalist role composition tool.
489 =head1 ROLE COMPOSITION
491 Role composition can be thought of as much more clever and meaningful multiple
492 inheritance. The basics of this implementation of roles is:
498 If a method is already defined on a class, that method will not be composed in
503 If a method that the role L</requires> to be implemented is not implemented,
504 role application will fail loudly.
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.
514 =head1 IMPORTED SUBROUTINES
518 requires qw(foo bar);
520 Declares a list of methods that must be defined to compose role.
526 with 'Some::Role1', 'Some::Role2';
528 Composes another role into the current role (or class via L<Role::Tiny::With>).
530 If you have conflicts and want to resolve them in favour of Some::Role1 you
536 If you have conflicts and want to resolve different conflicts in favour of
537 different roles, please refactor your codebase.
541 before foo => sub { ... };
543 See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
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>.
553 around foo => sub { ... };
555 See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
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>.
565 after foo => sub { ... };
567 See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
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>.
575 =head2 Strict and Warnings
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:
582 use warnings NONFATAL => 'all';
588 if (Role::Tiny::does_role($foo, 'Some::Role')) {
592 Returns true if class has been composed with role.
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
597 if ($foo->does('Some::Role')) {
601 will work for classes but to test a role, one must use ::does_role directly.
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.
609 =head2 apply_roles_to_package
611 Role::Tiny->apply_roles_to_package(
612 'Some::Package', 'Some::Role', 'Some::Other::Role'
615 Composes role with package. See also L<Role::Tiny::With>.
617 =head2 apply_roles_to_object
619 Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
621 Composes roles in order into object directly. Object is reblessed into the
624 =head2 create_class_with_roles
626 Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
628 Creates a new class based on base, with the roles composed into it in order.
629 New class is returned.
633 Role::Tiny->is_role('Some::Role1')
635 Returns true if the given package is a role.
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.
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>.
649 Ovid's L<Role::Basic> provides roles with a similar scope, but without method
650 modifiers, and having some extra usage restrictions.
654 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
658 dg - David Leadbeater (cpan:DGL) <dgl@dgl.cx>
660 frew - Arthur Axel "fREW" Schmidt (cpan:FREW) <frioux@gmail.com>
662 hobbs - Andrew Rodland (cpan:ARODLAND) <arodland@cpan.org>
664 jnap - John Napiorkowski (cpan:JJNAPIORK) <jjn1056@yahoo.com>
666 ribasushi - Peter Rabbitson (cpan:RIBASUSHI) <ribasushi@cpan.org>
668 chip - Chip Salzenberg (cpan:CHIPS) <chip@pobox.com>
670 ajgb - Alex J. G. Burzyński (cpan:AJGB) <ajgb@cpan.org>
672 doy - Jesse Luehrs (cpan:DOY) <doy at tozt dot net>
674 perigrin - Chris Prather (cpan:PERIGRIN) <chris@prather.org>
676 Mithaldu - Christian Walde (cpan:MITHALDU) <walde.christian@googlemail.com>
678 ilmari - Dagfinn Ilmari Mannsåker (cpan:ILMARI) <ilmari@ilmari.org>
680 tobyink - Toby Inkster (cpan:TOBYINK) <tobyink@cpan.org>
682 haarg - Graham Knop (cpan:HAARG) <haarg@haarg.org>
686 Copyright (c) 2010-2012 the Role::Tiny L</AUTHOR> and L</CONTRIBUTORS>
691 This library is free software and may be distributed under the same terms