Add various things
[gitmo/Mouse.git] / lib / Mouse / Meta / Role.pm
1 package Mouse::Meta::Role;
2 use strict;
3 use warnings;
4
5 use Mouse::Util qw(not_supported english_list);
6 use base qw(Mouse::Meta::Module);
7
8 sub method_metaclass(){ 'Mouse::Meta::Role::Method' } # required for get_method()
9
10 sub _new {
11     my $class = shift;
12
13     my %args  = @_;
14
15     $args{methods}          ||= {};
16     $args{attributes}       ||= {};
17     $args{required_methods} ||= [];
18     $args{roles}            ||= [];
19
20 #    return Mouse::Meta::Class->initialize($class)->new_object(%args)
21 #        if $class ne __PACKAGE__;
22
23     return bless \%args, $class;
24 }
25
26 sub create_anon_role{
27     my $self = shift;
28     return $self->create(undef, @_);
29 }
30
31 sub is_anon_role{
32     return exists $_[0]->{anon_serial_id};
33 }
34
35 sub get_roles { $_[0]->{roles} }
36
37 sub get_required_method_list{
38     return @{ $_[0]->{required_methods} };
39 }
40
41 sub add_required_methods {
42     my $self = shift;
43     my @methods = @_;
44     push @{$self->{required_methods}}, @methods;
45 }
46
47 sub requires_method {
48     my($self, $name) = @_;
49     return scalar( grep{ $_ eq $name } @{ $self->{required_methods} } ) != 0;
50 }
51
52 sub add_attribute {
53     my $self = shift;
54     my $name = shift;
55
56     $self->{attributes}->{$name} = (@_ == 1) ? $_[0] : { @_ };
57 }
58
59 sub _canonicalize_apply_args{
60     my($self, $applicant, %args) = @_;
61
62     if($applicant->isa('Mouse::Meta::Class')){
63         $args{_to} = 'class';
64     }
65     elsif($applicant->isa('Mouse::Meta::Role')){
66         $args{_to} = 'role';
67     }
68     else{
69         $args{_to} = 'instance';
70
71         not_supported 'Application::ToInstance';
72     }
73
74     if($args{alias} && !exists $args{-alias}){
75         $args{-alias} = $args{alias};
76     }
77     if($args{excludes} && !exists $args{-excludes}){
78         $args{-excludes} = $args{excludes};
79     }
80
81     if(my $excludes = $args{-excludes}){
82         $args{-excludes} = {}; # replace with a hash ref
83         if(ref $excludes){
84             %{$args{-excludes}} = (map{ $_ => undef } @{$excludes});
85         }
86         else{
87             $args{-excludes}{$excludes} = undef;
88         }
89     }
90
91     return \%args;
92 }
93
94 sub _check_required_methods{
95     my($role, $class, $args, @other_roles) = @_;
96
97     if($args->{_to} eq 'class'){
98         my $class_name = $class->name;
99         my $role_name  = $role->name;
100         my @missing;
101         foreach my $method_name(@{$role->{required_methods}}){
102             if(!$class_name->can($method_name)){
103                 my $has_method      = 0;
104
105                 foreach my $another_role_spec(@other_roles){
106                     my $another_role_name = $another_role_spec->[0];
107                     if($role_name ne $another_role_name && $another_role_name->can($method_name)){
108                         $has_method = 1;
109                         last;
110                     }
111                 }
112
113                 push @missing, $method_name if !$has_method;
114             }
115         }
116         if(@missing){
117             $class->throw_error("'$role_name' requires the "
118                 . (@missing == 1 ? 'method' : 'methods')
119                 . " "
120                 . english_list(map{ sprintf q{'%s'}, $_ } @missing)
121                 . " to be implemented by '$class_name'");
122         }
123     }
124     elsif($args->{_to} eq 'role'){
125         # apply role($role) to role($class)
126         foreach my $method_name($role->get_required_method_list){
127             next if $class->has_method($method_name); # already has it
128             $class->add_required_methods($method_name);
129         }
130     }
131
132     return;
133 }
134
135 sub _apply_methods{
136     my($role, $class, $args) = @_;
137
138     my $role_name  = $role->name;
139     my $class_name = $class->name;
140
141     my $alias    = $args->{-alias};
142     my $excludes = $args->{-excludes};
143
144     foreach my $method_name($role->get_method_list){
145         next if $method_name eq 'meta';
146
147         my $code = $role_name->can($method_name);
148
149         if(!exists $excludes->{$method_name}){
150             if(!$class->has_method($method_name)){
151                 $class->add_method($method_name => $code);
152             }
153         }
154
155         if($alias && $alias->{$method_name}){
156             my $dstname = $alias->{$method_name};
157
158             my $dstcode = do{ no strict 'refs'; *{$class_name . '::' . $dstname}{CODE} };
159
160             if(defined($dstcode) && $dstcode != $code){
161                 $class->throw_error("Cannot create a method alias if a local method of the same name exists");
162             }
163             else{
164                 $class->add_method($dstname => $code);
165             }
166         }
167     }
168
169     return;
170 }
171
172 sub _apply_attributes{
173     my($role, $class, $args) = @_;
174
175     if ($args->{_to} eq 'class') {
176         # apply role to class
177         for my $attr_name ($role->get_attribute_list) {
178             next if $class->has_attribute($attr_name);
179
180             my $spec = $role->get_attribute($attr_name);
181
182             my $attr_metaclass = 'Mouse::Meta::Attribute';
183             if ( my $metaclass_name = $spec->{metaclass} ) {
184                 $attr_metaclass = Mouse::Util::resolve_metaclass_alias(
185                     'Attribute',
186                     $metaclass_name
187                 );
188             }
189
190             $attr_metaclass->create($class, $attr_name => %$spec);
191         }
192     }
193     elsif($args->{_to} eq 'role'){
194         # apply role to role
195         for my $attr_name ($role->get_attribute_list) {
196             next if $class->has_attribute($attr_name);
197
198             my $spec = $role->get_attribute($attr_name);
199             $class->add_attribute($attr_name => $spec);
200         }
201     }
202
203     return;
204 }
205
206 sub _apply_modifiers{
207     my($role, $class, $args) = @_;
208
209     for my $modifier_type (qw/override before around after/) {
210         my $add_modifier = "add_${modifier_type}_method_modifier";
211         my $modifiers    = $role->{"${modifier_type}_method_modifiers"};
212
213         while(my($method_name, $modifier_codes) = each %{$modifiers}){
214             foreach my $code(ref($modifier_codes) eq 'ARRAY' ? @{$modifier_codes} : $modifier_codes){
215                 $class->$add_modifier($method_name => $code);
216             }
217         }
218     }
219     return;
220 }
221
222 sub _append_roles{
223     my($role, $class, $args) = @_;
224
225     my $roles = ($args->{_to} eq 'class') ? $class->roles : $class->get_roles;
226
227     foreach my $r($role, @{$role->get_roles}){
228         if(!$class->does_role($r->name)){
229             push @{$roles}, $r;
230         }
231     }
232     return;
233 }
234
235 # Moose uses Application::ToInstance, Application::ToClass, Application::ToRole
236 sub apply {
237     my $self      = shift;
238     my $applicant = shift;
239
240     my $args = $self->_canonicalize_apply_args($applicant, @_);
241
242     $self->_check_required_methods($applicant, $args);
243     $self->_apply_methods($applicant, $args);
244     $self->_apply_attributes($applicant, $args);
245     $self->_apply_modifiers($applicant, $args);
246     $self->_append_roles($applicant, $args);
247     return;
248 }
249
250 sub combine_apply {
251     my(undef, $class, @roles) = @_;
252
253     if($class->isa('Mouse::Object')){
254         not_supported 'Application::ToInstance';
255     }
256
257     # check conflicting
258     my %method_provided;
259     my @method_conflicts;
260     my %attr_provided;
261     my %override_provided;
262
263     foreach my $role_spec (@roles) {
264         my $role      = $role_spec->[0]->meta;
265         my $role_name = $role->name;
266
267         # methods
268         foreach my $method_name($role->get_method_list){
269             next if $class->has_method($method_name); # manually resolved
270
271             my $code = do{ no strict 'refs'; \&{ $role_name . '::' . $method_name } };
272
273             my $c = $method_provided{$method_name};
274
275             if($c && $c->[0] != $code){
276                 push @{$c}, $role;
277                 push @method_conflicts, $c;
278             }
279             else{
280                 $method_provided{$method_name} = [$code, $method_name, $role];
281             }
282         }
283
284         # attributes
285         foreach my $attr_name($role->get_attribute_list){
286             my $attr = $role->get_attribute($attr_name);
287             my $c    = $attr_provided{$attr_name};
288             if($c && $c != $attr){
289                 $class->throw_error("We have encountered an attribute conflict with '$attr_name' "\r
290                                    . "during composition. This is fatal error and cannot be disambiguated.")
291             }
292             else{
293                 $attr_provided{$attr_name} = $attr;
294             }
295         }
296
297         # override modifiers
298         foreach my $method_name($role->get_method_modifier_list('override')){
299             my $override = $role->get_override_method_modifier($method_name);
300             my $c        = $override_provided{$method_name};
301             if($c && $c != $override){
302                 $class->throw_error( "We have encountered an 'override' method conflict with '$method_name' during "\r
303                                    . "composition (Two 'override' methods of the same name encountered). "\r
304                                    . "This is fatal error.")
305             }
306             else{
307                 $override_provided{$method_name} = $override;
308             }
309         }
310     }
311     if(@method_conflicts){
312         my $error;
313
314         if(@method_conflicts == 1){
315             my($code, $method_name, @roles) = @{$method_conflicts[0]};
316             $class->throw_error(
317                 sprintf q{Due to a method name conflict in roles %s, the method '%s' must be implemented or excluded by '%s'},
318                     english_list(map{ sprintf q{'%s'}, $_->name } @roles), $method_name, $class->name
319             );
320         }
321         else{
322             @method_conflicts = sort { $a->[0] cmp $b->[0] } @method_conflicts; # to avoid hash-ordering bugs
323             my $methods = english_list(map{ sprintf q{'%s'}, $_->[1] } @method_conflicts);
324             my $roles   = english_list(
325                 map{ sprintf q{'%s'}, $_->name }
326                 map{ my($code, $method_name, @roles) = @{$_}; @roles } @method_conflicts
327             );
328
329             $class->throw_error(
330                 sprintf q{Due to method name conflicts in roles %s, the methods %s must be implemented or excluded by '%s'},
331                     $roles, $methods, $class->name
332             );
333         }
334     }
335
336     foreach my $role_spec (@roles) {
337         my($role_name, $args) = @{$role_spec};
338
339         my $role = $role_name->meta;
340
341         $args = $role->_canonicalize_apply_args($class, %{$args});
342
343         $role->_check_required_methods($class, $args, @roles);
344         $role->_apply_methods($class, $args);
345         $role->_apply_attributes($class, $args);
346         $role->_apply_modifiers($class, $args);
347         $role->_append_roles($class, $args);
348     }
349     return;
350 }
351
352 for my $modifier_type (qw/before after around/) {
353
354     my $modifier = "${modifier_type}_method_modifiers";
355     my $add_method_modifier =  sub {
356         my ($self, $method_name, $method) = @_;
357
358         push @{ $self->{$modifier}->{$method_name} ||= [] }, $method;
359         return;
360     };
361     my $has_method_modifiers = sub{
362         my($self, $method_name) = @_;
363         my $m = $self->{$modifier}->{$method_name};
364         return $m && @{$m} != 0;
365     };
366     my $get_method_modifiers = sub {
367         my ($self, $method_name) = @_;
368         return @{ $self->{$modifier}->{$method_name} ||= [] }
369     };
370
371     no strict 'refs';
372     *{ 'add_' . $modifier_type . '_method_modifier'  } = $add_method_modifier;
373     *{ 'has_' . $modifier_type . '_method_modifiers' } = $has_method_modifiers;
374     *{ 'get_' . $modifier_type . '_method_modifiers' } = $get_method_modifiers;
375 }
376
377 sub add_override_method_modifier{
378     my($self, $method_name, $method) = @_;
379
380     if($self->has_method($method_name)){
381         # This error happens in the override keyword or during role composition,
382         # so I added a message, "A local method of ...", only for compatibility (gfx)
383         $self->throw_error("Cannot add an override of method '$method_name' "\r
384                    . "because there is a local version of '$method_name'"
385                    . "(A local method of the same name as been found)");
386     }
387
388     $self->{override_method_modifiers}->{$method_name} = $method;
389 }
390
391 sub has_override_method_modifier {\r
392     my ($self, $method_name) = @_;\r
393     return exists $self->{override_method_modifiers}->{$method_name};\r
394 }\r
395 \r
396 sub get_override_method_modifier {\r
397     my ($self, $method_name) = @_;\r
398     return $self->{override_method_modifiers}->{$method_name};\r
399 }
400
401 sub get_method_modifier_list {
402     my($self, $modifier_type) = @_;
403
404     return keys %{ $self->{$modifier_type . '_method_modifiers'} };
405 }
406
407 # This is currently not passing all the Moose tests.
408 sub does_role {
409     my ($self, $role_name) = @_;
410
411     (defined $role_name)
412         || $self->throw_error("You must supply a role name to look for");
413
414     # if we are it,.. then return true
415     return 1 if $role_name eq $self->name;
416     # otherwise.. check our children
417     for my $role (@{ $self->get_roles }) {
418         return 1 if $role->does_role($role_name);
419     }
420     return 0;
421 }
422
423
424 1;
425