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