bump version
[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.000001'; # 1.0.1
10 $VERSION = eval $VERSION;
11
12 our %INFO;
13 our %APPLIED_TO;
14 our %COMPOSED;
15
16 # Module state workaround totally stolen from Zefram's Module::Runtime.
17
18 BEGIN {
19   *_WORK_AROUND_BROKEN_MODULE_STATE = "$]" < 5.009 ? sub(){1} : sub(){0};
20 }
21
22 sub Role::Tiny::__GUARD__::DESTROY {
23   delete $INC{$_[0]->[0]} if @{$_[0]};
24 }
25
26 sub _load_module {
27   (my $proto = $_[0]) =~ s/::/\//g;
28   $proto .= '.pm';
29   return 1 if $INC{$proto};
30   # can't just ->can('can') because a sub-package Foo::Bar::Baz
31   # creates a 'Baz::' key in Foo::Bar's symbol table
32   return 1 if grep !/::$/, keys %{_getstash($_[0])||{}};
33   my $guard = _WORK_AROUND_BROKEN_MODULE_STATE
34     && bless([ $proto ], 'Role::Tiny::__GUARD__');
35   require $proto;
36   pop @$guard if _WORK_AROUND_BROKEN_MODULE_STATE;
37   return 1;
38 }
39
40 sub import {
41   my $target = caller;
42   my $me = shift;
43   strict->import;
44   warnings->import(FATAL => 'all');
45   return if $INFO{$target}; # already exported into this package
46   # get symbol table reference
47   my $stash = do { no strict 'refs'; \%{"${target}::"} };
48   # install before/after/around subs
49   foreach my $type (qw(before after around)) {
50     *{_getglob "${target}::${type}"} = sub {
51       require Class::Method::Modifiers;
52       push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
53     };
54   }
55   *{_getglob "${target}::requires"} = sub {
56     push @{$INFO{$target}{requires}||=[]}, @_;
57   };
58   *{_getglob "${target}::with"} = sub {
59     die "Only one role supported at a time by with" if @_ > 1;
60     $me->apply_role_to_package($target, $_[0]);
61   };
62   # grab all *non-constant* (stash slot is not a scalarref) subs present
63   # in the symbol table and store their refaddrs (no need to forcibly
64   # inflate constant subs into real subs) - also add '' to here (this
65   # is used later)
66   @{$INFO{$target}{not_methods}={}}{
67     '', map { *$_{CODE}||() } grep !ref($_), values %$stash
68   } = ();
69   # a role does itself
70   $APPLIED_TO{$target} = { $target => undef };
71 }
72
73 sub apply_role_to_package {
74   my ($me, $to, $role) = @_;
75
76   _load_module($role);
77
78   die "This is apply_role_to_package" if ref($to);
79   die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
80
81   $me->_check_requires($to, $role, @{$info->{requires}||[]});
82
83   $me->_install_methods($to, $role);
84
85   $me->_install_modifiers($to, $info->{modifiers});
86
87   # only add does() method to classes and only if they don't have one
88   if (not $INFO{$to} and not $to->can('does')) {
89     *{_getglob "${to}::does"} = \&does_role;
90   }
91
92   # copy our role list into the target's
93   @{$APPLIED_TO{$to}||={}}{keys %{$APPLIED_TO{$role}}} = ();
94 }
95
96 sub apply_roles_to_object {
97   my ($me, $object, @roles) = @_;
98   die "No roles supplied!" unless @roles;
99   my $class = ref($object);
100   bless($object, $me->create_class_with_roles($class, @roles));
101   $object;
102 }
103
104 sub create_class_with_roles {
105   my ($me, $superclass, @roles) = @_;
106
107   die "No roles supplied!" unless @roles;
108
109   my $new_name = join(
110     '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
111   );
112
113   return $new_name if $COMPOSED{class}{$new_name};
114
115   foreach my $role (@roles) {
116     _load_module($role);
117     die "${role} is not a Role::Tiny" unless $INFO{$role};
118   }
119
120   if ($] >= 5.010) {
121     require mro;
122   } else {
123     require MRO::Compat;
124   }
125
126   my @composable = map $me->_composable_package_for($_), reverse @roles;
127
128   *{_getglob("${new_name}::ISA")} = [ @composable, $superclass ];
129
130   my @info = map $INFO{$_}, @roles;
131
132   $me->_check_requires(
133     $new_name, $compose_name,
134     do { my %h; @h{map @{$_->{requires}||[]}, @info} = (); keys %h }
135   );
136
137   *{_getglob "${new_name}::does"} = \&does_role unless $new_name->can('does');
138
139   @{$APPLIED_TO{$new_name}||={}}{
140     map keys %{$APPLIED_TO{$_}}, @roles
141   } = ();
142
143   $COMPOSED{class}{$new_name} = 1;
144   return $new_name;
145 }
146
147 sub _composable_package_for {
148   my ($me, $role) = @_;
149   my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
150   return $composed_name if $COMPOSED{role}{$composed_name};
151   $me->_install_methods($composed_name, $role);
152   my $base_name = $composed_name.'::_BASE';
153   *{_getglob("${composed_name}::ISA")} = [ $base_name ];
154   my $modifiers = $INFO{$role}{modifiers}||[];
155   my @mod_base;
156   foreach my $modified (
157     do { my %h; @h{map $_->[1], @$modifiers} = (); keys %h }
158   ) {
159     push @mod_base, "sub ${modified} { shift->next::method(\@_) }";
160   }
161   my $e;
162   {
163     local $@;
164     eval(my $code = join "\n", "package ${base_name};", @mod_base);
165     $e = "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
166   }
167   die $e if $e;
168   $me->_install_modifiers($composed_name, $modifiers);
169   $COMPOSED{role}{$composed_name} = 1;
170   return $composed_name;
171 }
172
173 sub _check_requires {
174   my ($me, $to, $name, @requires) = @_;
175   if (my @requires_fail = grep !$to->can($_), @requires) {
176     # role -> role, add to requires, role -> class, error out
177     if (my $to_info = $INFO{$to}) {
178       push @{$to_info->{requires}||=[]}, @requires_fail;
179     } else {
180       die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
181     }
182   }
183 }
184
185 sub _concrete_methods_of {
186   my ($me, $role) = @_;
187   my $info = $INFO{$role};
188   $info->{methods} ||= do {
189     # grab role symbol table
190     my $stash = do { no strict 'refs'; \%{"${role}::"}};
191     my $not_methods = $info->{not_methods};
192     +{
193       # grab all code entries that aren't in the not_methods list
194       map {
195         my $code = *{$stash->{$_}}{CODE};
196         # rely on the '' key we added in import for "no code here"
197         exists $not_methods->{$code||''} ? () : ($_ => $code)
198       } grep !ref($stash->{$_}), keys %$stash
199     };
200   };
201 }
202
203 sub methods_provided_by {
204   my ($me, $role) = @_;
205   die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
206   (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
207 }
208
209 sub _install_methods {
210   my ($me, $to, $role) = @_;
211
212   my $info = $INFO{$role};
213
214   my $methods = $me->_concrete_methods_of($role);
215
216   # grab target symbol table
217   my $stash = do { no strict 'refs'; \%{"${to}::"}};
218
219   # determine already extant methods of target
220   my %has_methods;
221   @has_methods{grep
222     +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
223     keys %$stash
224   } = ();
225
226   foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
227     no warnings 'once';
228     *{_getglob "${to}::${i}"} = $methods->{$i};
229   }
230 }
231
232 sub _install_modifiers {
233   my ($me, $to, $modifiers) = @_;
234   if (my $info = $INFO{$to}) {
235     push @{$info->{modifiers}}, @{$modifiers||[]};
236   } else {
237     foreach my $modifier (@{$modifiers||[]}) {
238       $me->_install_single_modifier($to, @$modifier);
239     }
240   }
241 }
242
243 sub _install_single_modifier {
244   my ($me, @args) = @_;
245   Class::Method::Modifiers::install_modifier(@args);
246 }
247
248 sub does_role {
249   my ($proto, $role) = @_;
250   return exists $APPLIED_TO{ref($proto)||$proto}{$role};
251 }
252
253 1;
254
255 =head1 NAME
256
257 Role::Tiny - Roles. Like a nouvelle cuisine portion size slice of Moose.
258
259 =head1 SYNOPSIS
260
261  package Some::Role;
262
263  use Role::Tiny;
264
265  sub foo { ... }
266
267  sub bar { ... }
268
269  around baz => sub { ... }
270
271  1;
272
273 else where
274
275  package Some::Class;
276
277  use Role::Tiny::With;
278
279  # bar gets imported, but not foo
280  with 'Some::Role';
281
282  sub foo { ... }
283
284  # baz is wrapped in the around modifier by Class::Method::Modifiers
285  sub baz { ... }
286
287  1;
288
289 If you wanted attributes as well, look at L<Moo::Role>.
290
291 =head1 DESCRIPTION
292
293 C<Role::Tiny> is a minimalist role composition tool.
294
295 =head1 ROLE COMPOSITION
296
297 Role composition can be thought of as much more clever and meaningful multiple
298 inheritance.  The basics of this implementation of roles is:
299
300 =over 2
301
302 =item *
303
304 If a method is already defined on a class, that method will not be composed in
305 from the role.
306
307 =item *
308
309 If a method that the role L</requires> to be implemented is not implemented,
310 role application will fail loudly.
311
312 =back
313
314 Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
315 composition is the other way around, where first wins.  In a more complete
316 system (see L<Moose>) roles are checked to see if they clash.  The goal of this
317 is to be much simpler, hence disallowing composition of multiple roles at once.
318
319 =head1 METHODS
320
321 =head2 apply_role_to_package
322
323  Role::Tiny->apply_role_to_package('Some::Package', 'Some::Role');
324
325 Composes role with package.  See also L<Role::Tiny::With>.
326
327 =head2 apply_roles_to_object
328
329  Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
330
331 Composes roles in order into object directly.  Object is reblessed into the
332 resulting class.
333
334 =head2 create_class_with_roles
335
336  Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
337
338 Creates a new class based on base, with the roles composed into it in order.
339 New class is returned.
340
341 =head1 SUBROUTINES
342
343 =head2 does_role
344
345  if (Role::Tiny::does_role($foo, 'Some::Role')) {
346    ...
347  }
348
349 Returns true if class has been composed with role.
350
351 This subroutine is also installed as ->does on any class a Role::Tiny is
352 composed into unless that class already has an ->does method, so
353
354   if ($foo->does('Some::Role')) {
355     ...
356   }
357
358 will work for classes but to test a role, one must use ::does_role directly
359
360 =head1 IMPORTED SUBROUTINES
361
362 =head2 requires
363
364  requires qw(foo bar);
365
366 Declares a list of methods that must be defined to compose role.
367
368 =head2 with
369
370  with 'Some::Role1';
371  with 'Some::Role2';
372
373 Composes another role into the current role.  Only one role may be composed in
374 at a time to allow the code to remain as simple as possible.
375
376 =head2 before
377
378  before foo => sub { ... };
379
380 See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
381 documentation.
382
383 Note that since you are not required to use method modifiers,
384 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
385 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
386 both L<Class::Method::Modifiers> and L<Role::Tiny>.
387
388 =head2 around
389
390  around foo => sub { ... };
391
392 See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
393 documentation.
394
395 Note that since you are not required to use method modifiers,
396 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
397 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
398 both L<Class::Method::Modifiers> and L<Role::Tiny>.
399
400 =head2 after
401
402  after foo => sub { ... };
403
404 See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
405 documentation.
406
407 Note that since you are not required to use method modifiers,
408 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
409 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
410 both L<Class::Method::Modifiers> and L<Role::Tiny>.
411
412 =head1 SEE ALSO
413
414 L<Role::Tiny> is the attribute-less subset of L<Moo::Role>; L<Moo::Role> is
415 a meta-protocol-less subset of the king of role systems, L<Moose::Role>.
416
417 If you don't want method modifiers and do want to be forcibly restricted
418 to a single role application per class, Ovid's L<Role::Basic> exists. But
419 Stevan Little (the L<Moose> author) and I are both still convinced that
420 he's Doing It Wrong.
421
422 =head1 AUTHOR
423
424 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
425
426 =head1 CONTRIBUTORS
427
428 dg - David Leadbeater (cpan:DGL) <dgl@dgl.cx>
429
430 frew - Arthur Axel "fREW" Schmidt (cpan:FREW) <frioux@gmail.com>
431
432 hobbs - Andrew Rodland (cpan:ARODLAND) <arodland@cpan.org>
433
434 jnap - John Napiorkowski (cpan:JJNAPIORK) <jjn1056@yahoo.com>
435
436 ribasushi - Peter Rabbitson (cpan:RIBASUSHI) <ribasushi@cpan.org>
437
438 chip - Chip Salzenberg (cpan:CHIPS) <chip@pobox.com>
439
440 ajgb - Alex J. G. BurzyƄski (cpan:AJGB) <ajgb@cpan.org>
441
442 doy - Jesse Luehrs (cpan:DOY) <doy at tozt dot net>
443
444 perigrin - Chris Prather (cpan:PERIGRIN) <chris@prather.org>
445
446 =head1 COPYRIGHT
447
448 Copyright (c) 2010-2012 the Role::Tiny L</AUTHOR> and L</CONTRIBUTORS>
449 as listed above.
450
451 =head1 LICENSE
452
453 This library is free software and may be distributed under the same terms
454 as perl itself.
455
456 =cut