2 package Moose::Meta::Attribute;
7 use Scalar::Util 'blessed', 'weaken', 'reftype';
10 our $VERSION = '0.10';
11 our $AUTHORITY = 'cpan:STEVAN';
13 use Moose::Meta::Method::Accessor;
14 use Moose::Util::TypeConstraints ();
16 use base 'Class::MOP::Attribute';
18 # options which are not directly used
19 # but we store them for metadata purposes
20 __PACKAGE__->meta->add_attribute('isa' => (reader => '_isa_metadata'));
21 __PACKAGE__->meta->add_attribute('does' => (reader => '_does_metadata'));
22 __PACKAGE__->meta->add_attribute('is' => (reader => '_is_metadata'));
24 # these are actual options for the attrs
25 __PACKAGE__->meta->add_attribute('required' => (reader => 'is_required' ));
26 __PACKAGE__->meta->add_attribute('lazy' => (reader => 'is_lazy' ));
27 __PACKAGE__->meta->add_attribute('coerce' => (reader => 'should_coerce' ));
28 __PACKAGE__->meta->add_attribute('weak_ref' => (reader => 'is_weak_ref' ));
29 __PACKAGE__->meta->add_attribute('auto_deref' => (reader => 'should_auto_deref'));
30 __PACKAGE__->meta->add_attribute('type_constraint' => (
31 reader => 'type_constraint',
32 predicate => 'has_type_constraint',
34 __PACKAGE__->meta->add_attribute('trigger' => (
36 predicate => 'has_trigger',
38 __PACKAGE__->meta->add_attribute('handles' => (
40 predicate => 'has_handles',
42 __PACKAGE__->meta->add_attribute('documentation' => (
43 reader => 'documentation',
44 predicate => 'has_documentation',
48 my ($class, $name, %options) = @_;
49 $class->_process_options($name, \%options);
50 return $class->SUPER::new($name, %options);
53 sub clone_and_inherit_options {
54 my ($self, %options) = @_;
55 # you can change default, required, coerce and documentation
57 foreach my $legal_option (qw(default coerce required documentation)) {
58 if (exists $options{$legal_option}) {
59 $actual_options{$legal_option} = $options{$legal_option};
60 delete $options{$legal_option};
63 # isa can be changed, but only if the
64 # new type is a subtype
67 if (blessed($options{isa}) && $options{isa}->isa('Moose::Meta::TypeConstraint')) {
68 $type_constraint = $options{isa};
71 $type_constraint = Moose::Util::TypeConstraints::find_type_constraint($options{isa});
72 (defined $type_constraint)
73 || confess "Could not find the type constraint '" . $options{isa} . "'";
76 # check here to see if the new type
77 # is a subtype of the old one
78 ($type_constraint->is_subtype_of($self->type_constraint->name))
79 || confess "New type constraint setting must be a subtype of inherited one"
80 # iff we have a type constraint that is ...
81 if $self->has_type_constraint;
83 $actual_options{type_constraint} = $type_constraint;
86 (scalar keys %options == 0)
87 || confess "Illegal inherited options => (" . (join ', ' => keys %options) . ")";
88 $self->clone(%actual_options);
91 sub _process_options {
92 my ($class, $name, $options) = @_;
94 if (exists $options->{is}) {
95 if ($options->{is} eq 'ro') {
96 $options->{reader} = $name;
97 (!exists $options->{trigger})
98 || confess "Cannot have a trigger on a read-only attribute";
100 elsif ($options->{is} eq 'rw') {
101 $options->{accessor} = $name;
102 ((reftype($options->{trigger}) || '') eq 'CODE')
103 || confess "Trigger must be a CODE ref"
104 if exists $options->{trigger};
107 confess "I do not understand this option (is => " . $options->{is} . ")"
111 if (exists $options->{isa}) {
113 if (exists $options->{does}) {
114 if (eval { $options->{isa}->can('does') }) {
115 ($options->{isa}->does($options->{does}))
116 || confess "Cannot have an isa option and a does option if the isa does not do the does";
119 confess "Cannot have an isa option which cannot ->does()";
123 # allow for anon-subtypes here ...
124 if (blessed($options->{isa}) && $options->{isa}->isa('Moose::Meta::TypeConstraint')) {
125 $options->{type_constraint} = $options->{isa};
129 if ($options->{isa} =~ /\|/) {
130 my @type_constraints = split /\s*\|\s*/ => $options->{isa};
131 $options->{type_constraint} = Moose::Util::TypeConstraints::create_type_constraint_union(
136 # otherwise assume it is a constraint
137 my $constraint = Moose::Util::TypeConstraints::find_type_constraint($options->{isa});
138 # if the constraing it not found ....
139 unless (defined $constraint) {
140 # assume it is a foreign class, and make
141 # an anon constraint for it
142 $constraint = Moose::Util::TypeConstraints::subtype(
144 Moose::Util::TypeConstraints::where { $_->isa($options->{isa}) }
147 $options->{type_constraint} = $constraint;
151 elsif (exists $options->{does}) {
152 # allow for anon-subtypes here ...
153 if (blessed($options->{does}) && $options->{does}->isa('Moose::Meta::TypeConstraint')) {
154 $options->{type_constraint} = $options->{isa};
157 # otherwise assume it is a constraint
158 my $constraint = Moose::Util::TypeConstraints::find_type_constraint($options->{does});
159 # if the constraing it not found ....
160 unless (defined $constraint) {
161 # assume it is a foreign class, and make
162 # an anon constraint for it
163 $constraint = Moose::Util::TypeConstraints::subtype(
165 Moose::Util::TypeConstraints::where { $_->does($options->{does}) }
168 $options->{type_constraint} = $constraint;
172 if (exists $options->{coerce} && $options->{coerce}) {
173 (exists $options->{type_constraint})
174 || confess "You cannot have coercion without specifying a type constraint";
175 confess "You cannot have a weak reference to a coerced value"
176 if $options->{weak_ref};
179 if (exists $options->{auto_deref} && $options->{auto_deref}) {
180 (exists $options->{type_constraint})
181 || confess "You cannot auto-dereference without specifying a type constraint";
182 ($options->{type_constraint}->is_a_type_of('ArrayRef') ||
183 $options->{type_constraint}->is_a_type_of('HashRef'))
184 || confess "You cannot auto-dereference anything other than a ArrayRef or HashRef";
187 if (exists $options->{lazy} && $options->{lazy}) {
188 (exists $options->{default})
189 || confess "You cannot have lazy attribute without specifying a default value for it";
193 sub initialize_instance_slot {
194 my ($self, $meta_instance, $instance, $params) = @_;
195 my $init_arg = $self->init_arg();
196 # try to fetch the init arg from the %params ...
199 if (exists $params->{$init_arg}) {
200 $val = $params->{$init_arg};
203 # skip it if it's lazy
204 return if $self->is_lazy;
205 # and die if it's required and doesn't have a default value
206 confess "Attribute (" . $self->name . ") is required"
207 if $self->is_required && !$self->has_default;
210 # if nothing was in the %params, we can use the
211 # attribute's default value (if it has one)
212 if (!defined $val && $self->has_default) {
213 $val = $self->default($instance);
216 if ($self->has_type_constraint) {
217 my $type_constraint = $self->type_constraint;
218 if ($self->should_coerce && $type_constraint->has_coercion) {
219 $val = $type_constraint->coerce($val);
221 (defined($type_constraint->check($val)))
222 || confess "Attribute (" .
224 ") does not pass the type constraint (" .
225 $type_constraint->name .
230 $meta_instance->set_slot_value($instance, $self->name, $val);
231 $meta_instance->weaken_slot_value($instance, $self->name)
232 if ref $val && $self->is_weak_ref;
238 my ($self, $instance, $value) = @_;
240 my $attr_name = $self->name;
242 if ($self->is_required) {
244 || confess "Attribute ($attr_name) is required, so cannot be set to undef";
247 if ($self->has_type_constraint) {
249 my $type_constraint = $self->type_constraint;
251 if ($self->should_coerce) {
252 $value = $type_constraint->coerce($value);
254 defined($type_constraint->_compiled_type_constraint->($value))
255 || confess "Attribute ($attr_name) does not pass the type constraint ("
256 . $type_constraint->name . ") with " . (defined($value) ? ("'" . $value . "'") : "undef")
260 my $meta_instance = Class::MOP::Class->initialize(blessed($instance))
263 $meta_instance->set_slot_value($instance, $attr_name, $value);
265 if (ref $value && $self->is_weak_ref) {
266 $meta_instance->weaken_slot_value($instance, $attr_name);
269 if ($self->has_trigger) {
270 $self->trigger->($instance, $value, $self);
275 my ($self, $instance) = @_;
277 if ($self->is_lazy) {
278 unless ($self->has_value($instance)) {
279 if ($self->has_default) {
280 my $default = $self->default($instance);
281 $self->set_value($instance, $default);
284 $self->set_value($instance, undef);
289 if ($self->should_auto_deref) {
291 my $type_constraint = $self->type_constraint;
293 if ($type_constraint->is_a_type_of('ArrayRef')) {
294 my $rv = $self->SUPER::get_value($instance);
295 return unless defined $rv;
296 return wantarray ? @{ $rv } : $rv;
298 elsif ($type_constraint->is_a_type_of('HashRef')) {
299 my $rv = $self->SUPER::get_value($instance);
300 return unless defined $rv;
301 return wantarray ? %{ $rv } : $rv;
304 confess "Can not auto de-reference the type constraint '" . $type_constraint->name . "'";
310 return $self->SUPER::get_value($instance);
314 ## installing accessors
316 sub accessor_metaclass { 'Moose::Meta::Method::Accessor' }
318 sub install_accessors {
320 $self->SUPER::install_accessors(@_);
322 if ($self->has_handles) {
325 # Here we canonicalize the 'handles' option
326 # this will sort out any details and always
327 # return an hash of methods which we want
328 # to delagate to, see that method for details
329 my %handles = $self->_canonicalize_handles();
331 # find the name of the accessor for this attribute
332 my $accessor_name = $self->reader || $self->accessor;
333 (defined $accessor_name)
334 || confess "You cannot install delegation without a reader or accessor for the attribute";
336 # make sure we handle HASH accessors correctly
337 ($accessor_name) = keys %{$accessor_name}
338 if ref($accessor_name) eq 'HASH';
340 # install the delegation ...
341 my $associated_class = $self->associated_class;
342 foreach my $handle (keys %handles) {
343 my $method_to_call = $handles{$handle};
345 (!$associated_class->has_method($handle))
346 || confess "You cannot overwrite a locally defined method ($handle) with a delegation";
349 # handles is not allowed to delegate
350 # any of these methods, as they will
351 # override the ones in your class, which
352 # is almost certainly not what you want.
353 next if $handle =~ /^BUILD|DEMOLISH$/ || Moose::Object->can($handle);
355 if ((reftype($method_to_call) || '') eq 'CODE') {
356 $associated_class->add_method($handle => $method_to_call);
359 $associated_class->add_method($handle => sub {
361 # we should check for lack of
362 # a callable return value from
364 ((shift)->$accessor_name())->$method_to_call(@_);
373 # private methods to help delegation ...
375 sub _canonicalize_handles {
377 my $handles = $self->handles;
378 if (ref($handles) eq 'HASH') {
381 elsif (ref($handles) eq 'ARRAY') {
382 return map { $_ => $_ } @{$handles};
384 elsif (ref($handles) eq 'Regexp') {
385 ($self->has_type_constraint)
386 || confess "Cannot delegate methods based on a RegExpr without a type constraint (isa)";
387 return map { ($_ => $_) }
388 grep { /$handles/ } $self->_get_delegate_method_list;
390 elsif (ref($handles) eq 'CODE') {
391 return $handles->($self, $self->_find_delegate_metaclass);
394 confess "Unable to canonicalize the 'handles' option with $handles";
398 sub _find_delegate_metaclass {
400 if (my $class = $self->_isa_metadata) {
401 # if the class does have
402 # a meta method, use it
403 return $class->meta if $class->can('meta');
404 # otherwise we might be
405 # dealing with a non-Moose
406 # class, and need to make
408 return Moose::Meta::Class->initialize($class);
410 elsif (my $role = $self->_does_metadata) {
411 # our role will always have
416 confess "Cannot find delegate metaclass for attribute " . $self->name;
420 sub _get_delegate_method_list {
422 my $meta = $self->_find_delegate_metaclass;
423 if ($meta->isa('Class::MOP::Class')) {
424 return map { $_->{name} } # NOTE: !never! delegate &meta
425 grep { $_->{class} ne 'Moose::Object' && $_->{name} ne 'meta' }
426 $meta->compute_all_applicable_methods;
428 elsif ($meta->isa('Moose::Meta::Role')) {
429 return $meta->get_method_list;
432 confess "Unable to recognize the delegate metaclass '$meta'";
444 Moose::Meta::Attribute - The Moose attribute metaclass
448 This is a subclass of L<Class::MOP::Attribute> with Moose specific
451 For the most part, the only time you will ever encounter an
452 instance of this class is if you are doing some serious deep
453 introspection. To really understand this class, you need to refer
454 to the L<Class::MOP::Attribute> documentation.
458 =head2 Overridden methods
460 These methods override methods in L<Class::MOP::Attribute> and add
461 Moose specific features. You can safely assume though that they
462 will behave just as L<Class::MOP::Attribute> does.
468 =item B<initialize_instance_slot>
470 =item B<install_accessors>
472 =item B<accessor_metaclass>
480 =head2 Additional Moose features
482 Moose attributes support type-constraint checking, weak reference
483 creation and type coercion.
487 =item B<clone_and_inherit_options>
489 This is to support the C<has '+foo'> feature, it clones an attribute
490 from a superclass and allows a very specific set of changes to be made
493 =item B<has_type_constraint>
495 Returns true if this meta-attribute has a type constraint.
497 =item B<type_constraint>
499 A read-only accessor for this meta-attribute's type constraint. For
500 more information on what you can do with this, see the documentation
501 for L<Moose::Meta::TypeConstraint>.
505 Returns true if this meta-attribute performs delegation.
509 This returns the value which was passed into the handles option.
513 Returns true if this meta-attribute produces a weak reference.
517 Returns true if this meta-attribute is required to have a value.
521 Returns true if this meta-attribute should be initialized lazily.
523 NOTE: lazy attributes, B<must> have a C<default> field set.
525 =item B<should_coerce>
527 Returns true if this meta-attribute should perform type coercion.
529 =item B<should_auto_deref>
531 Returns true if this meta-attribute should perform automatic
534 NOTE: This can only be done for attributes whose type constraint is
535 either I<ArrayRef> or I<HashRef>.
539 Returns true if this meta-attribute has a trigger set.
543 This is a CODE reference which will be executed every time the
544 value of an attribute is assigned. The CODE ref will get two values,
545 the invocant and the new value. This can be used to handle I<basic>
546 bi-directional relations.
548 =item B<documentation>
550 This is a string which contains the documentation for this attribute.
551 It serves no direct purpose right now, but it might in the future
552 in some kind of automated documentation system perhaps.
554 =item B<has_documentation>
556 Returns true if this meta-attribute has any documentation.
562 All complex software has bugs lurking in it, and this module is no
563 exception. If you find a bug please either email me, or add the bug
568 Stevan Little E<lt>stevan@iinteractive.comE<gt>
570 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
572 =head1 COPYRIGHT AND LICENSE
574 Copyright 2006, 2007 by Infinity Interactive, Inc.
576 L<http://www.iinteractive.com>
578 This library is free software; you can redistribute it and/or modify
579 it under the same terms as Perl itself.