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