2 package Moose::Meta::Attribute;
8 use Class::Load qw(is_class_loaded load_class);
9 use Scalar::Util 'blessed', 'weaken';
10 use List::MoreUtils 'any';
14 use Moose::Deprecated;
15 use Moose::Meta::Method::Accessor;
16 use Moose::Meta::Method::Delegation;
18 use Moose::Util::TypeConstraints ();
19 use Class::MOP::MiniTrait;
21 use base 'Class::MOP::Attribute', 'Moose::Meta::Mixin::AttributeCore';
23 Class::MOP::MiniTrait::apply(__PACKAGE__, 'Moose::Meta::Object::Trait');
25 __PACKAGE__->meta->add_attribute('traits' => (
26 reader => 'applied_traits',
27 predicate => 'has_applied_traits',
28 Class::MOP::_definition_context(),
31 # we need to have a ->does method in here to
32 # more easily support traits, and the introspection
33 # of those traits. We extend the does check to look
34 # for metatrait aliases.
36 my ($self, $role_name) = @_;
38 Moose::Util::resolve_metatrait_alias(Attribute => $role_name)
40 return 0 if !defined($name); # failed to load class
41 return $self->Moose::Object::does($name);
46 require Moose::Meta::Class;
47 ( ref $self && $self->associated_class ) || "Moose::Meta::Class";
52 my $inv = $self->_error_thrower;
53 unshift @_, "message" if @_ % 2 == 1;
54 unshift @_, attr => $self if ref $self;
56 my $handler = $inv->can("throw_error"); # to avoid incrementing depth by 1
60 sub _inline_throw_error {
61 my ( $self, $msg, $args ) = @_;
63 my $inv = $self->_error_thrower;
65 $inv = 'Moose::Meta::Class' unless $inv->can('_inline_throw_error');
68 my $class = $self->associated_class;
70 my $class_name = B::perlstring($class->name);
71 my $attr_name = B::perlstring($self->name);
72 $args = 'attr => Class::MOP::class_of(' . $class_name . ')'
73 . '->find_attribute_by_name(' . $attr_name . '), '
74 . (defined $args ? $args : '');
77 return $inv->_inline_throw_error($msg, $args)
81 my ($class, $name, %options) = @_;
82 $class->_process_options($name, \%options) unless $options{__hack_no_process_options}; # used from clone()... YECHKKK FIXME ICKY YUCK GROSS
84 delete $options{__hack_no_process_options};
89 map { $_->init_arg() }
90 $class->meta()->get_all_attributes()
93 my @bad = sort grep { ! $attrs{$_} } keys %options;
97 Carp::cluck "Found unknown argument(s) passed to '$name' attribute constructor in '$class': @bad";
100 return $class->SUPER::new($name, %options);
103 sub interpolate_class_and_new {
104 my ($class, $name, %args) = @_;
106 my ( $new_class, @traits ) = $class->interpolate_class(\%args);
108 $new_class->new($name, %args, ( scalar(@traits) ? ( traits => \@traits ) : () ) );
111 sub interpolate_class {
112 my ($class, $options) = @_;
114 $class = ref($class) || $class;
116 if ( my $metaclass_name = delete $options->{metaclass} ) {
117 my $new_class = Moose::Util::resolve_metaclass_alias( Attribute => $metaclass_name );
119 if ( $class ne $new_class ) {
120 if ( $new_class->can("interpolate_class") ) {
121 return $new_class->interpolate_class($options);
130 if (my $traits = $options->{traits}) {
132 my $has_foreign_options = 0;
134 while ($i < @$traits) {
135 my $trait = $traits->[$i++];
136 next if ref($trait); # options to a trait we discarded
138 $trait = Moose::Util::resolve_metatrait_alias(Attribute => $trait)
141 next if $class->does($trait);
143 push @traits, $trait;
146 if ($traits->[$i] && ref($traits->[$i])) {
147 $has_foreign_options = 1
148 if any { $_ ne '-alias' && $_ ne '-excludes' } keys %{ $traits->[$i] };
150 push @traits, $traits->[$i++];
156 superclasses => [ $class ],
157 roles => [ @traits ],
160 if ($has_foreign_options) {
161 $options{weaken} = 0;
167 my $anon_class = Moose::Meta::Class->create_anon_class(%options);
168 $class = $anon_class->name;
172 return ( wantarray ? ( $class, @traits ) : $class );
177 # method-generating options shouldn't be overridden
178 sub illegal_options_for_inheritance {
179 qw(reader writer accessor clearer predicate)
183 # This method *must* be able to handle
184 # Class::MOP::Attribute instances as
185 # well. Yes, I know that is wrong, but
186 # apparently we didn't realize it was
187 # doing that and now we have some code
188 # which is dependent on it. The real
189 # solution of course is to push this
190 # feature back up into Class::MOP::Attribute
191 # but I not right now, I am too lazy.
192 # However if you are reading this and
193 # looking for something to do,.. please
196 sub clone_and_inherit_options {
197 my ($self, %options) = @_;
200 # we may want to extends a Class::MOP::Attribute
201 # in which case we need to be able to use the
202 # core set of legal options that have always
203 # been here. But we allows Moose::Meta::Attribute
204 # instances to changes them.
206 my @illegal_options = $self->can('illegal_options_for_inheritance')
207 ? $self->illegal_options_for_inheritance
210 my @found_illegal_options = grep { exists $options{$_} && exists $self->{$_} ? $_ : undef } @illegal_options;
211 (scalar @found_illegal_options == 0)
212 || $self->throw_error("Illegal inherited options => (" . (join ', ' => @found_illegal_options) . ")", data => \%options);
216 if (blessed($options{isa}) && $options{isa}->isa('Moose::Meta::TypeConstraint')) {
217 $type_constraint = $options{isa};
220 $type_constraint = Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($options{isa});
221 (defined $type_constraint)
222 || $self->throw_error("Could not find the type constraint '" . $options{isa} . "'", data => $options{isa});
225 $options{type_constraint} = $type_constraint;
228 if ($options{does}) {
230 if (blessed($options{does}) && $options{does}->isa('Moose::Meta::TypeConstraint')) {
231 $type_constraint = $options{does};
234 $type_constraint = Moose::Util::TypeConstraints::find_or_create_does_type_constraint($options{does});
235 (defined $type_constraint)
236 || $self->throw_error("Could not find the type constraint '" . $options{does} . "'", data => $options{does});
239 $options{type_constraint} = $type_constraint;
243 # this doesn't apply to Class::MOP::Attributes,
244 # so we can ignore it for them.
246 if ($self->can('interpolate_class')) {
247 ( $options{metaclass}, my @traits ) = $self->interpolate_class(\%options);
250 my @all_traits = grep { $seen{$_}++ } @{ $self->applied_traits || [] }, @traits;
251 $options{traits} = \@all_traits if @all_traits;
254 # This method can be called on a CMOP::Attribute object, so we need to
255 # make sure we can call this method.
256 $self->_process_lazy_build_option( $self->name, \%options )
257 if $self->can('_process_lazy_build_option');
259 $self->clone(%options);
263 my ( $self, %params ) = @_;
265 my $class = delete $params{metaclass} || ref $self;
267 my ( @init, @non_init );
269 foreach my $attr ( grep { $_->has_value($self) } Class::MOP::class_of($self)->get_all_attributes ) {
270 push @{ $attr->has_init_arg ? \@init : \@non_init }, $attr;
273 my %new_params = ( ( map { $_->init_arg => $_->get_value($self) } @init ), %params );
275 my $name = delete $new_params{name};
277 my $clone = $class->new($name, %new_params, __hack_no_process_options => 1 );
279 foreach my $attr ( @non_init ) {
280 $attr->set_value($clone, $attr->get_value($self));
286 sub _process_options {
287 my ( $class, $name, $options ) = @_;
289 $class->_process_is_option( $name, $options );
290 $class->_process_isa_option( $name, $options );
291 $class->_process_does_option( $name, $options );
292 $class->_process_coerce_option( $name, $options );
293 $class->_process_trigger_option( $name, $options );
294 $class->_process_auto_deref_option( $name, $options );
295 $class->_process_lazy_build_option( $name, $options );
296 $class->_process_lazy_option( $name, $options );
297 $class->_process_required_option( $name, $options );
300 sub _process_is_option {
301 my ( $class, $name, $options ) = @_;
303 return unless $options->{is};
305 ### -------------------------
306 ## is => ro, writer => _foo # turns into (reader => foo, writer => _foo) as before
307 ## is => rw, writer => _foo # turns into (reader => foo, writer => _foo)
308 ## is => rw, accessor => _foo # turns into (accessor => _foo)
309 ## is => ro, accessor => _foo # error, accesor is rw
310 ### -------------------------
312 if ( $options->{is} eq 'ro' ) {
314 "Cannot define an accessor name on a read-only attribute, accessors are read/write",
316 if exists $options->{accessor};
317 $options->{reader} ||= $name;
319 elsif ( $options->{is} eq 'rw' ) {
320 if ( $options->{writer} ) {
321 $options->{reader} ||= $name;
324 $options->{accessor} ||= $name;
327 elsif ( $options->{is} eq 'bare' ) {
329 # do nothing, but don't complain (later) about missing methods
332 $class->throw_error( "I do not understand this option (is => "
334 . ") on attribute ($name)", data => $options->{is} );
338 sub _process_isa_option {
339 my ( $class, $name, $options ) = @_;
341 return unless exists $options->{isa};
343 if ( exists $options->{does} ) {
344 if ( try { $options->{isa}->can('does') } ) {
345 ( $options->{isa}->does( $options->{does} ) )
346 || $class->throw_error(
347 "Cannot have an isa option and a does option if the isa does not do the does on attribute ($name)",
352 "Cannot have an isa option which cannot ->does() on attribute ($name)",
357 # allow for anon-subtypes here ...
358 if ( blessed( $options->{isa} )
359 && $options->{isa}->isa('Moose::Meta::TypeConstraint') ) {
360 $options->{type_constraint} = $options->{isa};
363 $options->{type_constraint}
364 = Moose::Util::TypeConstraints::find_or_create_isa_type_constraint(
369 sub _process_does_option {
370 my ( $class, $name, $options ) = @_;
372 return unless exists $options->{does} && ! exists $options->{isa};
374 # allow for anon-subtypes here ...
375 if ( blessed( $options->{does} )
376 && $options->{does}->isa('Moose::Meta::TypeConstraint') ) {
377 $options->{type_constraint} = $options->{does};
380 $options->{type_constraint}
381 = Moose::Util::TypeConstraints::find_or_create_does_type_constraint(
386 sub _process_coerce_option {
387 my ( $class, $name, $options ) = @_;
389 return unless $options->{coerce};
391 ( exists $options->{type_constraint} )
392 || $class->throw_error(
393 "You cannot have coercion without specifying a type constraint on attribute ($name)",
397 "You cannot have a weak reference to a coerced value on attribute ($name)",
399 if $options->{weak_ref};
401 unless ( $options->{type_constraint}->has_coercion ) {
402 my $type = $options->{type_constraint}->name;
404 Moose::Deprecated::deprecated(
405 feature => 'coerce without coercion',
407 "You cannot coerce an attribute ($name) unless its type ($type) has a coercion"
412 sub _process_trigger_option {
413 my ( $class, $name, $options ) = @_;
415 return unless exists $options->{trigger};
417 ( 'CODE' eq ref $options->{trigger} )
418 || $class->throw_error("Trigger must be a CODE ref on attribute ($name)", data => $options->{trigger});
421 sub _process_auto_deref_option {
422 my ( $class, $name, $options ) = @_;
424 return unless $options->{auto_deref};
426 ( exists $options->{type_constraint} )
427 || $class->throw_error(
428 "You cannot auto-dereference without specifying a type constraint on attribute ($name)",
431 ( $options->{type_constraint}->is_a_type_of('ArrayRef')
432 || $options->{type_constraint}->is_a_type_of('HashRef') )
433 || $class->throw_error(
434 "You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute ($name)",
438 sub _process_lazy_build_option {
439 my ( $class, $name, $options ) = @_;
441 return unless $options->{lazy_build};
444 "You can not use lazy_build and default for the same attribute ($name)",
446 if exists $options->{default};
448 $options->{lazy} = 1;
449 $options->{builder} ||= "_build_${name}";
451 if ( $name =~ /^_/ ) {
452 $options->{clearer} ||= "_clear${name}";
453 $options->{predicate} ||= "_has${name}";
456 $options->{clearer} ||= "clear_${name}";
457 $options->{predicate} ||= "has_${name}";
461 sub _process_lazy_option {
462 my ( $class, $name, $options ) = @_;
464 return unless $options->{lazy};
466 ( exists $options->{default} || defined $options->{builder} )
467 || $class->throw_error(
468 "You cannot have a lazy attribute ($name) without specifying a default value for it",
472 sub _process_required_option {
473 my ( $class, $name, $options ) = @_;
478 ( !exists $options->{init_arg} || defined $options->{init_arg} )
479 || exists $options->{default}
480 || defined $options->{builder}
484 "You cannot have a required attribute ($name) without a default, builder, or an init_arg",
489 sub initialize_instance_slot {
490 my ($self, $meta_instance, $instance, $params) = @_;
491 my $init_arg = $self->init_arg();
492 # try to fetch the init arg from the %params ...
496 if ( defined($init_arg) and exists $params->{$init_arg}) {
497 $val = $params->{$init_arg};
501 # skip it if it's lazy
502 return if $self->is_lazy;
503 # and die if it's required and doesn't have a default value
504 $self->throw_error("Attribute (" . $self->name . ") is required", object => $instance, data => $params)
505 if $self->is_required && !$self->has_default && !$self->has_builder;
507 # if nothing was in the %params, we can use the
508 # attribute's default value (if it has one)
509 if ($self->has_default) {
510 $val = $self->default($instance);
513 elsif ($self->has_builder) {
514 $val = $self->_call_builder($instance);
519 return unless $value_is_set;
521 $val = $self->_coerce_and_verify( $val, $instance );
523 $self->set_initial_value($instance, $val);
525 if ( ref $val && $self->is_weak_ref ) {
526 $self->_weaken_value($instance);
531 my ( $self, $instance ) = @_;
533 my $builder = $self->builder();
535 return $instance->$builder()
536 if $instance->can( $self->builder );
538 $self->throw_error( blessed($instance)
539 . " does not support builder method '"
541 . "' for attribute '"
550 sub _make_initializer_writer_callback {
552 my ($meta_instance, $instance, $slot_name) = @_;
553 my $old_callback = $self->SUPER::_make_initializer_writer_callback(@_);
555 $old_callback->($self->_coerce_and_verify($_[0], $instance));
560 my ($self, $instance, @args) = @_;
561 my $value = $args[0];
563 my $attr_name = quotemeta($self->name);
565 if ($self->is_required and not @args) {
566 $self->throw_error("Attribute ($attr_name) is required", object => $instance);
569 $value = $self->_coerce_and_verify( $value, $instance );
572 if ( $self->has_trigger && $self->has_value($instance) ) {
573 @old = $self->get_value($instance, 'for trigger');
576 $self->SUPER::set_value($instance, $value);
578 if ( ref $value && $self->is_weak_ref ) {
579 $self->_weaken_value($instance);
582 if ($self->has_trigger) {
583 $self->trigger->($instance, $value, @old);
587 sub _inline_set_value {
589 my ($instance, $value, $tc, $coercion, $message, $for_constructor) = @_;
593 $tc ||= '$type_constraint';
594 $coercion ||= '$type_coercion';
595 $message ||= '$type_message';
598 if ($self->_writer_value_needs_copy) {
599 push @code, $self->_inline_copy_value($value, $copy);
603 # constructors already handle required checks
604 push @code, $self->_inline_check_required
605 unless $for_constructor;
607 push @code, $self->_inline_tc_code($value, $tc, $coercion, $message);
609 # constructors do triggers all at once at the end
610 push @code, $self->_inline_get_old_value_for_trigger($instance, $old)
611 unless $for_constructor;
614 $self->SUPER::_inline_set_value($instance, $value),
615 $self->_inline_weaken_value($instance, $value),
618 # constructors do triggers all at once at the end
619 push @code, $self->_inline_trigger($instance, $value, $old)
620 unless $for_constructor;
625 sub _writer_value_needs_copy {
627 return $self->should_coerce;
630 sub _inline_copy_value {
632 my ($value, $copy) = @_;
634 return 'my ' . $copy . ' = ' . $value . ';'
637 sub _inline_check_required {
640 return unless $self->is_required;
642 my $attr_name = quotemeta($self->name);
646 $self->_inline_throw_error(
647 '"Attribute (' . $attr_name . ') is required, so cannot '
648 . 'be set to undef"' # defined $_[1] is not good enough
654 sub _inline_tc_code {
656 my ($value, $tc, $coercion, $message, $is_lazy) = @_;
658 $self->_inline_check_coercion(
659 $value, $tc, $coercion, $is_lazy,
661 $self->_inline_check_constraint(
662 $value, $tc, $message, $is_lazy,
667 sub _inline_check_coercion {
669 my ($value, $tc, $coercion) = @_;
671 return unless $self->should_coerce && $self->type_constraint->has_coercion;
673 if ( $self->type_constraint->can_be_inlined ) {
675 'if (! (' . $self->type_constraint->_inline_check($value) . ')) {',
676 $value . ' = ' . $coercion . '->(' . $value . ');',
682 'if (!' . $tc . '->(' . $value . ')) {',
683 $value . ' = ' . $coercion . '->(' . $value . ');',
689 sub _inline_check_constraint {
691 my ($value, $tc, $message) = @_;
693 return unless $self->has_type_constraint;
695 my $attr_name = quotemeta($self->name);
697 if ( $self->type_constraint->can_be_inlined ) {
699 'if (! (' . $self->type_constraint->_inline_check($value) . ')) {',
700 $self->_inline_throw_error(
701 '"Attribute (' . $attr_name . ') does not pass the type '
702 . 'constraint because: " . '
703 . 'do { local $_ = ' . $value . '; '
704 . $message . '->(' . $value . ')'
713 'if (!' . $tc . '->(' . $value . ')) {',
714 $self->_inline_throw_error(
715 '"Attribute (' . $attr_name . ') does not pass the type '
716 . 'constraint because: " . '
717 . 'do { local $_ = ' . $value . '; '
718 . $message . '->(' . $value . ')'
727 sub _inline_get_old_value_for_trigger {
729 my ($instance, $old) = @_;
731 return unless $self->has_trigger;
734 'my ' . $old . ' = ' . $self->_inline_instance_has($instance),
735 '? ' . $self->_inline_instance_get($instance),
740 sub _inline_weaken_value {
742 my ($instance, $value) = @_;
744 return unless $self->is_weak_ref;
746 my $mi = $self->associated_class->get_meta_instance;
748 $mi->inline_weaken_slot_value($instance, $self->name, $value),
749 'if ref ' . $value . ';',
753 sub _inline_trigger {
755 my ($instance, $value, $old) = @_;
757 return unless $self->has_trigger;
759 return '$trigger->(' . $instance . ', ' . $value . ', ' . $old . ');';
762 sub _eval_environment {
767 $env->{'$trigger'} = \($self->trigger)
768 if $self->has_trigger;
769 $env->{'$attr_default'} = \($self->default)
770 if $self->has_default;
772 if ($self->has_type_constraint) {
773 my $tc_obj = $self->type_constraint;
775 $env->{'$type_constraint'} = \(
776 $tc_obj->_compiled_type_constraint
777 ) unless $tc_obj->can_be_inlined;
778 # these two could probably get inlined versions too
779 $env->{'$type_coercion'} = \(
780 $tc_obj->coercion->_compiled_type_coercion
781 ) if $tc_obj->has_coercion;
782 $env->{'$type_message'} = \(
783 $tc_obj->has_message ? $tc_obj->message : $tc_obj->_default_message
786 $env = { %$env, %{ $tc_obj->inline_environment } };
790 $env->{'$attr'} = \$self
791 if $self->has_initializer && $self->is_lazy;
792 # pretty sure this is only going to be closed over if you use a custom
793 # error class at this point, but we should still get rid of this
795 $env->{'$meta'} = \($self->associated_class);
801 my ( $self, $instance ) = @_;
803 my $meta_instance = Class::MOP::Class->initialize( blessed($instance) )
806 $meta_instance->weaken_slot_value( $instance, $self->name );
810 my ($self, $instance, $for_trigger) = @_;
812 if ($self->is_lazy) {
813 unless ($self->has_value($instance)) {
815 if ($self->has_default) {
816 $value = $self->default($instance);
817 } elsif ( $self->has_builder ) {
818 $value = $self->_call_builder($instance);
821 $value = $self->_coerce_and_verify( $value, $instance );
823 $self->set_initial_value($instance, $value);
827 if ( $self->should_auto_deref && ! $for_trigger ) {
829 my $type_constraint = $self->type_constraint;
831 if ($type_constraint->is_a_type_of('ArrayRef')) {
832 my $rv = $self->SUPER::get_value($instance);
833 return unless defined $rv;
834 return wantarray ? @{ $rv } : $rv;
836 elsif ($type_constraint->is_a_type_of('HashRef')) {
837 my $rv = $self->SUPER::get_value($instance);
838 return unless defined $rv;
839 return wantarray ? %{ $rv } : $rv;
842 $self->throw_error("Can not auto de-reference the type constraint '" . $type_constraint->name . "'", object => $instance, type_constraint => $type_constraint);
848 return $self->SUPER::get_value($instance);
852 sub _inline_get_value {
854 my ($instance, $tc, $coercion, $message) = @_;
856 my $slot_access = $self->_inline_instance_get($instance);
857 $tc ||= '$type_constraint';
858 $coercion ||= '$type_coercion';
859 $message ||= '$type_message';
862 $self->_inline_check_lazy($instance, $tc, $coercion, $message),
863 $self->_inline_return_auto_deref($slot_access),
867 sub _inline_check_lazy {
869 my ($instance, $tc, $coercion, $message) = @_;
871 return unless $self->is_lazy;
873 my $slot_exists = $self->_inline_instance_has($instance);
876 'if (!' . $slot_exists . ') {',
877 $self->_inline_init_from_default($instance, '$default', $tc, $coercion, $message, 'lazy'),
882 sub _inline_init_from_default {
884 my ($instance, $default, $tc, $coercion, $message, $for_lazy) = @_;
886 if (!($self->has_default || $self->has_builder)) {
888 'You cannot have a lazy attribute '
889 . '(' . $self->name . ') '
890 . 'without specifying a default value for it',
896 $self->_inline_generate_default($instance, $default),
897 # intentionally not using _inline_tc_code, since that can be overridden
898 # to do things like possibly only do member tc checks, which isn't
899 # appropriate for checking the result of a default
900 $self->has_type_constraint
901 ? ($self->_inline_check_coercion($default, $tc, $coercion, $for_lazy),
902 $self->_inline_check_constraint($default, $tc, $message, $for_lazy))
904 $self->_inline_init_slot($instance, $default),
908 sub _inline_generate_default {
910 my ($instance, $default) = @_;
912 if ($self->has_default) {
913 my $source = 'my ' . $default . ' = $attr_default';
914 $source .= '->(' . $instance . ')'
915 if $self->is_default_a_coderef;
916 return $source . ';';
918 elsif ($self->has_builder) {
919 my $builder = B::perlstring($self->builder);
920 my $builder_str = quotemeta($self->builder);
921 my $attr_name_str = quotemeta($self->name);
923 'my ' . $default . ';',
924 'if (my $builder = ' . $instance . '->can(' . $builder . ')) {',
925 $default . ' = ' . $instance . '->$builder;',
928 'my $class = ref(' . $instance . ') || ' . $instance . ';',
929 $self->_inline_throw_error(
930 '"$class does not support builder method '
931 . '\'' . $builder_str . '\' for attribute '
932 . '\'' . $attr_name_str . '\'"'
939 "Can't generate a default for " . $self->name
940 . " since no default or builder was specified"
945 sub _inline_init_slot {
947 my ($inv, $value) = @_;
949 if ($self->has_initializer) {
950 return '$attr->set_initial_value(' . $inv . ', ' . $value . ');';
953 return $self->_inline_instance_set($inv, $value) . ';';
957 sub _inline_return_auto_deref {
960 return 'return ' . $self->_auto_deref(@_) . ';';
965 my ($ref_value) = @_;
967 return $ref_value unless $self->should_auto_deref;
969 my $type_constraint = $self->type_constraint;
972 if ($type_constraint->is_a_type_of('ArrayRef')) {
975 elsif ($type_constraint->is_a_type_of('HashRef')) {
980 'Can not auto de-reference the type constraint \''
981 . $type_constraint->name
983 type_constraint => $type_constraint,
988 . '? ' . $sigil . '{ (' . $ref_value . ') || return } '
989 . ': (' . $ref_value . ')';
992 ## installing accessors
994 sub accessor_metaclass { 'Moose::Meta::Method::Accessor' }
996 sub install_accessors {
998 $self->SUPER::install_accessors(@_);
999 $self->install_delegation if $self->has_handles;
1003 sub _check_associated_methods {
1006 @{ $self->associated_methods }
1007 || ($self->_is_metadata || '') eq 'bare'
1010 'Attribute (' . $self->name . ') of class '
1011 . $self->associated_class->name
1012 . ' has no associated methods'
1013 . ' (did you mean to provide an "is" argument?)'
1019 sub _process_accessors {
1021 my ($type, $accessor, $generate_as_inline_methods) = @_;
1023 $accessor = ( keys %$accessor )[0] if ( ref($accessor) || '' ) eq 'HASH';
1024 my $method = $self->associated_class->get_method($accessor);
1027 && $method->isa('Class::MOP::Method::Accessor')
1028 && $method->associated_attribute->name ne $self->name ) {
1030 my $other_attr_name = $method->associated_attribute->name;
1031 my $name = $self->name;
1034 "You are overwriting an accessor ($accessor) for the $other_attr_name attribute"
1035 . " with a new accessor method for the $name attribute" );
1040 && !$method->is_stub
1041 && !$method->isa('Class::MOP::Method::Accessor')
1042 && ( !$self->definition_context
1043 || $method->package_name eq $self->definition_context->{package} )
1047 "You are overwriting a locally defined method ($accessor) with "
1051 if ( !$self->associated_class->has_method($accessor)
1052 && $self->associated_class->has_package_symbol( '&' . $accessor ) ) {
1055 "You are overwriting a locally defined function ($accessor) with "
1059 $self->SUPER::_process_accessors(@_);
1062 sub remove_accessors {
1064 $self->SUPER::remove_accessors(@_);
1065 $self->remove_delegation if $self->has_handles;
1069 sub install_delegation {
1073 # Here we canonicalize the 'handles' option
1074 # this will sort out any details and always
1075 # return an hash of methods which we want
1076 # to delagate to, see that method for details
1077 my %handles = $self->_canonicalize_handles;
1080 # install the delegation ...
1081 my $associated_class = $self->associated_class;
1082 foreach my $handle (sort keys %handles) {
1083 my $method_to_call = $handles{$handle};
1084 my $class_name = $associated_class->name;
1085 my $name = "${class_name}::${handle}";
1087 if ( my $method = $associated_class->get_method($handle) ) {
1089 "You cannot overwrite a locally defined method ($handle) with a delegation",
1090 method_name => $handle
1091 ) unless $method->is_stub;
1095 # handles is not allowed to delegate
1096 # any of these methods, as they will
1097 # override the ones in your class, which
1098 # is almost certainly not what you want.
1100 # FIXME warn when $handle was explicitly specified, but not if the source is a regex or something
1101 #cluck("Not delegating method '$handle' because it is a core method") and
1102 next if $class_name->isa("Moose::Object") and $handle =~ /^BUILD|DEMOLISH$/ || Moose::Object->can($handle);
1104 my $method = $self->_make_delegation_method($handle, $method_to_call);
1106 $self->associated_class->add_method($method->name, $method);
1107 $self->associate_method($method);
1111 sub remove_delegation {
1113 my %handles = $self->_canonicalize_handles;
1114 my $associated_class = $self->associated_class;
1115 foreach my $handle (keys %handles) {
1116 next unless any { $handle eq $_ }
1118 @{ $self->associated_methods };
1119 $self->associated_class->remove_method($handle);
1123 # private methods to help delegation ...
1125 sub _canonicalize_handles {
1127 my $handles = $self->handles;
1128 if (my $handle_type = ref($handles)) {
1129 if ($handle_type eq 'HASH') {
1132 elsif ($handle_type eq 'ARRAY') {
1133 return map { $_ => $_ } @{$handles};
1135 elsif ($handle_type eq 'Regexp') {
1136 ($self->has_type_constraint)
1137 || $self->throw_error("Cannot delegate methods based on a Regexp without a type constraint (isa)", data => $handles);
1138 return map { ($_ => $_) }
1139 grep { /$handles/ } $self->_get_delegate_method_list;
1141 elsif ($handle_type eq 'CODE') {
1142 return $handles->($self, $self->_find_delegate_metaclass);
1144 elsif (blessed($handles) && $handles->isa('Moose::Meta::TypeConstraint::DuckType')) {
1145 return map { $_ => $_ } @{ $handles->methods };
1147 elsif (blessed($handles) && $handles->isa('Moose::Meta::TypeConstraint::Role')) {
1148 $handles = $handles->role;
1151 $self->throw_error("Unable to canonicalize the 'handles' option with $handles", data => $handles);
1155 load_class($handles);
1156 my $role_meta = Class::MOP::class_of($handles);
1158 (blessed $role_meta && $role_meta->isa('Moose::Meta::Role'))
1159 || $self->throw_error("Unable to canonicalize the 'handles' option with $handles because its metaclass is not a Moose::Meta::Role", data => $handles);
1161 return map { $_ => $_ }
1163 grep { !$_->isa('Class::MOP::Method::Meta') } (
1164 $role_meta->_get_local_methods,
1165 $role_meta->get_required_method_list,
1169 sub _get_delegate_method_list {
1171 my $meta = $self->_find_delegate_metaclass;
1172 if ($meta->isa('Class::MOP::Class')) {
1173 return map { $_->name } # NOTE: !never! delegate &meta
1174 grep { $_->package_name ne 'Moose::Object' && !$_->isa('Class::MOP::Method::Meta') }
1175 $meta->get_all_methods;
1177 elsif ($meta->isa('Moose::Meta::Role')) {
1178 return $meta->get_method_list;
1181 $self->throw_error("Unable to recognize the delegate metaclass '$meta'", data => $meta);
1185 sub _find_delegate_metaclass {
1187 if (my $class = $self->_isa_metadata) {
1188 unless ( is_class_loaded($class) ) {
1191 'The %s attribute is trying to delegate to a class which has not been loaded - %s',
1196 # we might be dealing with a non-Moose class,
1197 # and need to make our own metaclass. if there's
1198 # already a metaclass, it will be returned
1199 return Class::MOP::Class->initialize($class);
1201 elsif (my $role = $self->_does_metadata) {
1202 unless ( is_class_loaded($class) ) {
1205 'The %s attribute is trying to delegate to a role which has not been loaded - %s',
1211 return Class::MOP::class_of($role);
1214 $self->throw_error("Cannot find delegate metaclass for attribute " . $self->name);
1218 sub delegation_metaclass { 'Moose::Meta::Method::Delegation' }
1220 sub _make_delegation_method {
1221 my ( $self, $handle_name, $method_to_call ) = @_;
1223 my @curried_arguments;
1225 ($method_to_call, @curried_arguments) = @$method_to_call
1226 if 'ARRAY' eq ref($method_to_call);
1228 return $self->delegation_metaclass->new(
1229 name => $handle_name,
1230 package_name => $self->associated_class->name,
1232 delegate_to_method => $method_to_call,
1233 curried_arguments => \@curried_arguments,
1237 sub _coerce_and_verify {
1240 my $instance = shift;
1242 return $val unless $self->has_type_constraint;
1244 $val = $self->type_constraint->coerce($val)
1245 if $self->should_coerce && $self->type_constraint->has_coercion;
1247 $self->verify_against_type_constraint($val, instance => $instance);
1252 sub verify_against_type_constraint {
1256 return 1 if !$self->has_type_constraint;
1258 my $type_constraint = $self->type_constraint;
1260 $type_constraint->check($val)
1261 || $self->throw_error("Attribute ("
1263 . ") does not pass the type constraint because: "
1264 . $type_constraint->get_message($val), data => $val, @_);
1267 package Moose::Meta::Attribute::Custom::Moose;
1268 sub register_implementation { 'Moose::Meta::Attribute' }
1272 # ABSTRACT: The Moose attribute metaclass
1280 This class is a subclass of L<Class::MOP::Attribute> that provides
1281 additional Moose-specific functionality.
1283 To really understand this class, you will need to start with the
1284 L<Class::MOP::Attribute> documentation. This class can be understood
1285 as a set of additional features on top of the basic feature provided
1286 by that parent class.
1290 C<Moose::Meta::Attribute> is a subclass of L<Class::MOP::Attribute>.
1294 Many of the documented below override methods in
1295 L<Class::MOP::Attribute> and add Moose specific features.
1301 =item B<< Moose::Meta::Attribute->new(%options) >>
1303 This method overrides the L<Class::MOP::Attribute> constructor.
1305 Many of the options below are described in more detail in the
1306 L<Moose::Manual::Attributes> document.
1308 It adds the following options to the constructor:
1312 =item * is => 'ro', 'rw', 'bare'
1314 This provides a shorthand for specifying the C<reader>, C<writer>, or
1315 C<accessor> names. If the attribute is read-only ('ro') then it will
1316 have a C<reader> method with the same attribute as the name.
1318 If it is read-write ('rw') then it will have an C<accessor> method
1319 with the same name. If you provide an explicit C<writer> for a
1320 read-write attribute, then you will have a C<reader> with the same
1321 name as the attribute, and a C<writer> with the name you provided.
1323 Use 'bare' when you are deliberately not installing any methods
1324 (accessor, reader, etc.) associated with this attribute; otherwise,
1325 Moose will issue a deprecation warning when this attribute is added to a
1328 =item * isa => $type
1330 This option accepts a type. The type can be a string, which should be
1331 a type name. If the type name is unknown, it is assumed to be a class
1334 This option can also accept a L<Moose::Meta::TypeConstraint> object.
1336 If you I<also> provide a C<does> option, then your C<isa> option must
1337 be a class name, and that class must do the role specified with
1340 =item * does => $role
1342 This is short-hand for saying that the attribute's type must be an
1343 object which does the named role.
1345 =item * coerce => $bool
1347 This option is only valid for objects with a type constraint
1348 (C<isa>) that defined a coercion. If this is true, then coercions will be applied whenever
1349 this attribute is set.
1351 You can make both this and the C<weak_ref> option true.
1353 =item * trigger => $sub
1355 This option accepts a subroutine reference, which will be called after
1356 the attribute is set.
1358 =item * required => $bool
1360 An attribute which is required must be provided to the constructor. An
1361 attribute which is required can also have a C<default> or C<builder>,
1362 which will satisfy its required-ness.
1364 A required attribute must have a C<default>, C<builder> or a
1365 non-C<undef> C<init_arg>
1367 =item * lazy => $bool
1369 A lazy attribute must have a C<default> or C<builder>. When an
1370 attribute is lazy, the default value will not be calculated until the
1373 =item * weak_ref => $bool
1375 If this is true, the attribute's value will be stored as a weak
1378 =item * auto_deref => $bool
1380 If this is true, then the reader will dereference the value when it is
1381 called. The attribute must have a type constraint which defines the
1382 attribute as an array or hash reference.
1384 =item * lazy_build => $bool
1386 Setting this to true makes the attribute lazy and provides a number of
1394 is equivalent to this:
1399 builder => '_build_size',
1400 clearer => 'clear_size',
1401 predicate => 'has_size',
1405 If your attribute name starts with an underscore (C<_>), then the clearer
1406 and predicate will as well:
1418 builder => '_build__size',
1419 clearer => '_clear_size',
1420 predicate => '_has_size',
1423 Note the doubled underscore in the builder name. Internally, Moose
1424 simply prepends the attribute name with "_build_" to come up with the
1427 =item * documentation
1429 An arbitrary string that can be retrieved later by calling C<<
1430 $attr->documentation >>.
1434 =item B<< $attr->clone(%options) >>
1436 This creates a new attribute based on attribute being cloned. You must
1437 supply a C<name> option to provide a new name for the attribute.
1439 The C<%options> can only specify options handled by
1440 L<Class::MOP::Attribute>.
1444 =head2 Value management
1448 =item B<< $attr->initialize_instance_slot($meta_instance, $instance, $params) >>
1450 This method is used internally to initialize the attribute's slot in
1451 the object C<$instance>.
1453 This overrides the L<Class::MOP::Attribute> method to handle lazy
1454 attributes, weak references, and type constraints.
1460 eval { $point->meta->get_attribute('x')->set_value($point, 'forty-two') };
1465 I<Attribute (x) does not pass the type constraint (Int) with 'forty-two'>
1467 Before setting the value, a check is made on the type constraint of
1468 the attribute, if it has one, to see if the value passes it. If the
1469 value fails to pass, the set operation dies with a L</throw_error>.
1471 Any coercion to convert values is done before checking the type constraint.
1473 To check a value against a type constraint before setting it, fetch the
1474 attribute instance using L<Class::MOP::Class/find_attribute_by_name>,
1475 fetch the type_constraint from the attribute using L<Moose::Meta::Attribute/type_constraint>
1476 and call L<Moose::Meta::TypeConstraint/check>. See L<Moose::Cookbook::Basics::Recipe4>
1481 =head2 Attribute Accessor generation
1485 =item B<< $attr->install_accessors >>
1487 This method overrides the parent to also install delegation methods.
1489 If, after installing all methods, the attribute object has no associated
1490 methods, it throws an error unless C<< is => 'bare' >> was passed to the
1491 attribute constructor. (Trying to add an attribute that has no associated
1492 methods is almost always an error.)
1494 =item B<< $attr->remove_accessors >>
1496 This method overrides the parent to also remove delegation methods.
1498 =item B<< $attr->inline_set($instance_var, $value_var) >>
1500 This method return a code snippet suitable for inlining the relevant
1501 operation. It expect strings containing variable names to be used in the
1502 inlining, like C<'$self'> or C<'$_[1]'>.
1504 =item B<< $attr->install_delegation >>
1506 This method adds its delegation methods to the attribute's associated
1507 class, if it has any to add.
1509 =item B<< $attr->remove_delegation >>
1511 This method remove its delegation methods from the attribute's
1514 =item B<< $attr->accessor_metaclass >>
1516 Returns the accessor metaclass name, which defaults to
1517 L<Moose::Meta::Method::Accessor>.
1519 =item B<< $attr->delegation_metaclass >>
1521 Returns the delegation metaclass name, which defaults to
1522 L<Moose::Meta::Method::Delegation>.
1526 =head2 Additional Moose features
1528 These methods are not found in the superclass. They support features
1533 =item B<< $attr->does($role) >>
1535 This indicates whether the I<attribute itself> does the given
1536 role. The role can be given as a full class name, or as a resolvable
1539 Note that this checks the attribute itself, not its type constraint,
1540 so it is checking the attribute's metaclass and any traits applied to
1543 =item B<< Moose::Meta::Class->interpolate_class_and_new($name, %options) >>
1545 This is an alternate constructor that handles the C<metaclass> and
1548 Effectively, this method is a factory that finds or creates the
1549 appropriate class for the given C<metaclass> and/or C<traits>.
1551 Once it has the appropriate class, it will call C<< $class->new($name,
1552 %options) >> on that class.
1554 =item B<< $attr->clone_and_inherit_options(%options) >>
1556 This method supports the C<has '+foo'> feature. It does various bits
1557 of processing on the supplied C<%options> before ultimately calling
1558 the C<clone> method.
1560 One of its main tasks is to make sure that the C<%options> provided
1561 does not include the options returned by the
1562 C<illegal_options_for_inheritance> method.
1564 =item B<< $attr->illegal_options_for_inheritance >>
1566 This returns a blacklist of options that can not be overridden in a
1567 subclass's attribute definition.
1569 This exists to allow a custom metaclass to change or add to the list
1570 of options which can not be changed.
1572 =item B<< $attr->type_constraint >>
1574 Returns the L<Moose::Meta::TypeConstraint> object for this attribute,
1577 =item B<< $attr->has_type_constraint >>
1579 Returns true if this attribute has a type constraint.
1581 =item B<< $attr->verify_against_type_constraint($value) >>
1583 Given a value, this method returns true if the value is valid for the
1584 attribute's type constraint. If the value is not valid, it throws an
1587 =item B<< $attr->handles >>
1589 This returns the value of the C<handles> option passed to the
1592 =item B<< $attr->has_handles >>
1594 Returns true if this attribute performs delegation.
1596 =item B<< $attr->is_weak_ref >>
1598 Returns true if this attribute stores its value as a weak reference.
1600 =item B<< $attr->is_required >>
1602 Returns true if this attribute is required to have a value.
1604 =item B<< $attr->is_lazy >>
1606 Returns true if this attribute is lazy.
1608 =item B<< $attr->is_lazy_build >>
1610 Returns true if the C<lazy_build> option was true when passed to the
1613 =item B<< $attr->should_coerce >>
1615 Returns true if the C<coerce> option passed to the constructor was
1618 =item B<< $attr->should_auto_deref >>
1620 Returns true if the C<auto_deref> option passed to the constructor was
1623 =item B<< $attr->trigger >>
1625 This is the subroutine reference that was in the C<trigger> option
1626 passed to the constructor, if any.
1628 =item B<< $attr->has_trigger >>
1630 Returns true if this attribute has a trigger set.
1632 =item B<< $attr->documentation >>
1634 Returns the value that was in the C<documentation> option passed to
1635 the constructor, if any.
1637 =item B<< $attr->has_documentation >>
1639 Returns true if this attribute has any documentation.
1641 =item B<< $attr->applied_traits >>
1643 This returns an array reference of all the traits which were applied
1644 to this attribute. If none were applied, this returns C<undef>.
1646 =item B<< $attr->has_applied_traits >>
1648 Returns true if this attribute has any traits applied.
1654 See L<Moose/BUGS> for details on reporting bugs.