Module::Runtime-ify
[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 %INFO;
10 our %APPLIED_TO;
11 our %COMPOSED;
12
13 # Module state workaround totally stolen from Zefram's Module::Runtime.
14
15 BEGIN {
16   *_WORK_AROUND_BROKEN_MODULE_STATE = "$]" < 5.009 ? sub(){1} : sub(){0};
17 }
18
19 sub Role::Tiny::__GUARD__::DESTROY {
20   delete $INC{$_[0]->[0]} if @{$_[0]};
21 }
22
23 sub _load_module {
24   (my $proto = $_[0]) =~ s/::/\//g;
25   $proto .= '.pm';
26   return 1 if $INC{$proto};
27   # can't just ->can('can') because a sub-package Foo::Bar::Baz
28   # creates a 'Baz::' key in Foo::Bar's symbol table
29   return 1 if grep !/::$/, keys %{_getstash($_[0])||{}};
30   my $guard = _WORK_AROUND_BROKEN_MODULE_STATE
31     && bless([ $proto ], 'Role::Tiny::__GUARD__');
32   require $proto;
33   pop @$guard if _WORK_AROUND_BROKEN_MODULE_STATE;
34   return 1;
35 }
36
37 sub import {
38   my $target = caller;
39   my $me = shift;
40   strictures->import;
41   return if $INFO{$target}; # already exported into this package
42   # get symbol table reference
43   my $stash = do { no strict 'refs'; \%{"${target}::"} };
44   # install before/after/around subs
45   foreach my $type (qw(before after around)) {
46     *{_getglob "${target}::${type}"} = sub {
47       require Class::Method::Modifiers;
48       push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
49     };
50   }
51   *{_getglob "${target}::requires"} = sub {
52     push @{$INFO{$target}{requires}||=[]}, @_;
53   };
54   *{_getglob "${target}::with"} = sub {
55     die "Only one role supported at a time by with" if @_ > 1;
56     $me->apply_role_to_package($target, $_[0]);
57   };
58   # grab all *non-constant* (stash slot is not a scalarref) subs present
59   # in the symbol table and store their refaddrs (no need to forcibly
60   # inflate constant subs into real subs) - also add '' to here (this
61   # is used later)
62   @{$INFO{$target}{not_methods}={}}{
63     '', map { *$_{CODE}||() } grep !ref($_), values %$stash
64   } = ();
65   # a role does itself
66   $APPLIED_TO{$target} = { $target => undef };
67 }
68
69 sub apply_role_to_package {
70   my ($me, $to, $role) = @_;
71
72   _load_module($role);
73
74   die "This is apply_role_to_package" if ref($to);
75   die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
76
77   $me->_check_requires($to, $role, @{$info->{requires}||[]});
78
79   $me->_install_methods($to, $role);
80
81   $me->_install_modifiers($to, $info->{modifiers});
82
83   # only add does() method to classes and only if they don't have one
84   if (not $INFO{$to} and not $to->can('does')) {
85     *{_getglob "${to}::does"} = \&does_role;
86   }
87
88   # copy our role list into the target's
89   @{$APPLIED_TO{$to}||={}}{keys %{$APPLIED_TO{$role}}} = ();
90 }
91
92 sub apply_roles_to_object {
93   my ($me, $object, @roles) = @_;
94   die "No roles supplied!" unless @roles;
95   my $class = ref($object);
96   bless($object, $me->create_class_with_roles($class, @roles));
97   $object;
98 }
99
100 sub create_class_with_roles {
101   my ($me, $superclass, @roles) = @_;
102
103   die "No roles supplied!" unless @roles;
104
105   my $new_name = join(
106     '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
107   );
108
109   return $new_name if $COMPOSED{class}{$new_name};
110
111   foreach my $role (@roles) {
112     _load_module($role);
113     die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
114   }
115
116   if ($] >= 5.010) {
117     require mro;
118   } else {
119     require MRO::Compat;
120   }
121
122   my @composable = map $me->_composable_package_for($_), reverse @roles;
123
124   *{_getglob("${new_name}::ISA")} = [ @composable, $superclass ];
125
126   my @info = map +($INFO{$_} ? $INFO{$_} : ()), @roles;
127
128   $me->_check_requires(
129     $new_name, $compose_name,
130     do { my %h; @h{map @{$_->{requires}||[]}, @info} = (); keys %h }
131   );
132
133   *{_getglob "${new_name}::does"} = \&does_role unless $new_name->can('does');
134
135   @{$APPLIED_TO{$new_name}||={}}{
136     map keys %{$APPLIED_TO{$_}}, @roles
137   } = ();
138
139   $COMPOSED{class}{$new_name} = 1;
140   return $new_name;
141 }
142
143 sub _composable_package_for {
144   my ($me, $role) = @_;
145   my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
146   return $composed_name if $COMPOSED{role}{$composed_name};
147   $me->_install_methods($composed_name, $role);
148   my $base_name = $composed_name.'::_BASE';
149   *{_getglob("${composed_name}::ISA")} = [ $base_name ];
150   my $modifiers = $INFO{$role}{modifiers}||[];
151   my @mod_base;
152   foreach my $modified (
153     do { my %h; @h{map $_->[1], @$modifiers} = (); keys %h }
154   ) {
155     push @mod_base, "sub ${modified} { shift->next::method(\@_) }";
156   }
157   {
158     local $@;
159     eval(my $code = join "\n", "package ${base_name};", @mod_base);
160     die "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
161   }
162   $me->_install_modifiers($composed_name, $modifiers);
163   $COMPOSED{role}{$composed_name} = 1;
164   return $composed_name;
165 }
166
167 sub _check_requires {
168   my ($me, $to, $name, @requires) = @_;
169   if (my @requires_fail = grep !$to->can($_), @requires) {
170     # role -> role, add to requires, role -> class, error out
171     if (my $to_info = $INFO{$to}) {
172       push @{$to_info->{requires}||=[]}, @requires_fail;
173     } else {
174       die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
175     }
176   }
177 }
178
179 sub _concrete_methods_of {
180   my ($me, $role) = @_;
181   my $info = $INFO{$role};
182   $info->{methods} ||= do {
183     # grab role symbol table
184     my $stash = do { no strict 'refs'; \%{"${role}::"}};
185     my $not_methods = $info->{not_methods};
186     +{
187       # grab all code entries that aren't in the not_methods list
188       map {
189         my $code = *{$stash->{$_}}{CODE};
190         # rely on the '' key we added in import for "no code here"
191         exists $not_methods->{$code||''} ? () : ($_ => $code)
192       } grep !ref($stash->{$_}), keys %$stash
193     };
194   };
195 }
196
197 sub methods_provided_by {
198   my ($me, $role) = @_;
199   die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
200   (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
201 }
202
203 sub _install_methods {
204   my ($me, $to, $role) = @_;
205
206   my $info = $INFO{$role};
207
208   my $methods = $me->_concrete_methods_of($role);
209
210   # grab target symbol table
211   my $stash = do { no strict 'refs'; \%{"${to}::"}};
212
213   # determine already extant methods of target
214   my %has_methods;
215   @has_methods{grep
216     +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
217     keys %$stash
218   } = ();
219
220   foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
221     no warnings 'once';
222     *{_getglob "${to}::${i}"} = $methods->{$i};
223   }
224 }
225
226 sub _install_modifiers {
227   my ($me, $to, $modifiers) = @_;
228   if (my $info = $INFO{$to}) {
229     push @{$info->{modifiers}}, @{$modifiers||[]};
230   } else {
231     foreach my $modifier (@{$modifiers||[]}) {
232       $me->_install_single_modifier($to, @$modifier);
233     }
234   }
235 }
236
237 sub _install_single_modifier {
238   my ($me, @args) = @_;
239   Class::Method::Modifiers::install_modifier(@args);
240 }
241
242 sub does_role {
243   my ($proto, $role) = @_;
244   return exists $APPLIED_TO{ref($proto)||$proto}{$role};
245 }
246
247 1;
248
249 =head1 NAME
250
251 Role::Tiny - Roles. Like a nouvelle cusine portion size slice of Moose.
252
253 =head1 SYNOPSIS
254
255  package Some::Role;
256
257  use Role::Tiny;
258
259  sub foo { ... }
260
261  sub bar { ... }
262
263  1;
264
265 else where
266
267  package Some::Class;
268
269  use Role::Tiny::With;
270
271  # bar gets imported, but not foo
272  with 'Some::Role';
273
274  sub foo { ... }
275
276  1;
277
278 =head1 DESCRIPTION
279
280 C<Role::Tiny> is a minimalist role composition tool.
281
282 =head1 ROLE COMPOSITION
283
284 Role composition can be thought of as much more clever and meaningful multiple
285 inheritance.  The basics of this implementation of roles is:
286
287 =over 2
288
289 =item *
290
291 If a method is already defined on a class, that method will not be composed in
292 from the role.
293
294 =item *
295
296 If a method that the role L</requires> to be implemented is not implemented,
297 role application will fail loudly.
298
299 =back
300
301 Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
302 composition is the other way around, where first wins.  In a more complete
303 system (see L<Moose>) roles are checked to see if they clash.  The goal of this
304 is to be much simpler, hence disallowing composition of multiple roles at once.
305
306 =head1 METHODS
307
308 =head2 apply_role_to_package
309
310  Role::Tiny->apply_role_to_package('Some::Package', 'Some::Role');
311
312 Composes role with package.  See also L<Role::Tiny::With>.
313
314 =head2 apply_roles_to_object
315
316  Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
317
318 Composes roles in order into object directly.  Object is reblessed into the
319 resulting class.
320
321 =head2 create_class_with_roles
322
323  Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
324
325 Creates a new class based on base, with the roles composed into it in order.
326 New class is returned.
327
328 =head1 SUBROUTINES
329
330 =head2 does_role
331
332  if (Role::Tiny::does_role($foo, 'Some::Role')) {
333    ...
334  }
335
336 Returns true if class has been composed with role.
337
338 This subroutine is also installed as ->does on any class a Role::Tiny is
339 composed into unless that class already has an ->does method, so
340
341   if ($foo->does_role('Some::Role')) {
342     ...
343   }
344
345 will work for classes but to test a role, one must use ::does_role directly
346
347 =head1 IMPORTED SUBROUTINES
348
349 =head2 requires
350
351  requires qw(foo bar);
352
353 Declares a list of methods that must be defined to compose role.
354
355 =head2 with
356
357  with 'Some::Role1';
358  with 'Some::Role2';
359
360 Composes another role into the current role.  Only one role may be composed in
361 at a time to allow the code to remain as simple as possible.
362
363 =head2 before
364
365  before foo => sub { ... };
366
367 See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
368 documentation.
369
370 =head2 around
371
372  around foo => sub { ... };
373
374 See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
375 documentation.
376
377 =head2 after
378
379  after foo => sub { ... };
380
381 See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
382 documentation.
383
384 =head1 AUTHORS
385
386 See L<Moo> for authors.
387
388 =head1 COPYRIGHT AND LICENSE
389
390 See L<Moo> for the copyright and license.
391
392 =cut