2 package Moose::Meta::Attribute;
7 use Scalar::Util 'blessed', 'weaken', 'reftype';
9 use Sub::Name 'subname';
12 our $VERSION = '0.23';
13 our $AUTHORITY = 'cpan:STEVAN';
15 use Moose::Meta::Method::Accessor;
17 use Moose::Util::TypeConstraints ();
19 use base 'Class::MOP::Attribute';
21 # options which are not directly used
22 # but we store them for metadata purposes
23 __PACKAGE__->meta->add_attribute('isa' => (reader => '_isa_metadata'));
24 __PACKAGE__->meta->add_attribute('does' => (reader => '_does_metadata'));
25 __PACKAGE__->meta->add_attribute('is' => (reader => '_is_metadata'));
27 # these are actual options for the attrs
28 __PACKAGE__->meta->add_attribute('required' => (reader => 'is_required' ));
29 __PACKAGE__->meta->add_attribute('lazy' => (reader => 'is_lazy' ));
30 __PACKAGE__->meta->add_attribute('lazy_build' => (reader => 'is_lazy_build' ));
31 __PACKAGE__->meta->add_attribute('coerce' => (reader => 'should_coerce' ));
32 __PACKAGE__->meta->add_attribute('weak_ref' => (reader => 'is_weak_ref' ));
33 __PACKAGE__->meta->add_attribute('auto_deref' => (reader => 'should_auto_deref'));
34 __PACKAGE__->meta->add_attribute('type_constraint' => (
35 reader => 'type_constraint',
36 predicate => 'has_type_constraint',
38 __PACKAGE__->meta->add_attribute('trigger' => (
40 predicate => 'has_trigger',
42 __PACKAGE__->meta->add_attribute('handles' => (
44 predicate => 'has_handles',
46 __PACKAGE__->meta->add_attribute('documentation' => (
47 reader => 'documentation',
48 predicate => 'has_documentation',
50 __PACKAGE__->meta->add_attribute('traits' => (
51 reader => 'applied_traits',
52 predicate => 'has_applied_traits',
56 # we need to have a ->does method in here to
57 # more easily support traits, and the introspection
58 # of those traits. So in order to do this we
59 # just alias Moose::Object's version of it.
61 *does = \&Moose::Object::does;
64 my ($class, $name, %options) = @_;
65 $class->_process_options($name, \%options) unless $options{__hack_no_process_options}; # used from clone()... YECHKKK FIXME ICKY YUCK GROSS
66 return $class->SUPER::new($name, %options);
69 sub interpolate_class_and_new {
70 my ($class, $name, @args) = @_;
72 my ( $new_class, @traits ) = $class->interpolate_class(@args);
74 $new_class->new($name, @args, ( scalar(@traits) ? ( traits => \@traits ) : () ) );
77 sub interpolate_class {
78 my ($class, %options) = @_;
80 $class = ref($class) || $class;
82 if ( my $metaclass_name = delete $options{metaclass} ) {
83 my $new_class = Moose::Util::resolve_metaclass_alias( Attribute => $metaclass_name );
85 if ( $class ne $new_class ) {
86 if ( $new_class->can("interpolate_class") ) {
87 return $new_class->interpolate_class(%options);
96 if (my $traits = $options{traits}) {
97 if ( @traits = grep { not $class->does($_) } map {
98 Moose::Util::resolve_metatrait_alias( Attribute => $_ )
102 my $anon_class = Moose::Meta::Class->create_anon_class(
103 superclasses => [ $class ],
104 roles => [ @traits ],
108 $class = $anon_class->name;
112 return ( wantarray ? ( $class, @traits ) : $class );
115 sub clone_and_inherit_options {
116 my ($self, %options) = @_;
118 # you can change default, required, coerce, documentation, lazy, handles, builder, type_constraint (explicitly or using isa/does), metaclass and traits
120 foreach my $legal_option (qw(default coerce required documentation lazy handles builder type_constraint)) {
121 if (exists $options{$legal_option}) {
122 $actual_options{$legal_option} = $options{$legal_option};
123 delete $options{$legal_option};
129 if (blessed($options{isa}) && $options{isa}->isa('Moose::Meta::TypeConstraint')) {
130 $type_constraint = $options{isa};
133 $type_constraint = Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($options{isa});
134 (defined $type_constraint)
135 || confess "Could not find the type constraint '" . $options{isa} . "'";
138 $actual_options{type_constraint} = $type_constraint;
139 delete $options{isa};
142 if ($options{does}) {
144 if (blessed($options{does}) && $options{does}->isa('Moose::Meta::TypeConstraint')) {
145 $type_constraint = $options{does};
148 $type_constraint = Moose::Util::TypeConstraints::find_or_create_does_type_constraint($options{does});
149 (defined $type_constraint)
150 || confess "Could not find the type constraint '" . $options{does} . "'";
153 $actual_options{type_constraint} = $type_constraint;
154 delete $options{does};
158 # this doesn't apply to Class::MOP::Attributes,
159 # so we can ignore it for them.
161 if ($self->can('interpolate_class')) {
162 ( $actual_options{metaclass}, my @traits ) = $self->interpolate_class(%options);
165 my @all_traits = grep { $seen{$_}++ } @{ $self->applied_traits || [] }, @traits;
166 $actual_options{traits} = \@all_traits if @all_traits;
168 delete @options{qw(metaclass traits)};
171 (scalar keys %options == 0)
172 || confess "Illegal inherited options => (" . (join ', ' => keys %options) . ")";
175 $self->clone(%actual_options);
179 my ( $self, %params ) = @_;
181 my $class = $params{metaclass} || ref $self;
183 if ( 0 and $class eq ref $self ) {
184 return $self->SUPER::clone(%params);
186 my ( @init, @non_init );
188 foreach my $attr ( grep { $_->has_value($self) } $self->meta->compute_all_applicable_attributes ) {
189 push @{ $attr->has_init_arg ? \@init : \@non_init }, $attr;
192 my %new_params = ( ( map { $_->init_arg => $_->get_value($self) } @init ), %params );
194 my $name = delete $new_params{name};
196 my $clone = $class->new($name, %new_params, __hack_no_process_options => 1 );
198 foreach my $attr ( @non_init ) {
199 $attr->set_value($clone, $attr->get_value($self));
207 sub _process_options {
208 my ($class, $name, $options) = @_;
210 if (exists $options->{is}) {
211 if ($options->{is} eq 'ro') {
212 $options->{reader} ||= $name;
213 (!exists $options->{trigger})
214 || confess "Cannot have a trigger on a read-only attribute $name";
216 elsif ($options->{is} eq 'rw') {
217 $options->{accessor} = $name;
218 ((reftype($options->{trigger}) || '') eq 'CODE')
219 || confess "Trigger must be a CODE ref"
220 if exists $options->{trigger};
223 confess "I do not understand this option (is => " . $options->{is} . ") on attribute $name"
227 if (exists $options->{isa}) {
228 if (exists $options->{does}) {
229 if (eval { $options->{isa}->can('does') }) {
230 ($options->{isa}->does($options->{does}))
231 || confess "Cannot have an isa option and a does option if the isa does not do the does on attribute $name";
234 confess "Cannot have an isa option which cannot ->does() on attribute $name";
238 # allow for anon-subtypes here ...
239 if (blessed($options->{isa}) && $options->{isa}->isa('Moose::Meta::TypeConstraint')) {
240 $options->{type_constraint} = $options->{isa};
243 $options->{type_constraint} = Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($options->{isa});
246 elsif (exists $options->{does}) {
247 # allow for anon-subtypes here ...
248 if (blessed($options->{does}) && $options->{does}->isa('Moose::Meta::TypeConstraint')) {
249 $options->{type_constraint} = $options->{does};
252 $options->{type_constraint} = Moose::Util::TypeConstraints::find_or_create_does_type_constraint($options->{does});
256 if (exists $options->{coerce} && $options->{coerce}) {
257 (exists $options->{type_constraint})
258 || confess "You cannot have coercion without specifying a type constraint on attribute $name";
259 confess "You cannot have a weak reference to a coerced value on attribute $name"
260 if $options->{weak_ref};
263 if (exists $options->{auto_deref} && $options->{auto_deref}) {
264 (exists $options->{type_constraint})
265 || confess "You cannot auto-dereference without specifying a type constraint on attribute $name";
266 ($options->{type_constraint}->is_a_type_of('ArrayRef') ||
267 $options->{type_constraint}->is_a_type_of('HashRef'))
268 || confess "You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute $name";
271 if (exists $options->{lazy_build} && $options->{lazy_build} == 1) {
272 confess("You can not use lazy_build and default for the same attribute $name")
273 if exists $options->{default};
274 $options->{lazy} = 1;
275 $options->{required} = 1;
276 $options->{builder} ||= "_build_${name}";
278 $options->{clearer} ||= "_clear${name}";
279 $options->{predicate} ||= "_has${name}";
282 $options->{clearer} ||= "clear_${name}";
283 $options->{predicate} ||= "has_${name}";
287 if (exists $options->{lazy} && $options->{lazy}) {
288 (exists $options->{default} || defined $options->{builder} )
289 || confess "You cannot have lazy attribute ($name) without specifying a default value for it";
292 if ( $options->{required} && !( ( !exists $options->{init_arg} || defined $options->{init_arg} ) || exists $options->{default} || defined $options->{builder} ) ) {
293 confess "You cannot have a required attribute ($name) without a default, builder, or an init_arg";
298 sub initialize_instance_slot {
299 my ($self, $meta_instance, $instance, $params) = @_;
300 my $init_arg = $self->init_arg();
301 # try to fetch the init arg from the %params ...
305 if ( defined($init_arg) and exists $params->{$init_arg}) {
306 $val = $params->{$init_arg};
310 # skip it if it's lazy
311 return if $self->is_lazy;
312 # and die if it's required and doesn't have a default value
313 confess "Attribute (" . $self->name . ") is required"
314 if $self->is_required && !$self->has_default && !$self->has_builder;
316 # if nothing was in the %params, we can use the
317 # attribute's default value (if it has one)
318 if ($self->has_default) {
319 $val = $self->default($instance);
322 elsif ($self->has_builder) {
323 if (my $builder = $instance->can($self->builder)){
324 $val = $instance->$builder;
328 confess(blessed($instance)." does not support builder method '".$self->builder."' for attribute '" . $self->name . "'");
333 return unless $value_is_set;
335 if ($self->has_type_constraint) {
336 my $type_constraint = $self->type_constraint;
337 if ($self->should_coerce && $type_constraint->has_coercion) {
338 $val = $type_constraint->coerce($val);
340 $type_constraint->check($val)
341 || confess "Attribute ("
343 . ") does not pass the type constraint because: "
344 . $type_constraint->get_message($val);
347 $self->set_initial_value($instance, $val);
348 $meta_instance->weaken_slot_value($instance, $self->name)
349 if ref $val && $self->is_weak_ref;
355 # this duplicates too much code from
356 # Class::MOP::Attribute, we need to
357 # refactor these bits eventually.
359 sub _set_initial_slot_value {
360 my ($self, $meta_instance, $instance, $value) = @_;
362 my $slot_name = $self->name;
364 return $meta_instance->set_slot_value($instance, $slot_name, $value)
365 unless $self->has_initializer;
367 my ($type_constraint, $can_coerce);
368 if ($self->has_type_constraint) {
369 $type_constraint = $self->type_constraint;
370 $can_coerce = ($self->should_coerce && $type_constraint->has_coercion);
375 if ($type_constraint) {
376 $val = $type_constraint->coerce($val)
378 $type_constraint->check($val)
379 || confess "Attribute ("
381 . ") does not pass the type constraint because: "
382 . $type_constraint->get_message($val);
384 $meta_instance->set_slot_value($instance, $slot_name, $val);
387 my $initializer = $self->initializer;
389 # most things will just want to set a value, so make it first arg
390 $instance->$initializer($value, $callback, $self);
394 my ($self, $instance, $value) = @_;
396 my $attr_name = $self->name;
398 if ($self->is_required) {
400 || confess "Attribute ($attr_name) is required, so cannot be set to undef";
403 if ($self->has_type_constraint) {
405 my $type_constraint = $self->type_constraint;
407 if ($self->should_coerce) {
408 $value = $type_constraint->coerce($value);
410 $type_constraint->_compiled_type_constraint->($value)
411 || confess "Attribute ("
413 . ") does not pass the type constraint because "
414 . $type_constraint->get_message($value);
417 my $meta_instance = Class::MOP::Class->initialize(blessed($instance))
420 $meta_instance->set_slot_value($instance, $attr_name, $value);
422 if (ref $value && $self->is_weak_ref) {
423 $meta_instance->weaken_slot_value($instance, $attr_name);
426 if ($self->has_trigger) {
427 $self->trigger->($instance, $value, $self);
432 my ($self, $instance) = @_;
434 if ($self->is_lazy) {
435 unless ($self->has_value($instance)) {
436 if ($self->has_default) {
437 my $default = $self->default($instance);
438 $self->set_initial_value($instance, $default);
440 if ( $self->has_builder ){
441 if (my $builder = $instance->can($self->builder)){
442 $self->set_initial_value($instance, $instance->$builder);
445 confess(blessed($instance)
446 . " does not support builder method '"
448 . "' for attribute '"
454 $self->set_initial_value($instance, undef);
459 if ($self->should_auto_deref) {
461 my $type_constraint = $self->type_constraint;
463 if ($type_constraint->is_a_type_of('ArrayRef')) {
464 my $rv = $self->SUPER::get_value($instance);
465 return unless defined $rv;
466 return wantarray ? @{ $rv } : $rv;
468 elsif ($type_constraint->is_a_type_of('HashRef')) {
469 my $rv = $self->SUPER::get_value($instance);
470 return unless defined $rv;
471 return wantarray ? %{ $rv } : $rv;
474 confess "Can not auto de-reference the type constraint '" . $type_constraint->name . "'";
480 return $self->SUPER::get_value($instance);
484 ## installing accessors
486 sub accessor_metaclass { 'Moose::Meta::Method::Accessor' }
488 sub install_accessors {
490 $self->SUPER::install_accessors(@_);
492 if ($self->has_handles) {
495 # Here we canonicalize the 'handles' option
496 # this will sort out any details and always
497 # return an hash of methods which we want
498 # to delagate to, see that method for details
499 my %handles = $self->_canonicalize_handles();
501 # find the accessor method for this attribute
502 my $accessor = $self->get_read_method_ref;
503 # then unpack it if we need too ...
504 $accessor = $accessor->body if blessed $accessor;
506 # install the delegation ...
507 my $associated_class = $self->associated_class;
508 foreach my $handle (keys %handles) {
509 my $method_to_call = $handles{$handle};
510 my $class_name = $associated_class->name;
511 my $name = "${class_name}::${handle}";
513 (!$associated_class->has_method($handle))
514 || confess "You cannot overwrite a locally defined method ($handle) with a delegation";
517 # handles is not allowed to delegate
518 # any of these methods, as they will
519 # override the ones in your class, which
520 # is almost certainly not what you want.
522 # FIXME warn when $handle was explicitly specified, but not if the source is a regex or something
523 #cluck("Not delegating method '$handle' because it is a core method") and
524 next if $class_name->isa("Moose::Object") and $handle =~ /^BUILD|DEMOLISH$/ || Moose::Object->can($handle);
526 if ((reftype($method_to_call) || '') eq 'CODE') {
527 $associated_class->add_method($handle => subname $name, $method_to_call);
531 # we used to do a goto here, but the
532 # goto didn't handle failure correctly
533 # (it just returned nothing), so I took
534 # that out. However, the more I thought
535 # about it, the less I liked it doing
536 # the goto, and I prefered the act of
537 # delegation being actually represented
538 # in the stack trace.
540 $associated_class->add_method($handle => subname $name, sub {
541 my $proxy = (shift)->$accessor();
543 || confess "Cannot delegate $handle to $method_to_call because " .
544 "the value of " . $self->name . " is not defined";
545 $proxy->$method_to_call(@_);
554 # private methods to help delegation ...
556 sub _canonicalize_handles {
558 my $handles = $self->handles;
559 if (my $handle_type = ref($handles)) {
560 if ($handle_type eq 'HASH') {
563 elsif ($handle_type eq 'ARRAY') {
564 return map { $_ => $_ } @{$handles};
566 elsif ($handle_type eq 'Regexp') {
567 ($self->has_type_constraint)
568 || confess "Cannot delegate methods based on a RegExpr without a type constraint (isa)";
569 return map { ($_ => $_) }
570 grep { /$handles/ } $self->_get_delegate_method_list;
572 elsif ($handle_type eq 'CODE') {
573 return $handles->($self, $self->_find_delegate_metaclass);
576 confess "Unable to canonicalize the 'handles' option with $handles";
580 my $role_meta = eval { $handles->meta };
582 confess "Unable to canonicalize the 'handles' option with $handles because : $@";
585 (blessed $role_meta && $role_meta->isa('Moose::Meta::Role'))
586 || confess "Unable to canonicalize the 'handles' option with $handles because ->meta is not a Moose::Meta::Role";
588 return map { $_ => $_ } (
589 $role_meta->get_method_list,
590 $role_meta->get_required_method_list
595 sub _find_delegate_metaclass {
597 if (my $class = $self->_isa_metadata) {
598 # if the class does have
599 # a meta method, use it
600 return $class->meta if $class->can('meta');
601 # otherwise we might be
602 # dealing with a non-Moose
603 # class, and need to make
605 return Moose::Meta::Class->initialize($class);
607 elsif (my $role = $self->_does_metadata) {
608 # our role will always have
613 confess "Cannot find delegate metaclass for attribute " . $self->name;
617 sub _get_delegate_method_list {
619 my $meta = $self->_find_delegate_metaclass;
620 if ($meta->isa('Class::MOP::Class')) {
621 return map { $_->{name} } # NOTE: !never! delegate &meta
622 grep { $_->{class} ne 'Moose::Object' && $_->{name} ne 'meta' }
623 $meta->compute_all_applicable_methods;
625 elsif ($meta->isa('Moose::Meta::Role')) {
626 return $meta->get_method_list;
629 confess "Unable to recognize the delegate metaclass '$meta'";
641 Moose::Meta::Attribute - The Moose attribute metaclass
645 This is a subclass of L<Class::MOP::Attribute> with Moose specific
648 For the most part, the only time you will ever encounter an
649 instance of this class is if you are doing some serious deep
650 introspection. To really understand this class, you need to refer
651 to the L<Class::MOP::Attribute> documentation.
655 =head2 Overridden methods
657 These methods override methods in L<Class::MOP::Attribute> and add
658 Moose specific features. You can safely assume though that they
659 will behave just as L<Class::MOP::Attribute> does.
669 =item B<initialize_instance_slot>
671 =item B<install_accessors>
673 =item B<accessor_metaclass>
679 eval { $point->meta->get_attribute('x')->set_value($point, 'fourty-two') };
684 I<Attribute (x) does not pass the type constraint (Int) with 'fourty-two'>
686 Before setting the value, a check is made on the type constraint of
687 the attribute, if it has one, to see if the value passes it. If the
688 value fails to pass, the set operation dies with a L<Carp/confess>.
690 Any coercion to convert values is done before checking the type constraint.
692 To check a value against a type constraint before setting it, fetch the
693 attribute instance using L<Class::MOP::Class/find_attribute_by_name>,
694 fetch the type_constraint from the attribute using L<Moose::Meta::Attribute/type_constraint>
695 and call L<Moose::Meta::TypeConstraint/check>. See L<Moose::Cookbook::RecipeX>
700 =head2 Additional Moose features
702 Moose attributes support type-constraint checking, weak reference
703 creation and type coercion.
707 =item B<interpolate_class_and_new>
709 =item B<interpolate_class>
711 When called as a class method causes interpretation of the C<metaclass> and
714 =item B<clone_and_inherit_options>
716 This is to support the C<has '+foo'> feature, it clones an attribute
717 from a superclass and allows a very specific set of changes to be made
720 =item B<has_type_constraint>
722 Returns true if this meta-attribute has a type constraint.
724 =item B<type_constraint>
726 A read-only accessor for this meta-attribute's type constraint. For
727 more information on what you can do with this, see the documentation
728 for L<Moose::Meta::TypeConstraint>.
732 Returns true if this meta-attribute performs delegation.
736 This returns the value which was passed into the handles option.
740 Returns true if this meta-attribute produces a weak reference.
744 Returns true if this meta-attribute is required to have a value.
748 Returns true if this meta-attribute should be initialized lazily.
750 NOTE: lazy attributes, B<must> have a C<default> or C<builder> field set.
752 =item B<is_lazy_build>
754 Returns true if this meta-attribute should be initialized lazily through
755 the builder generated by lazy_build. Using C<lazy_build =E<gt> 1> will
756 make your attribute required and lazy. In addition it will set the builder, clearer
757 and predicate options for you using the following convention.
759 #If your attribute name starts with an underscore:
760 has '_foo' => (lazy_build => 1);
762 has '_foo' => (lazy => 1, required => 1, predicate => '_has_foo', clearer => '_clear_foo', builder => '_build__foo);
764 has '_foo' => (lazy => 1, required => 1, predicate => '_has_foo', clearer => '_clear_foo', default => sub{shift->_build__foo});
766 #If your attribute name does not start with an underscore:
767 has 'foo' => (lazy_build => 1);
769 has 'foo' => (lazy => 1, required => 1, predicate => 'has_foo', clearer => 'clear_foo', builder => '_build_foo);
771 has 'foo' => (lazy => 1, required => 1, predicate => 'has_foo', clearer => 'clear_foo', default => sub{shift->_build_foo});
773 The reason for the different naming of the C<builder> is that the C<builder>
774 method is a private method while the C<clearer> and C<predicate> methods
777 NOTE: This means your class should provide a method whose name matches the value
778 of the builder part, in this case _build__foo or _build_foo.
780 =item B<should_coerce>
782 Returns true if this meta-attribute should perform type coercion.
784 =item B<should_auto_deref>
786 Returns true if this meta-attribute should perform automatic
789 NOTE: This can only be done for attributes whose type constraint is
790 either I<ArrayRef> or I<HashRef>.
794 Returns true if this meta-attribute has a trigger set.
798 This is a CODE reference which will be executed every time the
799 value of an attribute is assigned. The CODE ref will get two values,
800 the invocant and the new value. This can be used to handle I<basic>
801 bi-directional relations.
803 =item B<documentation>
805 This is a string which contains the documentation for this attribute.
806 It serves no direct purpose right now, but it might in the future
807 in some kind of automated documentation system perhaps.
809 =item B<has_documentation>
811 Returns true if this meta-attribute has any documentation.
813 =item B<applied_traits>
815 This will return the ARRAY ref of all the traits applied to this
816 attribute, or if no traits have been applied, it returns C<undef>.
818 =item B<has_applied_traits>
820 Returns true if this meta-attribute has any traits applied.
826 All complex software has bugs lurking in it, and this module is no
827 exception. If you find a bug please either email me, or add the bug
832 Stevan Little E<lt>stevan@iinteractive.comE<gt>
834 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
836 =head1 COPYRIGHT AND LICENSE
838 Copyright 2006-2008 by Infinity Interactive, Inc.
840 L<http://www.iinteractive.com>
842 This library is free software; you can redistribute it and/or modify
843 it under the same terms as Perl itself.