2 package Moose::Meta::Role;
8 use Scalar::Util 'blessed';
10 use Devel::GlobalDestruction 'in_global_destruction';
12 our $VERSION = '0.93';
13 $VERSION = eval $VERSION;
14 our $AUTHORITY = 'cpan:STEVAN';
16 use Moose::Meta::Class;
17 use Moose::Meta::Role::Method;
18 use Moose::Meta::Role::Method::Required;
19 use Moose::Meta::Role::Method::Conflicting;
20 use Moose::Util qw( ensure_all_roles );
22 use base 'Class::MOP::Module', 'Class::MOP::HasAttributes';
24 ## ------------------------------------------------------------------
26 ## I normally don't do this, but I am doing
27 ## a whole bunch of meta-programmin in this
28 ## module, so it just makes sense. For a clearer
29 ## picture of what is going on in the next
30 ## several lines of code, look at the really
31 ## big comment at the end of this file (right
34 ## ------------------------------------------------------------------
36 my $META = __PACKAGE__->meta;
38 ## ------------------------------------------------------------------
42 # since roles are lazy, we hold all the attributes
43 # of the individual role in 'statis' until which
44 # time when it is applied to a class. This means
45 # keeping a lot of things in hash maps, so we are
46 # using a little of that meta-programmin' magic
47 # here an saving lots of extra typin. And since
48 # many of these attributes above require similar
49 # functionality to support them, so we again use
50 # the wonders of meta-programmin' to deliver a
51 # very compact solution to this normally verbose
57 name => 'excluded_roles_map',
58 attr_reader => 'get_excluded_roles_map' ,
60 add => 'add_excluded_roles',
61 get_keys => 'get_excluded_roles_list',
62 existence => 'excludes_role',
66 name => 'required_methods',
67 attr_reader => 'get_required_methods_map',
69 remove => 'remove_required_methods',
70 get_values => 'get_required_method_list',
71 existence => 'requires_method',
76 my $attr_reader = $action->{attr_reader};
77 my $methods = $action->{methods};
79 # create the attribute
80 $META->add_attribute($action->{name} => (
81 reader => $attr_reader,
85 # create some helper methods
86 $META->add_method($methods->{add} => sub {
87 my ($self, @values) = @_;
88 $self->$attr_reader->{$_} = undef foreach @values;
89 }) if exists $methods->{add};
91 $META->add_method($methods->{get_keys} => sub {
93 keys %{$self->$attr_reader};
94 }) if exists $methods->{get_keys};
96 $META->add_method($methods->{get_values} => sub {
98 values %{$self->$attr_reader};
99 }) if exists $methods->{get_values};
101 $META->add_method($methods->{get} => sub {
102 my ($self, $name) = @_;
103 $self->$attr_reader->{$name}
104 }) if exists $methods->{get};
106 $META->add_method($methods->{existence} => sub {
107 my ($self, $name) = @_;
108 exists $self->$attr_reader->{$name} ? 1 : 0;
109 }) if exists $methods->{existence};
111 $META->add_method($methods->{remove} => sub {
112 my ($self, @values) = @_;
113 delete $self->$attr_reader->{$_} foreach @values;
114 }) if exists $methods->{remove};
117 $META->add_attribute(
119 reader => 'method_metaclass',
120 default => 'Moose::Meta::Role::Method',
123 $META->add_attribute(
124 'required_method_metaclass',
125 reader => 'required_method_metaclass',
126 default => 'Moose::Meta::Role::Method::Required',
129 $META->add_attribute(
130 'conflicting_method_metaclass',
131 reader => 'conflicting_method_metaclass',
132 default => 'Moose::Meta::Role::Method::Conflicting',
135 $META->add_attribute(
136 'application_to_class_class',
137 reader => 'application_to_class_class',
138 default => 'Moose::Meta::Role::Application::ToClass',
141 $META->add_attribute(
142 'application_to_role_class',
143 reader => 'application_to_role_class',
144 default => 'Moose::Meta::Role::Application::ToRole',
147 $META->add_attribute(
148 'application_to_instance_class',
149 reader => 'application_to_instance_class',
150 default => 'Moose::Meta::Role::Application::ToInstance',
153 $META->add_attribute(
154 'composition_class_roles',
155 reader => 'composition_class_roles',
156 predicate => 'has_composition_class_roles',
159 # More or less copied from Moose::Meta::Class
163 return Class::MOP::get_metaclass_by_name($pkg)
164 || $class->SUPER::initialize(
166 'attribute_metaclass' => 'Moose::Meta::Attribute',
172 # XXX - copied from Moose::Meta::Class
176 # Since this _is_ a role, it needs to be loaded after Moose::Meta::Role is
177 # done setting itself up.
178 unless ($Role_Loaded) {
179 require Moose::Meta::Attribute::Trait::InRole;
184 blessed $_[0] && $_[0]->isa('Class::MOP::Attribute')
185 ? $self->_ensure_attribute_trait($_[0] )
186 : $self->_process_attribute(@_)
189 $self->SUPER::add_attribute($attr);
194 sub _ensure_attribute_trait {
198 ensure_all_roles( $attr, 'Moose::Meta::Attribute::Trait::InRole' );
203 sub _process_attribute {
204 my ( $self, $name, @args ) = @_;
206 my %args = scalar @args == 1
207 && ref( $args[0] ) eq 'HASH' ? %{ $args[0] } : @args;
209 if ( $args{traits} ) {
210 push @{ $args{traits} }, 'Moose::Meta::Attribute::Trait::InRole';
213 $args{traits} = ['Moose::Meta::Attribute::Trait::InRole'];
216 $self->attribute_metaclass->interpolate_class_and_new( $name, %args );
219 sub add_required_methods {
224 if (!blessed($method)) {
225 $method = $self->required_method_metaclass->new(
229 $self->get_required_methods_map->{$method->name} = $method;
233 sub add_conflicting_method {
237 if (@_ == 1 && blessed($_[0])) {
241 $method = $self->conflicting_method_metaclass->new(@_);
244 $self->add_required_methods($method);
247 ## ------------------------------------------------------------------
251 # the before/around/after method modifiers are
252 # stored by name, but there can be many methods
253 # then associated with that name. So again we have
254 # lots of similar functionality, so we can do some
255 # meta-programmin' and save some time.
258 foreach my $modifier_type (qw[ before around after ]) {
260 my $attr_reader = "get_${modifier_type}_method_modifiers_map";
262 # create the attribute ...
263 $META->add_attribute("${modifier_type}_method_modifiers" => (
264 reader => $attr_reader,
265 default => sub { {} }
268 # and some helper methods ...
269 $META->add_method("get_${modifier_type}_method_modifiers" => sub {
270 my ($self, $method_name) = @_;
271 #return () unless exists $self->$attr_reader->{$method_name};
272 my $mm = $self->$attr_reader->{$method_name};
276 $META->add_method("has_${modifier_type}_method_modifiers" => sub {
277 my ($self, $method_name) = @_;
279 # for now we assume that if it exists,..
280 # it has at least one modifier in it
281 (exists $self->$attr_reader->{$method_name}) ? 1 : 0;
284 $META->add_method("add_${modifier_type}_method_modifier" => sub {
285 my ($self, $method_name, $method) = @_;
287 $self->$attr_reader->{$method_name} = []
288 unless exists $self->$attr_reader->{$method_name};
290 my $modifiers = $self->$attr_reader->{$method_name};
293 # check to see that we aren't adding the
294 # same code twice. We err in favor of the
295 # first on here, this may not be as expected
296 foreach my $modifier (@{$modifiers}) {
297 return if $modifier == $method;
300 push @{$modifiers} => $method;
305 ## ------------------------------------------------------------------
306 ## override method mofidiers
308 $META->add_attribute('override_method_modifiers' => (
309 reader => 'get_override_method_modifiers_map',
310 default => sub { {} }
314 # these are a little different because there
315 # can only be one per name, whereas the other
316 # method modifiers can have multiples.
319 sub add_override_method_modifier {
320 my ($self, $method_name, $method) = @_;
321 (!$self->has_method($method_name))
322 || Moose->throw_error("Cannot add an override of method '$method_name' " .
323 "because there is a local version of '$method_name'");
324 $self->get_override_method_modifiers_map->{$method_name} = $method;
327 sub has_override_method_modifier {
328 my ($self, $method_name) = @_;
330 # for now we assume that if it exists,..
331 # it has at least one modifier in it
332 (exists $self->get_override_method_modifiers_map->{$method_name}) ? 1 : 0;
335 sub get_override_method_modifier {
336 my ($self, $method_name) = @_;
337 $self->get_override_method_modifiers_map->{$method_name};
340 ## general list accessor ...
342 sub get_method_modifier_list {
343 my ($self, $modifier_type) = @_;
344 my $accessor = "get_${modifier_type}_method_modifiers_map";
345 keys %{$self->$accessor};
348 sub reset_package_cache_flag { (shift)->{'_package_cache_flag'} = undef }
349 sub update_package_cache_flag {
351 $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);
356 ## ------------------------------------------------------------------
359 $META->add_attribute('roles' => (
360 reader => 'get_roles',
361 default => sub { [] }
365 my ($self, $role) = @_;
366 (blessed($role) && $role->isa('Moose::Meta::Role'))
367 || Moose->throw_error("Roles must be instances of Moose::Meta::Role");
368 push @{$self->get_roles} => $role;
369 $self->reset_package_cache_flag;
372 sub calculate_all_roles {
378 $_->calculate_all_roles
379 } @{ $self->get_roles });
383 my ($self, $role_name) = @_;
385 || Moose->throw_error("You must supply a role name to look for");
386 # if we are it,.. then return true
387 return 1 if $role_name eq $self->name;
388 # otherwise.. check our children
389 foreach my $role (@{$self->get_roles}) {
390 return 1 if $role->does_role($role_name);
395 sub find_method_by_name { (shift)->get_method(@_) }
398 Carp::cluck("The alias_method method is deprecated. Use add_method instead.\n");
402 $self->add_method(@_);
405 ## ------------------------------------------------------------------
407 ## ------------------------------------------------------------------
410 my ($self, $other, @args) = @_;
413 || Moose->throw_error("You must pass in an blessed instance");
415 my $application_class;
416 if ($other->isa('Moose::Meta::Role')) {
417 $application_class = $self->application_to_role_class;
419 elsif ($other->isa('Moose::Meta::Class')) {
420 $application_class = $self->application_to_class_class;
423 $application_class = $self->application_to_instance_class;
426 Class::MOP::load_class($application_class);
427 return $application_class->new(@args)->apply($self, $other);
431 my ($class, @role_specs) = @_;
433 require Moose::Meta::Role::Composite;
435 my (@roles, %role_params);
436 while (@role_specs) {
437 my ($role_name, $params) = @{ splice @role_specs, 0, 1 };
438 my $requested_role = Class::MOP::class_of($role_name);
440 my $actual_role = $requested_role->_role_for_combination($params);
441 push @roles => $actual_role;
443 next unless defined $params;
444 $role_params{$actual_role->name} = $params;
447 my $c = Moose::Meta::Role::Composite->new(roles => \@roles);
448 return $c->apply_params(\%role_params);
451 sub _role_for_combination {
452 my ($self, $params) = @_;
457 my ( $role, $package_name, %options ) = @_;
459 $options{package} = $package_name;
461 (ref $options{attributes} eq 'HASH')
462 || confess "You must pass a HASH ref of attributes"
463 if exists $options{attributes};
465 (ref $options{methods} eq 'HASH')
466 || confess "You must pass a HASH ref of methods"
467 if exists $options{methods};
469 my (%initialize_options) = %options;
470 delete @initialize_options{qw(
478 my $meta = $role->initialize( $package_name => %initialize_options );
480 $meta->_instantiate_module( $options{version}, $options{authority} );
483 $meta->add_method('meta' => sub {
484 $role->initialize(ref($_[0]) || $_[0]);
487 if (exists $options{attributes}) {
488 foreach my $attribute_name (keys %{$options{attributes}}) {
489 my $attr = $options{attributes}->{$attribute_name};
490 $meta->add_attribute($attribute_name => $attr);
494 if (exists $options{methods}) {
495 foreach my $method_name (keys %{$options{methods}}) {
496 $meta->add_method($method_name, $options{methods}->{$method_name});
500 Class::MOP::weaken_metaclass($meta->name)
501 if $meta->is_anon_role;
506 # anonymous roles. most of it is copied straight out of Class::MOP::Class.
507 # an intrepid hacker might find great riches if he unifies this code with that
508 # code in Class::MOP::Module or Class::MOP::Package
511 # this should be sufficient, if you have a
512 # use case where it is not, write a test and
514 my $ANON_ROLE_SERIAL = 0;
517 # we need a sufficiently annoying prefix
518 # this should suffice for now, this is
519 # used in a couple of places below, so
520 # need to put it up here for now.
521 my $ANON_ROLE_PREFIX = 'Moose::Meta::Role::__ANON__::SERIAL::';
525 no warnings 'uninitialized';
526 $self->name =~ /^$ANON_ROLE_PREFIX/;
529 sub create_anon_role {
530 my ($role, %options) = @_;
531 my $package_name = $ANON_ROLE_PREFIX . ++$ANON_ROLE_SERIAL;
532 return $role->create($package_name, %options);
536 # this will only get called for
537 # anon-roles, all other calls
538 # are assumed to occur during
539 # global destruction and so don't
540 # really need to be handled explicitly
544 return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
546 no warnings 'uninitialized';
547 return unless $self->name =~ /^$ANON_ROLE_PREFIX/;
549 # XXX: is this necessary for us? I don't understand what it's doing
552 # Moose does a weird thing where it replaces the metaclass for
553 # class when fixing metaclass incompatibility. In that case,
554 # we don't want to clean out the namespace now. We can detect
555 # that because Moose will explicitly update the singleton
556 # cache in Class::MOP.
557 #my $current_meta = Class::MOP::get_metaclass_by_name($self->name);
558 #return if $current_meta ne $self;
560 my ($serial_id) = ($self->name =~ /^$ANON_ROLE_PREFIX(\d+)/);
562 foreach my $key (keys %{$ANON_ROLE_PREFIX . $serial_id}) {
563 delete ${$ANON_ROLE_PREFIX . $serial_id}{$key};
565 delete ${'main::' . $ANON_ROLE_PREFIX}{$serial_id . '::'};
569 #####################################################################
571 ## This is Moose::Meta::Role as defined by Moose (plus the use of
572 ## MooseX::AttributeHelpers module). It is here as a reference to
573 ## make it easier to see what is happening above with all the meta
575 #####################################################################
578 # metaclass => 'Array',
579 # reader => 'get_roles',
580 # isa => 'ArrayRef[Moose::Meta::Role]',
581 # default => sub { [] },
583 # 'push' => 'add_role',
587 # has 'excluded_roles_map' => (
588 # metaclass => 'Hash',
589 # reader => 'get_excluded_roles_map',
590 # isa => 'HashRef[Str]',
592 # # Not exactly set, cause it sets multiple
593 # 'set' => 'add_excluded_roles',
594 # 'keys' => 'get_excluded_roles_list',
595 # 'exists' => 'excludes_role',
599 # has 'required_methods' => (
600 # metaclass => 'Hash',
601 # reader => 'get_required_methods_map',
602 # isa => 'HashRef[Moose::Meta::Role::Method::Required]',
604 # # not exactly set, or delete since it works for multiple
605 # 'set' => 'add_required_methods',
606 # 'delete' => 'remove_required_methods',
607 # 'keys' => 'get_required_method_list',
608 # 'exists' => 'requires_method',
612 # # the before, around and after modifiers are
613 # # HASH keyed by method-name, with ARRAY of
614 # # CODE refs to apply in that order
616 # has 'before_method_modifiers' => (
617 # metaclass => 'Hash',
618 # reader => 'get_before_method_modifiers_map',
619 # isa => 'HashRef[ArrayRef[CodeRef]]',
621 # 'keys' => 'get_before_method_modifiers',
622 # 'exists' => 'has_before_method_modifiers',
623 # # This actually makes sure there is an
624 # # ARRAY at the given key, and pushed onto
625 # # it. It also checks for duplicates as well
626 # # 'add' => 'add_before_method_modifier'
630 # has 'after_method_modifiers' => (
631 # metaclass => 'Hash',
632 # reader =>'get_after_method_modifiers_map',
633 # isa => 'HashRef[ArrayRef[CodeRef]]',
635 # 'keys' => 'get_after_method_modifiers',
636 # 'exists' => 'has_after_method_modifiers',
637 # # This actually makes sure there is an
638 # # ARRAY at the given key, and pushed onto
639 # # it. It also checks for duplicates as well
640 # # 'add' => 'add_after_method_modifier'
644 # has 'around_method_modifiers' => (
645 # metaclass => 'Hash',
646 # reader =>'get_around_method_modifiers_map',
647 # isa => 'HashRef[ArrayRef[CodeRef]]',
649 # 'keys' => 'get_around_method_modifiers',
650 # 'exists' => 'has_around_method_modifiers',
651 # # This actually makes sure there is an
652 # # ARRAY at the given key, and pushed onto
653 # # it. It also checks for duplicates as well
654 # # 'add' => 'add_around_method_modifier'
658 # # override is similar to the other modifiers
659 # # except that it is not an ARRAY of code refs
660 # # but instead just a single name->code mapping
662 # has 'override_method_modifiers' => (
663 # metaclass => 'Hash',
664 # reader =>'get_override_method_modifiers_map',
665 # isa => 'HashRef[CodeRef]',
667 # 'keys' => 'get_override_method_modifier',
668 # 'exists' => 'has_override_method_modifier',
669 # 'add' => 'add_override_method_modifier', # checks for local method ..
673 #####################################################################
684 Moose::Meta::Role - The Moose Role metaclass
688 This class is a subclass of L<Class::MOP::Module> that provides
689 additional Moose-specific functionality.
691 It's API looks a lot like L<Moose::Meta::Class>, but internally it
692 implements many things differently. This may change in the future.
696 C<Moose::Meta::Role> is a subclass of L<Class::MOP::Module>.
704 =item B<< Moose::Meta::Role->initialize($role_name) >>
706 This method creates a new role object with the provided name.
708 =item B<< Moose::Meta::Role->combine( [ $role => { ... } ], [ $role ], ... ) >>
710 This method accepts a list of array references. Each array reference
711 should contain a role name as its first element. The second element is
712 an optional hash reference. The hash reference can contain C<-excludes>
713 and C<-alias> keys to control how methods are composed from the role.
715 The return value is a new L<Moose::Meta::Role::Composite> that
716 represents the combined roles.
718 =item B<< Moose::Meta::Role->create($name, %options) >>
720 This method is identical to the L<Moose::Meta::Class> C<create>
723 =item B<< Moose::Meta::Role->create_anon_role >>
725 This method is identical to the L<Moose::Meta::Class>
726 C<create_anon_class> method.
728 =item B<< $metarole->is_anon_role >>
730 Returns true if the role is an anonymous role.
734 =head2 Role application
738 =item B<< $metarole->apply( $thing, @options ) >>
740 This method applies a role to the given C<$thing>. That can be another
741 L<Moose::Meta::Role>, object, a L<Moose::Meta::Class> object, or a
742 (non-meta) object instance.
744 The options are passed directly to the constructor for the appropriate
745 L<Moose::Meta::Role::Application> subclass.
747 Note that this will apply the role even if the C<$thing> in question already
748 C<does> this role. L<Moose::Util/does_role> is a convenient wrapper for
749 finding out if role application is necessary.
753 =head2 Roles and other roles
757 =item B<< $metarole->get_roles >>
759 This returns an array reference of roles which this role does. This
760 list may include duplicates.
762 =item B<< $metarole->calculate_all_roles >>
764 This returns a I<unique> list of all roles that this role does, and
765 all the roles that its roles do.
767 =item B<< $metarole->does_role($role_name) >>
769 Given a role I<name>, returns true if this role does the given
772 =item B<< $metarole->add_role($role) >>
774 Given a L<Moose::Meta::Role> object, this adds the role to the list of
775 roles that the role does.
777 =item B<< $metarole->get_excluded_roles_list >>
779 Returns a list of role names which this role excludes.
781 =item B<< $metarole->excludes_role($role_name) >>
783 Given a role I<name>, returns true if this role excludes the named
786 =item B<< $metarole->add_excluded_roles(@role_names) >>
788 Given one or more role names, adds those roles to the list of excluded
795 The methods for dealing with a role's methods are all identical in API
796 and behavior to the same methods in L<Class::MOP::Class>.
800 =item B<< $metarole->method_metaclass >>
802 Returns the method metaclass name for the role. This defaults to
803 L<Moose::Meta::Role::Method>.
805 =item B<< $metarole->get_method($name) >>
807 =item B<< $metarole->has_method($name) >>
809 =item B<< $metarole->add_method( $name, $body ) >>
811 =item B<< $metarole->get_method_list >>
813 =item B<< $metarole->find_method_by_name($name) >>
815 These methods are all identical to the methods of the same name in
816 L<Class::MOP::Package>
822 As with methods, the methods for dealing with a role's attribute are
823 all identical in API and behavior to the same methods in
824 L<Class::MOP::Class>.
826 However, attributes stored in this class are I<not> stored as
827 objects. Rather, the attribute definition is stored as a hash
828 reference. When a role is composed into a class, this hash reference
829 is passed directly to the metaclass's C<add_attribute> method.
831 This is quite likely to change in the future.
835 =item B<< $metarole->get_attribute($attribute_name) >>
837 =item B<< $metarole->has_attribute($attribute_name) >>
839 =item B<< $metarole->get_attribute_list >>
841 =item B<< $metarole->add_attribute($name, %options) >>
843 =item B<< $metarole->remove_attribute($attribute_name) >>
847 =head2 Required methods
851 =item B<< $metarole->get_required_method_list >>
853 Returns the list of methods required by the role.
855 =item B<< $metarole->requires_method($name) >>
857 Returns true if the role requires the named method.
859 =item B<< $metarole->add_required_methods(@names) >>
861 Adds the named methods to the role's list of required methods.
863 =item B<< $metarole->remove_required_methods(@names) >>
865 Removes the named methods from the role's list of required methods.
867 =item B<< $metarole->add_conflicting_method(%params) >>
869 Instantiate the parameters as a L<Moose::Meta::Role::Method::Conflicting>
870 object, then add it to the required method list.
874 =head2 Method modifiers
876 These methods act like their counterparts in L<Class::Mop::Class> and
877 L<Moose::Meta::Class>.
879 However, method modifiers are simply stored internally, and are not
880 applied until the role itself is applied to a class.
884 =item B<< $metarole->add_after_method_modifier($method_name, $method) >>
886 =item B<< $metarole->add_around_method_modifier($method_name, $method) >>
888 =item B<< $metarole->add_before_method_modifier($method_name, $method) >>
890 =item B<< $metarole->add_override_method_modifier($method_name, $method) >>
892 These methods all add an appropriate modifier to the internal list of
895 =item B<< $metarole->has_after_method_modifiers >>
897 =item B<< $metarole->has_around_method_modifiers >>
899 =item B<< $metarole->has_before_method_modifiers >>
901 =item B<< $metarole->has_override_method_modifier >>
903 Return true if the role has any modifiers of the given type.
905 =item B<< $metarole->get_after_method_modifiers($method_name) >>
907 =item B<< $metarole->get_around_method_modifiers($method_name) >>
909 =item B<< $metarole->get_before_method_modifiers($method_name) >>
911 Given a method name, returns a list of the appropriate modifiers for
914 =item B<< $metarole->get_override_method_modifier($method_name) >>
916 Given a method name, returns the override method modifier for that
917 method, if it has one.
925 =item B<< Moose::Meta::Role->meta >>
927 This will return a L<Class::MOP::Class> instance for this class.
933 All complex software has bugs lurking in it, and this module is no
934 exception. If you find a bug please either email me, or add the bug
939 Stevan Little E<lt>stevan@iinteractive.comE<gt>
941 =head1 COPYRIGHT AND LICENSE
943 Copyright 2006-2009 by Infinity Interactive, Inc.
945 L<http://www.iinteractive.com>
947 This library is free software; you can redistribute it and/or modify
948 it under the same terms as Perl itself.