e484c9266783b1c41080a589b1ae96e98d9e9971
[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.000000'; # 1.0.0
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   {
162     local $@;
163     eval(my $code = join "\n", "package ${base_name};", @mod_base);
164     die "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
165   }
166   $me->_install_modifiers($composed_name, $modifiers);
167   $COMPOSED{role}{$composed_name} = 1;
168   return $composed_name;
169 }
170
171 sub _check_requires {
172   my ($me, $to, $name, @requires) = @_;
173   if (my @requires_fail = grep !$to->can($_), @requires) {
174     # role -> role, add to requires, role -> class, error out
175     if (my $to_info = $INFO{$to}) {
176       push @{$to_info->{requires}||=[]}, @requires_fail;
177     } else {
178       die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
179     }
180   }
181 }
182
183 sub _concrete_methods_of {
184   my ($me, $role) = @_;
185   my $info = $INFO{$role};
186   $info->{methods} ||= do {
187     # grab role symbol table
188     my $stash = do { no strict 'refs'; \%{"${role}::"}};
189     my $not_methods = $info->{not_methods};
190     +{
191       # grab all code entries that aren't in the not_methods list
192       map {
193         my $code = *{$stash->{$_}}{CODE};
194         # rely on the '' key we added in import for "no code here"
195         exists $not_methods->{$code||''} ? () : ($_ => $code)
196       } grep !ref($stash->{$_}), keys %$stash
197     };
198   };
199 }
200
201 sub methods_provided_by {
202   my ($me, $role) = @_;
203   die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
204   (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
205 }
206
207 sub _install_methods {
208   my ($me, $to, $role) = @_;
209
210   my $info = $INFO{$role};
211
212   my $methods = $me->_concrete_methods_of($role);
213
214   # grab target symbol table
215   my $stash = do { no strict 'refs'; \%{"${to}::"}};
216
217   # determine already extant methods of target
218   my %has_methods;
219   @has_methods{grep
220     +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
221     keys %$stash
222   } = ();
223
224   foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
225     no warnings 'once';
226     *{_getglob "${to}::${i}"} = $methods->{$i};
227   }
228 }
229
230 sub _install_modifiers {
231   my ($me, $to, $modifiers) = @_;
232   if (my $info = $INFO{$to}) {
233     push @{$info->{modifiers}}, @{$modifiers||[]};
234   } else {
235     foreach my $modifier (@{$modifiers||[]}) {
236       $me->_install_single_modifier($to, @$modifier);
237     }
238   }
239 }
240
241 sub _install_single_modifier {
242   my ($me, @args) = @_;
243   Class::Method::Modifiers::install_modifier(@args);
244 }
245
246 sub does_role {
247   my ($proto, $role) = @_;
248   return exists $APPLIED_TO{ref($proto)||$proto}{$role};
249 }
250
251 1;
252
253 =head1 NAME
254
255 Role::Tiny - Roles. Like a nouvelle cuisine portion size slice of Moose.
256
257 =head1 SYNOPSIS
258
259  package Some::Role;
260
261  use Role::Tiny;
262
263  sub foo { ... }
264
265  sub bar { ... }
266
267  1;
268
269 else where
270
271  package Some::Class;
272
273  use Role::Tiny::With;
274
275  # bar gets imported, but not foo
276  with 'Some::Role';
277
278  sub foo { ... }
279
280  1;
281
282 =head1 DESCRIPTION
283
284 C<Role::Tiny> is a minimalist role composition tool.
285
286 =head1 ROLE COMPOSITION
287
288 Role composition can be thought of as much more clever and meaningful multiple
289 inheritance.  The basics of this implementation of roles is:
290
291 =over 2
292
293 =item *
294
295 If a method is already defined on a class, that method will not be composed in
296 from the role.
297
298 =item *
299
300 If a method that the role L</requires> to be implemented is not implemented,
301 role application will fail loudly.
302
303 =back
304
305 Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
306 composition is the other way around, where first wins.  In a more complete
307 system (see L<Moose>) roles are checked to see if they clash.  The goal of this
308 is to be much simpler, hence disallowing composition of multiple roles at once.
309
310 =head1 METHODS
311
312 =head2 apply_role_to_package
313
314  Role::Tiny->apply_role_to_package('Some::Package', 'Some::Role');
315
316 Composes role with package.  See also L<Role::Tiny::With>.
317
318 =head2 apply_roles_to_object
319
320  Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
321
322 Composes roles in order into object directly.  Object is reblessed into the
323 resulting class.
324
325 =head2 create_class_with_roles
326
327  Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
328
329 Creates a new class based on base, with the roles composed into it in order.
330 New class is returned.
331
332 =head1 SUBROUTINES
333
334 =head2 does_role
335
336  if (Role::Tiny::does_role($foo, 'Some::Role')) {
337    ...
338  }
339
340 Returns true if class has been composed with role.
341
342 This subroutine is also installed as ->does on any class a Role::Tiny is
343 composed into unless that class already has an ->does method, so
344
345   if ($foo->does('Some::Role')) {
346     ...
347   }
348
349 will work for classes but to test a role, one must use ::does_role directly
350
351 =head1 IMPORTED SUBROUTINES
352
353 =head2 requires
354
355  requires qw(foo bar);
356
357 Declares a list of methods that must be defined to compose role.
358
359 =head2 with
360
361  with 'Some::Role1';
362  with 'Some::Role2';
363
364 Composes another role into the current role.  Only one role may be composed in
365 at a time to allow the code to remain as simple as possible.
366
367 =head2 before
368
369  before foo => sub { ... };
370
371 See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
372 documentation.
373
374 =head2 around
375
376  around foo => sub { ... };
377
378 See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
379 documentation.
380
381 =head2 after
382
383  after foo => sub { ... };
384
385 See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
386 documentation.
387
388 =head1 AUTHOR
389
390 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
391
392 =head1 CONTRIBUTORS
393
394 dg - David Leadbeater (cpan:DGL) <dgl@dgl.cx>
395
396 frew - Arthur Axel "fREW" Schmidt (cpan:FREW) <frioux@gmail.com>
397
398 hobbs - Andrew Rodland (cpan:ARODLAND) <arodland@cpan.org>
399
400 jnap - John Napiorkowski (cpan:JJNAPIORK) <jjn1056@yahoo.com>
401
402 ribasushi - Peter Rabbitson (cpan:RIBASUSHI) <ribasushi@cpan.org>
403
404 chip - Chip Salzenberg (cpan:CHIPS) <chip@pobox.com>
405
406 ajgb - Alex J. G. BurzyƄski (cpan:AJGB) <ajgb@cpan.org>
407
408 doy - Jesse Luehrs (cpan:DOY) <doy at tozt dot net>
409
410 perigrin - Chris Prather (cpan:PERIGRIN) <chris@prather.org>
411
412 =head1 COPYRIGHT
413
414 Copyright (c) 2010-2012 the Role::Tiny L</AUTHOR> and L</CONTRIBUTORS>
415 as listed above.
416
417 =head1 LICENSE
418
419 This library is free software and may be distributed under the same terms
420 as perl itself.
421
422 =cut