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