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