remove vestigial _is_scalar_ref sub
[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 # 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   { local $@; 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       { local $@; 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* (stash slot is not a scalarref) 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($_), 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     { local $@; require mro; }
106   } else {
107     { local $@; 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   {
146     local $@;
147     eval(my $code = join "\n", "package ${base_name};", @mod_base);
148     die "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
149   }
150   $me->_install_modifiers($composed_name, $modifiers);
151   $COMPOSED{role}{$composed_name} = 1;
152   return $composed_name;
153 }
154
155 sub _check_requires {
156   my ($me, $to, $name, @requires) = @_;
157   if (my @requires_fail = grep !$to->can($_), @requires) {
158     # role -> role, add to requires, role -> class, error out
159     if (my $to_info = $INFO{$to}) {
160       push @{$to_info->{requires}||=[]}, @requires_fail;
161     } else {
162       die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
163     }
164   }
165 }
166
167 sub _concrete_methods_of {
168   my ($me, $role) = @_;
169   my $info = $INFO{$role};
170   $info->{methods} ||= do {
171     # grab role symbol table
172     my $stash = do { no strict 'refs'; \%{"${role}::"}};
173     my $not_methods = $info->{not_methods};
174     +{
175       # grab all code entries that aren't in the not_methods list
176       map {
177         my $code = *{$stash->{$_}}{CODE};
178         # rely on the '' key we added in import for "no code here"
179         exists $not_methods->{$code||''} ? () : ($_ => $code)
180       } grep !ref($stash->{$_}), keys %$stash
181     };
182   };
183 }
184
185 sub methods_provided_by {
186   my ($me, $role) = @_;
187   die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
188   (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
189 }
190
191 sub _install_methods {
192   my ($me, $to, $role) = @_;
193
194   my $info = $INFO{$role};
195
196   my $methods = $me->_concrete_methods_of($role);
197
198   # grab target symbol table
199   my $stash = do { no strict 'refs'; \%{"${to}::"}};
200
201   # determine already extant methods of target
202   my %has_methods;
203   @has_methods{grep
204     +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
205     keys %$stash
206   } = ();
207
208   foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
209     no warnings 'once';
210     *{_getglob "${to}::${i}"} = $methods->{$i};
211   }
212 }
213
214 sub _install_modifiers {
215   my ($me, $to, $modifiers) = @_;
216   if (my $info = $INFO{$to}) {
217     push @{$info->{modifiers}}, @{$modifiers||[]};
218   } else {
219     foreach my $modifier (@{$modifiers||[]}) {
220       $me->_install_single_modifier($to, @$modifier);
221     }
222   }
223 }
224
225 sub _install_single_modifier {
226   my ($me, @args) = @_;
227   Class::Method::Modifiers::install_modifier(@args);
228 }
229
230 sub does_role {
231   my ($proto, $role) = @_;
232   return exists $APPLIED_TO{ref($proto)||$proto}{$role};
233 }
234
235 1;
236
237 =head1 NAME
238
239 Role::Tiny - Roles. Like a nouvelle cusine portion size slice of Moose.
240
241 =head1 SYNOPSIS
242
243  package Some::Role;
244
245  use Role::Tiny;
246
247  sub foo { ... }
248
249  sub bar { ... }
250
251  1;
252
253 else where
254
255  package Some::Class;
256
257  use Role::Tiny::With;
258
259  # bar gets imported, but not foo
260  with 'Some::Role';
261
262  sub foo { ... }
263
264  1;
265
266 =head1 DESCRIPTION
267
268 C<Role::Tiny> is a minimalist role composition tool.
269
270 =head1 ROLE COMPOSITION
271
272 Role composition can be thought of as much more clever and meaningful multiple
273 inheritance.  The basics of this implementation of roles is:
274
275 =over 2
276
277 =item *
278
279 If a method is already defined on a class, that method will not be composed in
280 from the role.
281
282 =item *
283
284 If a method that the role L</requires> to be implemented is not implemented,
285 role application will fail loudly.
286
287 =back
288
289 Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
290 composition is the other way around, where first wins.  In a more complete
291 system (see L<Moose>) roles are checked to see if they clash.  The goal of this
292 is to be much simpler, hence disallowing composition of multiple roles at once.
293
294 =head1 METHODS
295
296 =head2 apply_role_to_package
297
298  Role::Tiny->apply_role_to_package('Some::Package', 'Some::Role');
299
300 Composes role with package.  See also L<Role::Tiny::With>.
301
302 =head2 apply_roles_to_object
303
304  Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
305
306 Composes roles in order into object directly.  Object is reblessed into the
307 resulting class.
308
309 =head2 create_class_with_roles
310
311  Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
312
313 Creates a new class based on base, with the roles composed into it in order.
314 New class is returned.
315
316 =head1 SUBROUTINES
317
318 =head2 does_role
319
320  if (Role::Tiny::does_role($foo, 'Some::Role')) {
321    ...
322  }
323
324 Returns true if class has been composed with role.
325
326 This subroutine is also installed as ->does on any class a Role::Tiny is
327 composed into unless that class already has an ->does method, so
328
329   if ($foo->does_role('Some::Role')) {
330     ...
331   }
332
333 will work for classes but to test a role, one must use ::does_role directly
334
335 =head1 IMPORTED SUBROUTINES
336
337 =head2 requires
338
339  requires qw(foo bar);
340
341 Declares a list of methods that must be defined to compose role.
342
343 =head2 with
344
345  with 'Some::Role1';
346  with 'Some::Role2';
347
348 Composes another role into the current role.  Only one role may be composed in
349 at a time to allow the code to remain as simple as possible.
350
351 =head2 before
352
353  before foo => sub { ... };
354
355 See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
356 documentation.
357
358 =head2 around
359
360  around foo => sub { ... };
361
362 See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
363 documentation.
364
365 =head2 after
366
367  after foo => sub { ... };
368
369 See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
370 documentation.
371
372 =head1 AUTHORS
373
374 See L<Moo> for authors.
375
376 =head1 COPYRIGHT AND LICENSE
377
378 See L<Moo> for the copyright and license.
379
380 =cut