2 package Moose::Meta::Attribute;
7 use Scalar::Util 'blessed', 'weaken', 'reftype';
9 use Sub::Name 'subname';
12 our $VERSION = '0.22';
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);
66 return $class->SUPER::new($name, %options);
69 sub interpolate_class_and_new {
70 my ($class, $name, @args) = @_;
72 $class->interpolate_class(@args)->new($name, @args);
75 sub interpolate_class {
76 my ($class, %options) = @_;
78 if ( my $metaclass_name = $options{metaclass} ) {
79 $class = Moose::Util::resolve_metaclass_alias( Attribute => $metaclass_name );
82 if (my $traits = $options{traits}) {
84 Moose::Util::resolve_metatrait_alias( Attribute => $_ )
89 my $anon_class = Moose::Meta::Class->create_anon_class(
90 superclasses => [ $class ],
95 return $anon_class->name;
102 sub clone_and_inherit_options {
103 my ($self, %options) = @_;
104 # you can change default, required, coerce, documentation, lazy, handles, builder, metaclass and traits
106 foreach my $legal_option (qw(default coerce required documentation lazy handles builder metaclass traits)) {
107 if (exists $options{$legal_option}) {
108 $actual_options{$legal_option} = $options{$legal_option};
109 delete $options{$legal_option};
115 if (blessed($options{isa}) && $options{isa}->isa('Moose::Meta::TypeConstraint')) {
116 $type_constraint = $options{isa};
119 $type_constraint = Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($options{isa});
120 (defined $type_constraint)
121 || confess "Could not find the type constraint '" . $options{isa} . "'";
124 $actual_options{type_constraint} = $type_constraint;
125 delete $options{isa};
128 if ($options{does}) {
130 if (blessed($options{does}) && $options{does}->isa('Moose::Meta::TypeConstraint')) {
131 $type_constraint = $options{does};
134 $type_constraint = Moose::Util::TypeConstraints::find_or_create_does_type_constraint($options{does});
135 (defined $type_constraint)
136 || confess "Could not find the type constraint '" . $options{does} . "'";
139 $actual_options{type_constraint} = $type_constraint;
140 delete $options{does};
143 (scalar keys %options == 0)
144 || confess "Illegal inherited options => (" . (join ', ' => keys %options) . ")";
145 $self->clone(%actual_options);
148 sub _process_options {
149 my ($class, $name, $options) = @_;
151 if (exists $options->{is}) {
152 if ($options->{is} eq 'ro') {
153 $options->{reader} ||= $name;
154 (!exists $options->{trigger})
155 || confess "Cannot have a trigger on a read-only attribute $name";
157 elsif ($options->{is} eq 'rw') {
158 $options->{accessor} = $name;
159 ((reftype($options->{trigger}) || '') eq 'CODE')
160 || confess "Trigger must be a CODE ref"
161 if exists $options->{trigger};
164 confess "I do not understand this option (is => " . $options->{is} . ") on attribute $name"
168 if (exists $options->{isa}) {
169 if (exists $options->{does}) {
170 if (eval { $options->{isa}->can('does') }) {
171 ($options->{isa}->does($options->{does}))
172 || confess "Cannot have an isa option and a does option if the isa does not do the does on attribute $name";
175 confess "Cannot have an isa option which cannot ->does() on attribute $name";
179 # allow for anon-subtypes here ...
180 if (blessed($options->{isa}) && $options->{isa}->isa('Moose::Meta::TypeConstraint')) {
181 $options->{type_constraint} = $options->{isa};
184 $options->{type_constraint} = Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($options->{isa});
187 elsif (exists $options->{does}) {
188 # allow for anon-subtypes here ...
189 if (blessed($options->{does}) && $options->{does}->isa('Moose::Meta::TypeConstraint')) {
190 $options->{type_constraint} = $options->{does};
193 $options->{type_constraint} = Moose::Util::TypeConstraints::find_or_create_does_type_constraint($options->{does});
197 if (exists $options->{coerce} && $options->{coerce}) {
198 (exists $options->{type_constraint})
199 || confess "You cannot have coercion without specifying a type constraint on attribute $name";
200 confess "You cannot have a weak reference to a coerced value on attribute $name"
201 if $options->{weak_ref};
204 if (exists $options->{auto_deref} && $options->{auto_deref}) {
205 (exists $options->{type_constraint})
206 || confess "You cannot auto-dereference without specifying a type constraint on attribute $name";
207 ($options->{type_constraint}->is_a_type_of('ArrayRef') ||
208 $options->{type_constraint}->is_a_type_of('HashRef'))
209 || confess "You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute $name";
212 if (exists $options->{lazy_build} && $options->{lazy_build} == 1) {
213 confess("You can not use lazy_build and default for the same attribute $name")
214 if exists $options->{default};
215 $options->{lazy} = 1;
216 $options->{required} = 1;
217 $options->{builder} ||= "_build_${name}";
219 $options->{clearer} ||= "_clear${name}";
220 $options->{predicate} ||= "_has${name}";
223 $options->{clearer} ||= "clear_${name}";
224 $options->{predicate} ||= "has_${name}";
228 if (exists $options->{lazy} && $options->{lazy}) {
229 (exists $options->{default} || defined $options->{builder} )
230 || confess "You cannot have lazy attribute ($name) without specifying a default value for it";
233 if ( $options->{required} && !( ( !exists $options->{init_arg} || defined $options->{init_arg} ) || exists $options->{default} || defined $options->{builder} ) ) {
234 confess "You cannot have a required attribute ($name) without a default, builder, or an init_arg";
239 sub initialize_instance_slot {
240 my ($self, $meta_instance, $instance, $params) = @_;
241 my $init_arg = $self->init_arg();
242 # try to fetch the init arg from the %params ...
246 if ( defined($init_arg) and exists $params->{$init_arg}) {
247 $val = $params->{$init_arg};
251 # skip it if it's lazy
252 return if $self->is_lazy;
253 # and die if it's required and doesn't have a default value
254 confess "Attribute (" . $self->name . ") is required"
255 if $self->is_required && !$self->has_default && !$self->has_builder;
257 # if nothing was in the %params, we can use the
258 # attribute's default value (if it has one)
259 if ($self->has_default) {
260 $val = $self->default($instance);
263 elsif ($self->has_builder) {
264 if (my $builder = $instance->can($self->builder)){
265 $val = $instance->$builder;
269 confess(blessed($instance)." does not support builder method '".$self->builder."' for attribute '" . $self->name . "'");
274 return unless $value_is_set;
276 if ($self->has_type_constraint) {
277 my $type_constraint = $self->type_constraint;
278 if ($self->should_coerce && $type_constraint->has_coercion) {
279 $val = $type_constraint->coerce($val);
281 $type_constraint->check($val)
282 || confess "Attribute ("
284 . ") does not pass the type constraint because: "
285 . $type_constraint->get_message($val);
288 $self->set_initial_value($instance, $val);
289 $meta_instance->weaken_slot_value($instance, $self->name)
290 if ref $val && $self->is_weak_ref;
296 # this duplicates too much code from
297 # Class::MOP::Attribute, we need to
298 # refactor these bits eventually.
300 sub _set_initial_slot_value {
301 my ($self, $meta_instance, $instance, $value) = @_;
303 my $slot_name = $self->name;
305 return $meta_instance->set_slot_value($instance, $slot_name, $value)
306 unless $self->has_initializer;
308 my ($type_constraint, $can_coerce);
309 if ($self->has_type_constraint) {
310 $type_constraint = $self->type_constraint;
311 $can_coerce = ($self->should_coerce && $type_constraint->has_coercion);
316 if ($type_constraint) {
317 $val = $type_constraint->coerce($val)
319 $type_constraint->check($val)
320 || confess "Attribute ("
322 . ") does not pass the type constraint because: "
323 . $type_constraint->get_message($val);
325 $meta_instance->set_slot_value($instance, $slot_name, $val);
328 my $initializer = $self->initializer;
330 # most things will just want to set a value, so make it first arg
331 $instance->$initializer($value, $callback, $self);
335 my ($self, $instance, $value) = @_;
337 my $attr_name = $self->name;
339 if ($self->is_required) {
341 || confess "Attribute ($attr_name) is required, so cannot be set to undef";
344 if ($self->has_type_constraint) {
346 my $type_constraint = $self->type_constraint;
348 if ($self->should_coerce) {
349 $value = $type_constraint->coerce($value);
351 $type_constraint->_compiled_type_constraint->($value)
352 || confess "Attribute ("
354 . ") does not pass the type constraint because "
355 . $type_constraint->get_message($value);
358 my $meta_instance = Class::MOP::Class->initialize(blessed($instance))
361 $meta_instance->set_slot_value($instance, $attr_name, $value);
363 if (ref $value && $self->is_weak_ref) {
364 $meta_instance->weaken_slot_value($instance, $attr_name);
367 if ($self->has_trigger) {
368 $self->trigger->($instance, $value, $self);
373 my ($self, $instance) = @_;
375 if ($self->is_lazy) {
376 unless ($self->has_value($instance)) {
377 if ($self->has_default) {
378 my $default = $self->default($instance);
379 $self->set_initial_value($instance, $default);
381 if ( $self->has_builder ){
382 if (my $builder = $instance->can($self->builder)){
383 $self->set_initial_value($instance, $instance->$builder);
386 confess(blessed($instance)
387 . " does not support builder method '"
389 . "' for attribute '"
395 $self->set_initial_value($instance, undef);
400 if ($self->should_auto_deref) {
402 my $type_constraint = $self->type_constraint;
404 if ($type_constraint->is_a_type_of('ArrayRef')) {
405 my $rv = $self->SUPER::get_value($instance);
406 return unless defined $rv;
407 return wantarray ? @{ $rv } : $rv;
409 elsif ($type_constraint->is_a_type_of('HashRef')) {
410 my $rv = $self->SUPER::get_value($instance);
411 return unless defined $rv;
412 return wantarray ? %{ $rv } : $rv;
415 confess "Can not auto de-reference the type constraint '" . $type_constraint->name . "'";
421 return $self->SUPER::get_value($instance);
425 ## installing accessors
427 sub accessor_metaclass { 'Moose::Meta::Method::Accessor' }
429 sub install_accessors {
431 $self->SUPER::install_accessors(@_);
433 if ($self->has_handles) {
436 # Here we canonicalize the 'handles' option
437 # this will sort out any details and always
438 # return an hash of methods which we want
439 # to delagate to, see that method for details
440 my %handles = $self->_canonicalize_handles();
442 # find the accessor method for this attribute
443 my $accessor = $self->get_read_method_ref;
444 # then unpack it if we need too ...
445 $accessor = $accessor->body if blessed $accessor;
447 # install the delegation ...
448 my $associated_class = $self->associated_class;
449 foreach my $handle (keys %handles) {
450 my $method_to_call = $handles{$handle};
451 my $class_name = $associated_class->name;
452 my $name = "${class_name}::${handle}";
454 (!$associated_class->has_method($handle))
455 || confess "You cannot overwrite a locally defined method ($handle) with a delegation";
458 # handles is not allowed to delegate
459 # any of these methods, as they will
460 # override the ones in your class, which
461 # is almost certainly not what you want.
463 # FIXME warn when $handle was explicitly specified, but not if the source is a regex or something
464 #cluck("Not delegating method '$handle' because it is a core method") and
465 next if $class_name->isa("Moose::Object") and $handle =~ /^BUILD|DEMOLISH$/ || Moose::Object->can($handle);
467 if ((reftype($method_to_call) || '') eq 'CODE') {
468 $associated_class->add_method($handle => subname $name, $method_to_call);
472 # we used to do a goto here, but the
473 # goto didn't handle failure correctly
474 # (it just returned nothing), so I took
475 # that out. However, the more I thought
476 # about it, the less I liked it doing
477 # the goto, and I prefered the act of
478 # delegation being actually represented
479 # in the stack trace.
481 $associated_class->add_method($handle => subname $name, sub {
482 my $proxy = (shift)->$accessor();
484 || confess "Cannot delegate $handle to $method_to_call because " .
485 "the value of " . $self->name . " is not defined";
486 $proxy->$method_to_call(@_);
495 # private methods to help delegation ...
497 sub _canonicalize_handles {
499 my $handles = $self->handles;
500 if (my $handle_type = ref($handles)) {
501 if ($handle_type eq 'HASH') {
504 elsif ($handle_type eq 'ARRAY') {
505 return map { $_ => $_ } @{$handles};
507 elsif ($handle_type eq 'Regexp') {
508 ($self->has_type_constraint)
509 || confess "Cannot delegate methods based on a RegExpr without a type constraint (isa)";
510 return map { ($_ => $_) }
511 grep { /$handles/ } $self->_get_delegate_method_list;
513 elsif ($handle_type eq 'CODE') {
514 return $handles->($self, $self->_find_delegate_metaclass);
517 confess "Unable to canonicalize the 'handles' option with $handles";
521 my $role_meta = eval { $handles->meta };
523 confess "Unable to canonicalize the 'handles' option with $handles because : $@";
526 (blessed $role_meta && $role_meta->isa('Moose::Meta::Role'))
527 || confess "Unable to canonicalize the 'handles' option with $handles because ->meta is not a Moose::Meta::Role";
529 return map { $_ => $_ } (
530 $role_meta->get_method_list,
531 $role_meta->get_required_method_list
536 sub _find_delegate_metaclass {
538 if (my $class = $self->_isa_metadata) {
539 # if the class does have
540 # a meta method, use it
541 return $class->meta if $class->can('meta');
542 # otherwise we might be
543 # dealing with a non-Moose
544 # class, and need to make
546 return Moose::Meta::Class->initialize($class);
548 elsif (my $role = $self->_does_metadata) {
549 # our role will always have
554 confess "Cannot find delegate metaclass for attribute " . $self->name;
558 sub _get_delegate_method_list {
560 my $meta = $self->_find_delegate_metaclass;
561 if ($meta->isa('Class::MOP::Class')) {
562 return map { $_->{name} } # NOTE: !never! delegate &meta
563 grep { $_->{class} ne 'Moose::Object' && $_->{name} ne 'meta' }
564 $meta->compute_all_applicable_methods;
566 elsif ($meta->isa('Moose::Meta::Role')) {
567 return $meta->get_method_list;
570 confess "Unable to recognize the delegate metaclass '$meta'";
582 Moose::Meta::Attribute - The Moose attribute metaclass
586 This is a subclass of L<Class::MOP::Attribute> with Moose specific
589 For the most part, the only time you will ever encounter an
590 instance of this class is if you are doing some serious deep
591 introspection. To really understand this class, you need to refer
592 to the L<Class::MOP::Attribute> documentation.
596 =head2 Overridden methods
598 These methods override methods in L<Class::MOP::Attribute> and add
599 Moose specific features. You can safely assume though that they
600 will behave just as L<Class::MOP::Attribute> does.
608 =item B<initialize_instance_slot>
610 =item B<install_accessors>
612 =item B<accessor_metaclass>
618 eval { $point->meta->get_attribute('x')->set_value($point, 'fourty-two') };
623 I<Attribute (x) does not pass the type constraint (Int) with 'fourty-two'>
625 Before setting the value, a check is made on the type constraint of
626 the attribute, if it has one, to see if the value passes it. If the
627 value fails to pass, the set operation dies with a L<Carp/confess>.
629 Any coercion to convert values is done before checking the type constraint.
631 To check a value against a type constraint before setting it, fetch the
632 attribute instance using L<Class::MOP::Class/find_attribute_by_name>,
633 fetch the type_constraint from the attribute using L<Moose::Meta::Attribute/type_constraint>
634 and call L<Moose::Meta::TypeConstraint/check>. See L<Moose::Cookbook::RecipeX>
639 =head2 Additional Moose features
641 Moose attributes support type-constraint checking, weak reference
642 creation and type coercion.
646 =item B<interpolate_class_and_new>
648 =item B<interpolate_class>
650 When called as a class method causes interpretation of the C<metaclass> and
653 =item B<clone_and_inherit_options>
655 This is to support the C<has '+foo'> feature, it clones an attribute
656 from a superclass and allows a very specific set of changes to be made
659 =item B<has_type_constraint>
661 Returns true if this meta-attribute has a type constraint.
663 =item B<type_constraint>
665 A read-only accessor for this meta-attribute's type constraint. For
666 more information on what you can do with this, see the documentation
667 for L<Moose::Meta::TypeConstraint>.
671 Returns true if this meta-attribute performs delegation.
675 This returns the value which was passed into the handles option.
679 Returns true if this meta-attribute produces a weak reference.
683 Returns true if this meta-attribute is required to have a value.
687 Returns true if this meta-attribute should be initialized lazily.
689 NOTE: lazy attributes, B<must> have a C<default> or C<builder> field set.
691 =item B<is_lazy_build>
693 Returns true if this meta-attribute should be initialized lazily through
694 the builder generated by lazy_build. Using C<lazy_build =E<gt> 1> will
695 make your attribute required and lazy. In addition it will set the builder, clearer
696 and predicate options for you using the following convention.
698 #If your attribute name starts with an underscore:
699 has '_foo' => (lazy_build => 1);
701 has '_foo' => (lazy => 1, required => 1, predicate => '_has_foo', clearer => '_clear_foo', builder => '_build__foo);
703 has '_foo' => (lazy => 1, required => 1, predicate => '_has_foo', clearer => '_clear_foo', default => sub{shift->_build__foo});
705 #If your attribute name does not start with an underscore:
706 has 'foo' => (lazy_build => 1);
708 has 'foo' => (lazy => 1, required => 1, predicate => 'has_foo', clearer => 'clear_foo', builder => '_build_foo);
710 has 'foo' => (lazy => 1, required => 1, predicate => 'has_foo', clearer => 'clear_foo', default => sub{shift->_build_foo});
712 The reason for the different naming of the C<builder> is that the C<builder>
713 method is a private method while the C<clearer> and C<predicate> methods
716 NOTE: This means your class should provide a method whose name matches the value
717 of the builder part, in this case _build__foo or _build_foo.
719 =item B<should_coerce>
721 Returns true if this meta-attribute should perform type coercion.
723 =item B<should_auto_deref>
725 Returns true if this meta-attribute should perform automatic
728 NOTE: This can only be done for attributes whose type constraint is
729 either I<ArrayRef> or I<HashRef>.
733 Returns true if this meta-attribute has a trigger set.
737 This is a CODE reference which will be executed every time the
738 value of an attribute is assigned. The CODE ref will get two values,
739 the invocant and the new value. This can be used to handle I<basic>
740 bi-directional relations.
742 =item B<documentation>
744 This is a string which contains the documentation for this attribute.
745 It serves no direct purpose right now, but it might in the future
746 in some kind of automated documentation system perhaps.
748 =item B<has_documentation>
750 Returns true if this meta-attribute has any documentation.
752 =item B<applied_traits>
754 This will return the ARRAY ref of all the traits applied to this
755 attribute, or if no traits have been applied, it returns C<undef>.
757 =item B<has_applied_traits>
759 Returns true if this meta-attribute has any traits applied.
765 All complex software has bugs lurking in it, and this module is no
766 exception. If you find a bug please either email me, or add the bug
771 Stevan Little E<lt>stevan@iinteractive.comE<gt>
773 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
775 =head1 COPYRIGHT AND LICENSE
777 Copyright 2006-2008 by Infinity Interactive, Inc.
779 L<http://www.iinteractive.com>
781 This library is free software; you can redistribute it and/or modify
782 it under the same terms as Perl itself.