_load_module
[gitmo/Role-Tiny.git] / lib / Role / Tiny.pm
1 package Role::Tiny;
2
3 use strict;
4 use warnings FATAL => 'all';
5
6 our %INFO;
7 our %APPLIED_TO;
8 our %COMPOSED;
9
10 sub _getglob { no strict 'refs'; \*{$_[0]} }
11
12 sub _load_module {
13   return 1 if $_[0]->can('can');
14   (my $proto = $_[0]) =~ s/::/\//g;
15   require "${proto}.pm";
16   return 1;
17 }
18
19 sub import {
20   my $target = caller;
21   my $me = $_[0];
22   strictures->import;
23   # get symbol table reference
24   my $stash = do { no strict 'refs'; \%{"${target}::"} };
25   # install before/after/around subs
26   foreach my $type (qw(before after around)) {
27     *{_getglob "${target}::${type}"} = sub {
28       require Class::Method::Modifiers;
29       push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
30     };
31   }
32   *{_getglob "${target}::requires"} = sub {
33     push @{$INFO{$target}{requires}||=[]}, @_;
34   };
35   *{_getglob "${target}::with"} = sub {
36     die "Only one role supported at a time by with" if @_ > 1;
37     $me->apply_role_to_package($_[0], $target);
38   };
39   # grab all *non-constant* (ref eq 'SCALAR') subs present
40   # in the symbol table and store their refaddrs (no need to forcibly
41   # inflate constant subs into real subs) - also add '' to here (this
42   # is used later)
43   @{$INFO{$target}{not_methods}={}}{
44     '', map { *$_{CODE}||() } grep !(ref eq 'SCALAR'), values %$stash
45   } = ();
46   # a role does itself
47   $APPLIED_TO{$target} = { $target => undef };
48 }
49
50 sub apply_role_to_package {
51   my ($me, $role, $to) = @_;
52
53   _load_module($role);
54
55   die "This is apply_role_to_package" if ref($to);
56   die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
57
58   $me->_check_requires($to, $role, @{$info->{requires}||[]});
59
60   $me->_install_methods($to, $role);
61
62   $me->_install_modifiers($to, $info->{modifiers});
63
64   # only add does() method to classes and only if they don't have one
65   if (not $INFO{$to} and not $to->can('does')) {
66     *{_getglob "${to}::does"} = \&does_role;
67   }
68
69   # copy our role list into the target's
70   @{$APPLIED_TO{$to}||={}}{keys %{$APPLIED_TO{$role}}} = ();
71 }
72
73 sub apply_roles_to_object {
74   my ($me, $object, @roles) = @_;
75   die "No roles supplied!" unless @roles;
76   my $class = ref($object);
77   bless($object, $me->create_class_with_roles($class, @roles));
78   $object;
79 }
80
81 sub create_class_with_roles {
82   my ($me, $superclass, @roles) = @_;
83
84   die "No roles supplied!" unless @roles;
85
86   my $new_name = join('+', $superclass, my $compose_name = join '+', @roles);
87   return $new_name if $COMPOSED{class}{$new_name};
88
89   foreach my $role (@roles) {
90     _load_module($role);
91     die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
92   }
93
94   if ($] > 5.010) {
95     require mro;
96   } else {
97     require MRO::Compat;
98   }
99
100   my @composable = map $me->_composable_package_for($_), reverse @roles;
101
102   *{_getglob("${new_name}::ISA")} = [ @composable, $superclass ];
103
104   my @info = map +($INFO{$_} ? $INFO{$_} : ()), @roles;
105
106   $me->_check_requires(
107     $new_name, $compose_name,
108     do { my %h; @h{map @{$_->{requires}||[]}, @info} = (); keys %h }
109   );
110
111   *{_getglob "${new_name}::does"} = \&does_role unless $new_name->can('does');
112
113   @{$APPLIED_TO{$new_name}||={}}{
114     map keys %{$APPLIED_TO{$_}}, @roles
115   } = ();
116
117   $COMPOSED{class}{$new_name} = 1;
118   return $new_name;
119 }
120
121 sub _composable_package_for {
122   my ($me, $role) = @_;
123   my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
124   return $composed_name if $COMPOSED{role}{$composed_name};
125   $me->_install_methods($composed_name, $role);
126   my $base_name = $composed_name.'::_BASE';
127   *{_getglob("${composed_name}::ISA")} = [ $base_name ];
128   my $modifiers = $INFO{$role}{modifiers}||[];
129   my @mod_base;
130   foreach my $modified (
131     do { my %h; @h{map $_->[1], @$modifiers} = (); keys %h }
132   ) {
133     push @mod_base, "sub ${modified} { shift->next::method(\@_) }";
134   }
135   eval(my $code = join "\n", "package ${base_name};", @mod_base);
136   die "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
137   $me->_install_modifiers($composed_name, $modifiers);
138   $COMPOSED{role}{$composed_name} = 1;
139   return $composed_name;
140 }
141
142 sub _check_requires {
143   my ($me, $to, $name, @requires) = @_;
144   if (my @requires_fail = grep !$to->can($_), @requires) {
145     # role -> role, add to requires, role -> class, error out
146     if (my $to_info = $INFO{$to}) {
147       push @{$to_info->{requires}||=[]}, @requires_fail;
148     } else {
149       die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
150     }
151   }
152 }
153
154 sub _concrete_methods_of {
155   my ($me, $role) = @_;
156   my $info = $INFO{$role};
157   $info->{methods} ||= do {
158     # grab role symbol table
159     my $stash = do { no strict 'refs'; \%{"${role}::"}};
160     my $not_methods = $info->{not_methods};
161     +{
162       # grab all code entries that aren't in the not_methods list
163       map {
164         my $code = *{$stash->{$_}}{CODE};
165         # rely on the '' key we added in import for "no code here"
166         exists $not_methods->{$code||''} ? () : ($_ => $code)
167       } grep !(ref($stash->{$_}) eq 'SCALAR'), keys %$stash
168     };
169   };
170 }
171
172 sub methods_provided_by {
173   my ($me, $role) = @_;
174   die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
175   (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
176 }
177
178 sub _install_methods {
179   my ($me, $to, $role) = @_;
180
181   my $info = $INFO{$role};
182
183   my $methods = $me->_concrete_methods_of($role);
184
185   # grab target symbol table
186   my $stash = do { no strict 'refs'; \%{"${to}::"}};
187
188   # determine already extant methods of target
189   my %has_methods;
190   @has_methods{grep
191     +((ref($stash->{$_}) eq 'SCALAR') || (*{$stash->{$_}}{CODE})),
192     keys %$stash
193   } = ();
194
195   foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
196     no warnings 'once';
197     *{_getglob "${to}::${i}"} = $methods->{$i};
198   }
199 }
200
201 sub _install_modifiers {
202   my ($me, $to, $modifiers) = @_;
203   foreach my $modifier (@{$modifiers||[]}) {
204     Class::Method::Modifiers::install_modifier($to, @{$modifier});
205   }
206 }
207
208 sub does_role {
209   my ($package, $role) = @_;
210   return exists $APPLIED_TO{$package}{$role};
211 }
212
213 1;