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