e5596e7dec410729b117c9f9479f6ec2535f6d06
[gitmo/Moose.git] / lib / Moose / Meta / Role.pm
1
2 package Moose::Meta::Role;
3
4 use strict;
5 use warnings;
6 use metaclass;
7
8 use Scalar::Util 'blessed';
9
10 our $VERSION   = '0.57';
11 $VERSION = eval $VERSION;
12 our $AUTHORITY = 'cpan:STEVAN';
13
14 use Moose::Meta::Class;
15 use Moose::Meta::Role::Method;
16 use Moose::Meta::Role::Method::Required;
17
18 use base 'Class::MOP::Module';
19
20 ## ------------------------------------------------------------------
21 ## NOTE:
22 ## I normally don't do this, but I am doing
23 ## a whole bunch of meta-programmin in this
24 ## module, so it just makes sense. For a clearer
25 ## picture of what is going on in the next 
26 ## several lines of code, look at the really 
27 ## big comment at the end of this file (right
28 ## before the POD).
29 ## - SL
30 ## ------------------------------------------------------------------
31
32 my $META = __PACKAGE__->meta;
33
34 ## ------------------------------------------------------------------
35 ## attributes ...
36
37 # NOTE:
38 # since roles are lazy, we hold all the attributes
39 # of the individual role in 'statis' until which
40 # time when it is applied to a class. This means
41 # keeping a lot of things in hash maps, so we are
42 # using a little of that meta-programmin' magic
43 # here an saving lots of extra typin. And since 
44 # many of these attributes above require similar
45 # functionality to support them, so we again use
46 # the wonders of meta-programmin' to deliver a
47 # very compact solution to this normally verbose
48 # problem.
49 # - SL
50
51 foreach my $action (
52     {
53         name        => 'excluded_roles_map',
54         attr_reader => 'get_excluded_roles_map' ,
55         methods     => {
56             add       => 'add_excluded_roles',
57             get_list  => 'get_excluded_roles_list',
58             existence => 'excludes_role',
59         }
60     },
61     {
62         name        => 'required_methods',
63         attr_reader => 'get_required_methods_map',
64         methods     => {
65             add       => 'add_required_methods',
66             remove    => 'remove_required_methods',
67             get_list  => 'get_required_method_list',
68             existence => 'requires_method',
69         }
70     },  
71     {
72         name        => 'attribute_map',
73         attr_reader => 'get_attribute_map',
74         methods     => {
75             get       => 'get_attribute',
76             get_list  => 'get_attribute_list',
77             existence => 'has_attribute',
78             remove    => 'remove_attribute',
79         }
80     }
81 ) {
82
83     my $attr_reader = $action->{attr_reader};
84     my $methods     = $action->{methods};
85
86     # create the attribute
87     $META->add_attribute($action->{name} => (
88         reader  => $attr_reader,
89         default => sub { {} }
90     ));
91
92     # create some helper methods
93     $META->add_method($methods->{add} => sub {
94         my ($self, @values) = @_;
95         $self->$attr_reader->{$_} = undef foreach @values;
96     }) if exists $methods->{add};
97
98     $META->add_method($methods->{get_list} => sub {
99         my ($self) = @_;
100         keys %{$self->$attr_reader};
101     }) if exists $methods->{get_list};
102
103     $META->add_method($methods->{get} => sub {
104         my ($self, $name) = @_;
105         $self->$attr_reader->{$name}
106     }) if exists $methods->{get};
107
108     $META->add_method($methods->{existence} => sub {
109         my ($self, $name) = @_;
110         exists $self->$attr_reader->{$name} ? 1 : 0;
111     }) if exists $methods->{existence};
112
113     $META->add_method($methods->{remove} => sub {
114         my ($self, @values) = @_;
115         delete $self->$attr_reader->{$_} foreach @values;
116     }) if exists $methods->{remove};
117 }
118
119 ## some things don't always fit, so they go here ...
120
121 sub add_attribute {
122     my $self = shift;
123     my $name = shift;
124     (defined $name && $name)
125         || Moose->throw_error("You must provide a name for the attribute");
126     my $attr_desc;
127     if (scalar @_ == 1 && ref($_[0]) eq 'HASH') {
128         $attr_desc = $_[0];
129     }
130     else {
131         $attr_desc = { @_ };
132     }
133     $self->get_attribute_map->{$name} = $attr_desc;
134 }
135
136 # DEPRECATED 
137 # sub _clean_up_required_methods {
138 #     my $self = shift;
139 #     foreach my $method ($self->get_required_method_list) {
140 #         $self->remove_required_methods($method)
141 #             if $self->has_method($method);
142 #     }
143 # }
144
145 ## ------------------------------------------------------------------
146 ## method modifiers
147
148 # NOTE:
149 # the before/around/after method modifiers are
150 # stored by name, but there can be many methods
151 # then associated with that name. So again we have
152 # lots of similar functionality, so we can do some
153 # meta-programmin' and save some time.
154 # - SL
155
156 foreach my $modifier_type (qw[ before around after ]) {
157
158     my $attr_reader = "get_${modifier_type}_method_modifiers_map";
159     
160     # create the attribute ...
161     $META->add_attribute("${modifier_type}_method_modifiers" => (
162         reader  => $attr_reader,
163         default => sub { {} }
164     ));  
165
166     # and some helper methods ...
167     $META->add_method("get_${modifier_type}_method_modifiers" => sub {
168         my ($self, $method_name) = @_;
169         #return () unless exists $self->$attr_reader->{$method_name};
170         @{$self->$attr_reader->{$method_name}};
171     });
172
173     $META->add_method("has_${modifier_type}_method_modifiers" => sub {
174         my ($self, $method_name) = @_;
175         # NOTE:
176         # for now we assume that if it exists,..
177         # it has at least one modifier in it
178         (exists $self->$attr_reader->{$method_name}) ? 1 : 0;
179     });
180
181     $META->add_method("add_${modifier_type}_method_modifier" => sub {
182         my ($self, $method_name, $method) = @_;
183
184         $self->$attr_reader->{$method_name} = []
185             unless exists $self->$attr_reader->{$method_name};
186
187         my $modifiers = $self->$attr_reader->{$method_name};
188
189         # NOTE:
190         # check to see that we aren't adding the
191         # same code twice. We err in favor of the
192         # first on here, this may not be as expected
193         foreach my $modifier (@{$modifiers}) {
194             return if $modifier == $method;
195         }
196
197         push @{$modifiers} => $method;
198     });
199
200 }
201
202 ## ------------------------------------------------------------------
203 ## override method mofidiers
204
205 $META->add_attribute('override_method_modifiers' => (
206     reader  => 'get_override_method_modifiers_map',
207     default => sub { {} }
208 ));
209
210 # NOTE:
211 # these are a little different because there
212 # can only be one per name, whereas the other
213 # method modifiers can have multiples.
214 # - SL
215
216 sub add_override_method_modifier {
217     my ($self, $method_name, $method) = @_;
218     (!$self->has_method($method_name))
219         || Moose->throw_error("Cannot add an override of method '$method_name' " .
220                    "because there is a local version of '$method_name'");
221     $self->get_override_method_modifiers_map->{$method_name} = $method;
222 }
223
224 sub has_override_method_modifier {
225     my ($self, $method_name) = @_;
226     # NOTE:
227     # for now we assume that if it exists,..
228     # it has at least one modifier in it
229     (exists $self->get_override_method_modifiers_map->{$method_name}) ? 1 : 0;
230 }
231
232 sub get_override_method_modifier {
233     my ($self, $method_name) = @_;
234     $self->get_override_method_modifiers_map->{$method_name};
235 }
236
237 ## general list accessor ...
238
239 sub get_method_modifier_list {
240     my ($self, $modifier_type) = @_;
241     my $accessor = "get_${modifier_type}_method_modifiers_map";
242     keys %{$self->$accessor};
243 }
244
245 sub reset_package_cache_flag  { (shift)->{'_package_cache_flag'} = undef }
246 sub update_package_cache_flag {
247     my $self = shift;
248     $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
249 }
250
251
252
253 ## ------------------------------------------------------------------
254 ## subroles
255
256 __PACKAGE__->meta->add_attribute('roles' => (
257     reader  => 'get_roles',
258     default => sub { [] }
259 ));
260
261 sub add_role {
262     my ($self, $role) = @_;
263     (blessed($role) && $role->isa('Moose::Meta::Role'))
264         || Moose->throw_error("Roles must be instances of Moose::Meta::Role");
265     push @{$self->get_roles} => $role;
266     $self->reset_package_cache_flag;
267 }
268
269 sub calculate_all_roles {
270     my $self = shift;
271     my %seen;
272     grep {
273         !$seen{$_->name}++
274     } ($self, map {
275                   $_->calculate_all_roles
276               } @{ $self->get_roles });
277 }
278
279 sub does_role {
280     my ($self, $role_name) = @_;
281     (defined $role_name)
282         || Moose->throw_error("You must supply a role name to look for");
283     # if we are it,.. then return true
284     return 1 if $role_name eq $self->name;
285     # otherwise.. check our children
286     foreach my $role (@{$self->get_roles}) {
287         return 1 if $role->does_role($role_name);
288     }
289     return 0;
290 }
291
292 ## ------------------------------------------------------------------
293 ## methods
294
295 sub method_metaclass { 'Moose::Meta::Role::Method' }
296
297 sub get_method_map {
298     my $self = shift;
299
300     my $current = Class::MOP::check_package_cache_flag($self->name);
301
302     if (defined $self->{'_package_cache_flag'} && $self->{'_package_cache_flag'} == $current) {
303         return $self->{'methods'} ||= {};
304     }
305
306     $self->{_package_cache_flag} = $current;
307
308     my $map  = $self->{'methods'} ||= {};
309
310     my $role_name        = $self->name;
311     my $method_metaclass = $self->method_metaclass;
312
313     my %all_code = $self->get_all_package_symbols('CODE');
314
315     foreach my $symbol (keys %all_code) {
316         my $code = $all_code{$symbol};
317
318         next if exists  $map->{$symbol} &&
319                 defined $map->{$symbol} &&
320                         $map->{$symbol}->body == $code;
321
322         my ($pkg, $name) = Class::MOP::get_code_info($code);
323
324         if ($pkg->can('meta')
325             # NOTE:
326             # we don't know what ->meta we are calling
327             # here, so we need to be careful cause it
328             # just might blow up at us, or just complain
329             # loudly (in the case of Curses.pm) so we
330             # just be a little overly cautious here.
331             # - SL
332             && eval { no warnings; blessed($pkg->meta) } # FIXME calls meta
333             && $pkg->meta->isa('Moose::Meta::Role')) {
334             my $role = $pkg->meta->name;
335             next unless $self->does_role($role);
336         }
337         else {
338             # NOTE:
339             # in 5.10 constant.pm the constants show up 
340             # as being in the right package, but in pre-5.10
341             # they show up as constant::__ANON__ so we 
342             # make an exception here to be sure that things
343             # work as expected in both.
344             # - SL
345             unless ($pkg eq 'constant' && $name eq '__ANON__') {
346                 next if ($pkg  || '') ne $role_name ||
347                         (($name || '') ne '__ANON__' && ($pkg  || '') ne $role_name);
348             }            
349         }
350         
351         $map->{$symbol} = $method_metaclass->wrap(
352             $code,
353             package_name => $role_name,
354             name         => $name            
355         );
356     }
357
358     return $map;    
359 }
360
361 sub get_method { 
362     my ($self, $name) = @_;
363     $self->get_method_map->{$name};
364 }
365
366 sub has_method {
367     my ($self, $name) = @_;
368     exists $self->get_method_map->{$name} ? 1 : 0
369 }
370
371 # FIXME this is copypasated from Class::MOP::Class
372 # refactor to inherit from some common base
373 sub wrap_method_body {
374     my ( $self, %args ) = @_;
375
376     ('CODE' eq ref $args{body})
377         || Moose->throw_error("Your code block must be a CODE reference");
378
379     $self->method_metaclass->wrap(
380         package_name => $self->name,
381         %args,
382     );
383 }
384
385 sub add_method {
386     my ($self, $method_name, $method) = @_;
387     (defined $method_name && $method_name)
388     || Moose->throw_error("You must define a method name");
389
390     my $body;
391     if (blessed($method)) {
392         $body = $method->body;
393         if ($method->package_name ne $self->name) {
394             $method = $method->clone(
395                 package_name => $self->name,
396                 name         => $method_name            
397             ) if $method->can('clone');
398         }
399     }
400     else {
401         $body = $method;
402         $method = $self->wrap_method_body( body => $body, name => $method_name );
403     }
404
405     $method->attach_to_class($self);
406
407     $self->get_method_map->{$method_name} = $method;
408
409     my $full_method_name = ($self->name . '::' . $method_name);
410     $self->add_package_symbol(
411         { sigil => '&', type => 'CODE', name => $method_name },
412         Class::MOP::subname($full_method_name => $body)
413     );
414
415     $self->update_package_cache_flag; # still valid, since we just added the method to the map, and if it was invalid before that then get_method_map updated it
416 }
417
418 sub find_method_by_name { (shift)->get_method(@_) }
419
420 sub get_method_list {
421     my $self = shift;
422     grep { !/^meta$/ } keys %{$self->get_method_map};
423 }
424
425 sub alias_method {
426     my $self = shift;
427
428     $self->add_method(@_);
429 }
430
431 ## ------------------------------------------------------------------
432 ## role construction
433 ## ------------------------------------------------------------------
434
435 sub apply {
436     my ($self, $other, @args) = @_;
437
438     (blessed($other))
439         || Moose->throw_error("You must pass in an blessed instance");
440         
441     if ($other->isa('Moose::Meta::Role')) {
442         require Moose::Meta::Role::Application::ToRole;
443         return Moose::Meta::Role::Application::ToRole->new(@args)->apply($self, $other);
444     }
445     elsif ($other->isa('Moose::Meta::Class')) {
446         require Moose::Meta::Role::Application::ToClass;
447         return Moose::Meta::Role::Application::ToClass->new(@args)->apply($self, $other);
448     }  
449     else {
450         require Moose::Meta::Role::Application::ToInstance;
451         return Moose::Meta::Role::Application::ToInstance->new(@args)->apply($self, $other);        
452     }  
453 }
454
455 sub combine {
456     my ($class, @role_specs) = @_;
457     
458     require Moose::Meta::Role::Application::RoleSummation;
459     require Moose::Meta::Role::Composite;  
460     
461     my (@roles, %role_params);
462     while (@role_specs) {
463         my ($role, $params) = @{ splice @role_specs, 0, 1 };
464         push @roles => $role->meta;
465         next unless defined $params;
466         $role_params{$role} = $params; 
467     }
468     
469     my $c = Moose::Meta::Role::Composite->new(roles => \@roles);
470     Moose::Meta::Role::Application::RoleSummation->new(
471         role_params => \%role_params
472     )->apply($c);
473     
474     return $c;
475 }
476
477 #####################################################################
478 ## NOTE:
479 ## This is Moose::Meta::Role as defined by Moose (plus the use of 
480 ## MooseX::AttributeHelpers module). It is here as a reference to 
481 ## make it easier to see what is happening above with all the meta
482 ## programming. - SL
483 #####################################################################
484 #
485 # has 'roles' => (
486 #     metaclass => 'Collection::Array',
487 #     reader    => 'get_roles',
488 #     isa       => 'ArrayRef[Moose::Meta::Roles]',
489 #     default   => sub { [] },
490 #     provides  => {
491 #         'push' => 'add_role',
492 #     }
493 # );
494
495 # has 'excluded_roles_map' => (
496 #     metaclass => 'Collection::Hash',
497 #     reader    => 'get_excluded_roles_map',
498 #     isa       => 'HashRef[Str]',
499 #     provides  => {
500 #         # Not exactly set, cause it sets multiple
501 #         'set'    => 'add_excluded_roles',
502 #         'keys'   => 'get_excluded_roles_list',
503 #         'exists' => 'excludes_role',
504 #     }
505 # );
506
507 # has 'attribute_map' => (
508 #     metaclass => 'Collection::Hash',
509 #     reader    => 'get_attribute_map',
510 #     isa       => 'HashRef[Str]',    
511 #     provides => {
512 #         # 'set'  => 'add_attribute' # has some special crap in it
513 #         'get'    => 'get_attribute',
514 #         'keys'   => 'get_attribute_list',
515 #         'exists' => 'has_attribute',
516 #         # Not exactly delete, cause it sets multiple
517 #         'delete' => 'remove_attribute',    
518 #     }
519 # );
520
521 # has 'required_methods' => (
522 #     metaclass => 'Collection::Hash',
523 #     reader    => 'get_required_methods_map',
524 #     isa       => 'HashRef[Str]',
525 #     provides  => {    
526 #         # not exactly set, or delete since it works for multiple 
527 #         'set'    => 'add_required_methods',
528 #         'delete' => 'remove_required_methods',
529 #         'keys'   => 'get_required_method_list',
530 #         'exists' => 'requires_method',    
531 #     }
532 # );
533
534 # # the before, around and after modifiers are 
535 # # HASH keyed by method-name, with ARRAY of 
536 # # CODE refs to apply in that order
537
538 # has 'before_method_modifiers' => (
539 #     metaclass => 'Collection::Hash',    
540 #     reader    => 'get_before_method_modifiers_map',
541 #     isa       => 'HashRef[ArrayRef[CodeRef]]',
542 #     provides  => {
543 #         'keys'   => 'get_before_method_modifiers',
544 #         'exists' => 'has_before_method_modifiers',   
545 #         # This actually makes sure there is an 
546 #         # ARRAY at the given key, and pushed onto
547 #         # it. It also checks for duplicates as well
548 #         # 'add'  => 'add_before_method_modifier'     
549 #     }    
550 # );
551
552 # has 'after_method_modifiers' => (
553 #     metaclass => 'Collection::Hash',    
554 #     reader    =>'get_after_method_modifiers_map',
555 #     isa       => 'HashRef[ArrayRef[CodeRef]]',
556 #     provides  => {
557 #         'keys'   => 'get_after_method_modifiers',
558 #         'exists' => 'has_after_method_modifiers', 
559 #         # This actually makes sure there is an 
560 #         # ARRAY at the given key, and pushed onto
561 #         # it. It also checks for duplicates as well          
562 #         # 'add'  => 'add_after_method_modifier'     
563 #     }    
564 # );
565 #     
566 # has 'around_method_modifiers' => (
567 #     metaclass => 'Collection::Hash',    
568 #     reader    =>'get_around_method_modifiers_map',
569 #     isa       => 'HashRef[ArrayRef[CodeRef]]',
570 #     provides  => {
571 #         'keys'   => 'get_around_method_modifiers',
572 #         'exists' => 'has_around_method_modifiers',   
573 #         # This actually makes sure there is an 
574 #         # ARRAY at the given key, and pushed onto
575 #         # it. It also checks for duplicates as well        
576 #         # 'add'  => 'add_around_method_modifier'     
577 #     }    
578 # );
579
580 # # override is similar to the other modifiers
581 # # except that it is not an ARRAY of code refs
582 # # but instead just a single name->code mapping
583 #     
584 # has 'override_method_modifiers' => (
585 #     metaclass => 'Collection::Hash',    
586 #     reader    =>'get_override_method_modifiers_map',
587 #     isa       => 'HashRef[CodeRef]',   
588 #     provides  => {
589 #         'keys'   => 'get_override_method_modifier',
590 #         'exists' => 'has_override_method_modifier',   
591 #         'add'    => 'add_override_method_modifier', # checks for local method ..     
592 #     }
593 # );
594 #     
595 #####################################################################
596
597
598 1;
599
600 __END__
601
602 =pod
603
604 =head1 NAME
605
606 Moose::Meta::Role - The Moose Role metaclass
607
608 =head1 DESCRIPTION
609
610 Please see L<Moose::Role> for more information about roles.
611 For the most part, this has no user-serviceable parts inside
612 this module. It's API is still subject to some change (although
613 probably not that much really).
614
615 =head1 METHODS
616
617 =over 4
618
619 =item B<meta>
620
621 =item B<new>
622
623 =item B<apply>
624
625 =item B<apply_to_metaclass_instance>
626
627 =item B<combine>
628
629 =back
630
631 =over 4
632
633 =item B<name>
634
635 =item B<version>
636
637 =item B<role_meta>
638
639 =back
640
641 =over 4
642
643 =item B<get_roles>
644
645 =item B<add_role>
646
647 =item B<does_role>
648
649 =back
650
651 =over 4
652
653 =item B<add_excluded_roles>
654
655 =item B<excludes_role>
656
657 =item B<get_excluded_roles_list>
658
659 =item B<get_excluded_roles_map>
660
661 =item B<calculate_all_roles>
662
663 =back
664
665 =over 4
666
667 =item B<method_metaclass>
668
669 =item B<find_method_by_name>
670
671 =item B<get_method>
672
673 =item B<has_method>
674
675 =item B<add_method>
676
677 =item B<wrap_method_body>
678
679 =item B<alias_method>
680
681 =item B<get_method_list>
682
683 =item B<get_method_map>
684
685 =item B<update_package_cache_flag>
686
687 =item B<reset_package_cache_flag>
688
689 =back
690
691 =over 4
692
693 =item B<add_attribute>
694
695 =item B<has_attribute>
696
697 =item B<get_attribute>
698
699 =item B<get_attribute_list>
700
701 =item B<get_attribute_map>
702
703 =item B<remove_attribute>
704
705 =back
706
707 =over 4
708
709 =item B<add_required_methods>
710
711 =item B<remove_required_methods>
712
713 =item B<get_required_method_list>
714
715 =item B<get_required_methods_map>
716
717 =item B<requires_method>
718
719 =back
720
721 =over 4
722
723 =item B<add_after_method_modifier>
724
725 =item B<add_around_method_modifier>
726
727 =item B<add_before_method_modifier>
728
729 =item B<add_override_method_modifier>
730
731 =over 4
732
733 =back
734
735 =item B<has_after_method_modifiers>
736
737 =item B<has_around_method_modifiers>
738
739 =item B<has_before_method_modifiers>
740
741 =item B<has_override_method_modifier>
742
743 =over 4
744
745 =back
746
747 =item B<get_after_method_modifiers>
748
749 =item B<get_around_method_modifiers>
750
751 =item B<get_before_method_modifiers>
752
753 =item B<get_method_modifier_list>
754
755 =over 4
756
757 =back
758
759 =item B<get_override_method_modifier>
760
761 =item B<get_after_method_modifiers_map>
762
763 =item B<get_around_method_modifiers_map>
764
765 =item B<get_before_method_modifiers_map>
766
767 =item B<get_override_method_modifiers_map>
768
769 =back
770
771 =head1 BUGS
772
773 All complex software has bugs lurking in it, and this module is no
774 exception. If you find a bug please either email me, or add the bug
775 to cpan-RT.
776
777 =head1 AUTHOR
778
779 Stevan Little E<lt>stevan@iinteractive.comE<gt>
780
781 =head1 COPYRIGHT AND LICENSE
782
783 Copyright 2006-2008 by Infinity Interactive, Inc.
784
785 L<http://www.iinteractive.com>
786
787 This library is free software; you can redistribute it and/or modify
788 it under the same terms as Perl itself.
789
790 =cut