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