generate constructors in subclasses on demand
[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
9our %INFO;
10our %APPLIED_TO;
1947330a 11our %COMPOSED;
ab3370e7 12
5e03b55c 13# inlined from Moo::_Utils - update that first.
14
fb5074f6 15sub _load_module {
fb5074f6 16 (my $proto = $_[0]) =~ s/::/\//g;
5e03b55c 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])||{}};
fb5074f6 21 require "${proto}.pm";
22 return 1;
23}
24
ab3370e7 25sub import {
26 my $target = caller;
b1eebd55 27 my $me = $_[0];
de3d4906 28 strictures->import;
1ba11455 29 return if $INFO{$target}; # already exported into this package
ab3370e7 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)) {
5a247406 34 *{_getglob "${target}::${type}"} = sub {
b1eebd55 35 require Class::Method::Modifiers;
ab3370e7 36 push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
37 };
38 }
5a247406 39 *{_getglob "${target}::requires"} = sub {
ab3370e7 40 push @{$INFO{$target}{requires}||=[]}, @_;
41 };
5a247406 42 *{_getglob "${target}::with"} = sub {
43 die "Only one role supported at a time by with" if @_ > 1;
369a4c50 44 $me->apply_role_to_package($target, $_[0]);
96d3f07a 45 };
ab3370e7 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
57sub apply_role_to_package {
369a4c50 58 my ($me, $to, $role) = @_;
1947330a 59
fb5074f6 60 _load_module($role);
61
ab3370e7 62 die "This is apply_role_to_package" if ref($to);
1947330a 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
1947330a 76 # copy our role list into the target's
77 @{$APPLIED_TO{$to}||={}}{keys %{$APPLIED_TO{$role}}} = ();
78}
79
80sub 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
88sub create_class_with_roles {
89 my ($me, $superclass, @roles) = @_;
90
fb5074f6 91 die "No roles supplied!" unless @roles;
92
c69190f1 93 my $new_name = join(
94 '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
95 );
96
1947330a 97 return $new_name if $COMPOSED{class}{$new_name};
98
99 foreach my $role (@roles) {
fb5074f6 100 _load_module($role);
1947330a 101 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
102 }
103
786e5ba0 104 if ($] >= 5.010) {
b1eebd55 105 require mro;
106 } else {
107 require MRO::Compat;
108 }
1947330a 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 );
1947330a 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
131sub _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}||[];
b1eebd55 139 my @mod_base;
1947330a 140 foreach my $modified (
141 do { my %h; @h{map $_->[1], @$modifiers} = (); keys %h }
142 ) {
b1eebd55 143 push @mod_base, "sub ${modified} { shift->next::method(\@_) }";
1947330a 144 }
b1eebd55 145 eval(my $code = join "\n", "package ${base_name};", @mod_base);
146 die "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
1947330a 147 $me->_install_modifiers($composed_name, $modifiers);
148 $COMPOSED{role}{$composed_name} = 1;
149 return $composed_name;
150}
151
152sub _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
4db3a740 164sub _concrete_methods_of {
165 my ($me, $role) = @_;
1947330a 166 my $info = $INFO{$role};
4db3a740 167 $info->{methods} ||= do {
ab3370e7 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 {
934ea2c1 174 my $code = *{$stash->{$_}}{CODE};
175 # rely on the '' key we added in import for "no code here"
176 exists $not_methods->{$code||''} ? () : ($_ => $code)
ab3370e7 177 } grep !(ref($stash->{$_}) eq 'SCALAR'), keys %$stash
178 };
179 };
4db3a740 180}
181
182sub 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
188sub _install_methods {
189 my ($me, $to, $role) = @_;
190
191 my $info = $INFO{$role};
192
193 my $methods = $me->_concrete_methods_of($role);
1947330a 194
ab3370e7 195 # grab target symbol table
196 my $stash = do { no strict 'refs'; \%{"${to}::"}};
1947330a 197
ab3370e7 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 } = ();
ab3370e7 204
1947330a 205 foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
ab3370e7 206 no warnings 'once';
5a247406 207 *{_getglob "${to}::${i}"} = $methods->{$i};
ab3370e7 208 }
1947330a 209}
ab3370e7 210
1947330a 211sub _install_modifiers {
212 my ($me, $to, $modifiers) = @_;
dccea57d 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 }
96d3f07a 219 }
ab3370e7 220}
221
dccea57d 222sub _install_single_modifier {
223 my ($me, @args) = @_;
224 Class::Method::Modifiers::install_modifier(@args);
225}
226
ab3370e7 227sub does_role {
390ac406 228 my ($proto, $role) = @_;
229 return exists $APPLIED_TO{ref($proto)||$proto}{$role};
ab3370e7 230}
231
2321;
5febcf4d 233
0b6e5fff 234=head1 NAME
235
236Role::Tiny - Roles. Like a nouvelle cusine portion size slice of Moose.
5febcf4d 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
250else where
251
252 package Some::Class;
253
254 require Role::Tiny;
255
256 # bar gets imported, but not foo
257 Role::Tiny->apply_role_to_package('Some::Role', __PACKAGE__);
258
259 sub foo { ... }
260
261 1;
262
263=head1 DESCRIPTION
264
265C<Role::Tiny> is a minimalist role composition tool.
266
267=head1 ROLE COMPOSITION
268
269Role composition can be thought of as much more clever and meaningful multiple
270inheritance. The basics of this implementation of roles is:
271
272=over 2
273
274=item *
275
276If a method is already defined on a class, that method will not be composed in
277from the role.
278
279=item *
280
281If a method that the role L</requires> to be implemented is not implemented,
282role application will fail loudly.
283
0d39f9d3 284=back
285
5febcf4d 286Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
287composition is the other way around, where first wins. In a more complete
288system (see L<Moose>) roles are checked to see if they clash. The goal of this
289is to be much simpler, hence disallowing composition of multiple roles at once.
290
291=head1 METHODS
292
293=head2 apply_role_to_package
294
369a4c50 295 Role::Tiny->apply_role_to_package('Some::Package', 'Some::Role');
5febcf4d 296
297Composes role with package
298
299=head2 apply_roles_to_object
300
301 Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
302
303Composes roles in order into object directly. Object is reblessed into the
304resulting class.
305
306=head2 create_class_with_roles
307
308 Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
309
310Creates a new class based on base, with the roles composed into it in order.
311New class is returned.
312
54e4000d 313=head1 SUBROUTINES
5febcf4d 314
315=head2 does_role
316
54e4000d 317 if (Role::Tiny::does_role($foo, 'Some::Role')) {
5febcf4d 318 ...
319 }
320
321Returns true if class has been composed with role.
322
54e4000d 323This subroutine is also installed as ->does on any class a Role::Tiny is
324composed into unless that class already has an ->does method, so
325
326 if ($foo->does_role('Some::Role')) {
327 ...
328 }
329
330will work for classes but to test a role, one must use ::does_role directly
331
5febcf4d 332=head1 IMPORTED SUBROUTINES
333
334=head2 requires
335
336 requires qw(foo bar);
337
338Declares 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
345Composes another role into the current role. Only one role may be composed in
346at a time to allow the code to remain as simple as possible.
347
348=head2 before
349
350 before foo => sub { ... };
351
352See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
353documentation.
354
355=head2 around
356
357 around foo => sub { ... };
358
359See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
360documentation.
361
362=head2 after
363
364 after foo => sub { ... };
365
366See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
367documentation.
368
40f3e3aa 369=head1 AUTHORS
370
371See L<Moo> for authors.
372
373=head1 COPYRIGHT AND LICENSE
374
375See L<Moo> for the copyright and license.
376
377=cut