1 package Mouse::Meta::Attribute;
7 use Mouse::Util qw(:meta);
9 use Mouse::Meta::TypeConstraint;
10 use Mouse::Meta::Method::Accessor;
14 my($class, $name, $args) = @_;
17 # XXX: for backward compatibility (with method modifiers)
18 if($class->can('canonicalize_args') != \&canonicalize_args){
19 %{$args} = $class->canonicalize_args($name, %{$args});
22 # taken from Class::MOP::Attribute::new
25 or $class->throw_error('You must provide a name for the attribute');
27 if(!exists $args->{init_arg}){
28 $args->{init_arg} = $name;
31 # 'required' requires eigher 'init_arg', 'builder', or 'default'
32 my $can_be_required = defined( $args->{init_arg} );
34 if(exists $args->{builder}){
36 # Moose refuses a CODE ref builder, but Mouse doesn't for backward compatibility
37 # This feature will be changed in a future. (gfx)
38 $class->throw_error('builder must be a defined scalar value which is a method name')
39 #if ref $args->{builder} || !defined $args->{builder};
40 if !defined $args->{builder};
44 elsif(exists $args->{default}){
45 if(ref $args->{default} && ref($args->{default}) ne 'CODE'){
46 $class->throw_error("References are not allowed as default values, you must "
47 . "wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])");
52 if( $args->{required} && !$can_be_required ) {
53 $class->throw_error("You cannot have a required attribute ($name) without a default, builder, or an init_arg");
56 # taken from Mouse::Meta::Attribute->new and _process_args->
58 if(exists $args->{is}){
62 $args->{reader} ||= $name;
65 if(exists $args->{writer}){
66 $args->{reader} ||= $name;
69 $args->{accessor} ||= $name;
73 # do nothing, but don't complain (later) about missing methods
76 $is = 'undef' if !defined $is;
77 $class->throw_error("I do not understand this option (is => $is) on attribute ($name)");
82 if(exists $args->{isa}){
83 $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_isa_type_constraint($args->{isa});
85 elsif(exists $args->{does}){
87 # $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_does_type_constraint($args->{does});
89 $tc = $args->{type_constraint};
93 || $class->throw_error("You cannot have coercion without specifying a type constraint on attribute ($name)");
96 && $class->throw_error("You cannot have a weak reference to a coerced value on attribute ($name)");
99 if ($args->{lazy_build}) {
100 exists($args->{default})
101 && $class->throw_error("You can not use lazy_build and default for the same attribute ($name)");
104 $args->{builder} ||= "_build_${name}";
106 $args->{clearer} ||= "_clear${name}";
107 $args->{predicate} ||= "_has${name}";
110 $args->{clearer} ||= "clear_${name}";
111 $args->{predicate} ||= "has_${name}";
115 if ($args->{auto_deref}) {
117 || $class->throw_error("You cannot auto-dereference without specifying a type constraint on attribute ($name)");
119 ( $tc->is_a_type_of('ArrayRef') || $tc->is_a_type_of('HashRef') )
120 || $class->throw_error("You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute ($name)");
123 if (exists $args->{trigger}) {
124 ('CODE' eq ref $args->{trigger})
125 || $class->throw_error("Trigger must be a CODE ref on attribute ($name)");
129 (exists $args->{default} || defined $args->{builder})
130 || $class->throw_error("You cannot have lazy attribute ($name) without specifying a default value for it");
140 my %args = (@_ == 1) ? %{ $_[0] } : @_;
142 $class->_process_options($name, \%args);
146 my $self = bless \%args, $class;
149 if($class ne __PACKAGE__){
150 $class->meta->_initialize_object($self, \%args);
153 # XXX: there is no fast way to check attribute validity
157 # Carp::cluck("Found unknown argument(s) passed to '$name' attribute constructor in '$class': @bad");
165 sub name { $_[0]->{name} }
166 sub associated_class { $_[0]->{associated_class} }
168 sub accessor { $_[0]->{accessor} }
169 sub reader { $_[0]->{reader} }
170 sub writer { $_[0]->{writer} }
171 sub predicate { $_[0]->{predicate} }
172 sub clearer { $_[0]->{clearer} }
173 sub handles { $_[0]->{handles} }
175 sub _is_metadata { $_[0]->{is} }
176 sub is_required { $_[0]->{required} }
177 sub default { $_[0]->{default} }
178 sub is_lazy { $_[0]->{lazy} }
179 sub is_lazy_build { $_[0]->{lazy_build} }
180 sub is_weak_ref { $_[0]->{weak_ref} }
181 sub init_arg { $_[0]->{init_arg} }
182 sub type_constraint { $_[0]->{type_constraint} }
184 sub trigger { $_[0]->{trigger} }
185 sub builder { $_[0]->{builder} }
186 sub should_auto_deref { $_[0]->{auto_deref} }
187 sub should_coerce { $_[0]->{coerce} }
191 sub has_accessor { exists $_[0]->{accessor} }
192 sub has_reader { exists $_[0]->{reader} }
193 sub has_writer { exists $_[0]->{writer} }
194 sub has_predicate { exists $_[0]->{predicate} }
195 sub has_clearer { exists $_[0]->{clearer} }
196 sub has_handles { exists $_[0]->{handles} }
198 sub has_default { exists $_[0]->{default} }
199 sub has_type_constraint { exists $_[0]->{type_constraint} }
200 sub has_trigger { exists $_[0]->{trigger} }
201 sub has_builder { exists $_[0]->{builder} }
203 sub has_read_method { exists $_[0]->{reader} || exists $_[0]->{accessor} }
204 sub has_write_method { exists $_[0]->{writer} || exists $_[0]->{accessor} }
206 sub _create_args { # DEPRECATED
207 $_[0]->{_create_args} = $_[1] if @_ > 1;
208 $_[0]->{_create_args}
211 sub interpolate_class{
212 my($class, $args) = @_;
214 if(my $metaclass = delete $args->{metaclass}){
215 $class = Mouse::Util::resolve_metaclass_alias( Attribute => $metaclass );
219 if(my $traits_ref = delete $args->{traits}){
221 for (my $i = 0; $i < @{$traits_ref}; $i++) {
222 my $trait = Mouse::Util::resolve_metaclass_alias(Attribute => $traits_ref->[$i], trait => 1);
224 next if $class->does($trait);
226 push @traits, $trait;
229 push @traits, $traits_ref->[++$i]
230 if ref($traits_ref->[$i+1]);
234 $class = Mouse::Meta::Class->create_anon_class(
235 superclasses => [ $class ],
242 return( $class, @traits );
245 sub canonicalize_args{ # DEPRECATED
246 my ($self, $name, %args) = @_;
248 Carp::cluck("$self->canonicalize_args has been deprecated."
249 . "Use \$self->_process_options instead.")
256 my ($self, $class, $name, %args) = @_;
258 Carp::cluck("$self->create has been deprecated."
259 . "Use \$meta->add_attribute and \$attr->install_accessors instead.")
266 sub _coerce_and_verify {
267 my($self, $value, $instance) = @_;
269 my $type_constraint = $self->{type_constraint};
271 return $value if !$type_constraint;
273 if ($self->should_coerce && $type_constraint->has_coercion) {
274 $value = $type_constraint->coerce($value);
277 return $value if $type_constraint->check($value);
279 $self->verify_against_type_constraint($value);
284 sub verify_against_type_constraint {
285 my ($self, $value) = @_;
287 my $type_constraint = $self->{type_constraint};
288 return 1 if !$type_constraint;;
289 return 1 if $type_constraint->check($value);
291 $self->verify_type_constraint_error($self->name, $value, $type_constraint);
294 sub verify_type_constraint_error {
295 my($self, $name, $value, $type) = @_;
296 $self->throw_error("Attribute ($name) does not pass the type constraint because: " . $type->get_message($value));
299 sub coerce_constraint { # DEPRECATED
300 my $type = $_[0]->{type_constraint}
303 Carp::cluck("coerce_constraint() has been deprecated, which was an internal utility anyway");
305 return Mouse::Util::TypeConstraints->typecast_constraints($_[0]->associated_class->name, $type, $_[1]);
308 sub clone_and_inherit_options{
309 my($self, %args) = @_;
311 my($attribute_class, @traits) = ref($self)->interpolate_class(\%args);
313 $args{traits} = \@traits if @traits;
314 return $attribute_class->new($self->name, %{$self}, %args);
317 sub clone_parent { # DEPRECATED
321 my %args = ($self->get_parent_args($class, $name), @_);
323 Carp::cluck("$self->clone_parent has been deprecated."
324 . "Use \$meta->add_attribute and \$attr->install_accessors instead.")
327 $self->clone_and_inherited_args($class, $name, %args);
330 sub get_parent_args { # DEPRECATED
335 for my $super ($class->linearized_isa) {
336 my $super_attr = $super->can("meta") && $super->meta->get_attribute($name)
338 return %{ $super_attr->_create_args };
341 $self->throw_error("Could not find an attribute by the name of '$name' to inherit from");
345 sub get_read_method { # DEPRECATED
346 $_[0]->{reader} || $_[0]->{accessor}
348 sub get_write_method { # DEPRECATED
349 $_[0]->{writer} || $_[0]->{accessor}
352 sub get_read_method_ref{
355 $self->{_read_method_ref} ||= do{
356 my $metaclass = $self->associated_class
357 or $self->throw_error('No asocciated class for ' . $self->name);
359 my $reader = $self->{reader} || $self->{accessor};
361 $metaclass->name->can($reader);
364 $self->accessor_metaclass->_generate_reader($self, $metaclass);
369 sub get_write_method_ref{
372 $self->{_write_method_ref} ||= do{
373 my $metaclass = $self->associated_class
374 or $self->throw_error('No asocciated class for ' . $self->name);
376 my $reader = $self->{writer} || $self->{accessor};
378 $metaclass->name->can($reader);
381 $self->accessor_metaclass->_generate_writer($self, $metaclass);
386 sub _canonicalize_handles {
387 my($self, $handles) = @_;
389 if (ref($handles) eq 'HASH') {
392 elsif (ref($handles) eq 'ARRAY') {
393 return map { $_ => $_ } @$handles;
396 $self->throw_error("Unable to canonicalize the 'handles' option with $handles");
401 sub associate_method{
402 my ($attribute, $method) = @_;
403 $attribute->{associated_methods}++;
407 sub accessor_metaclass(){ 'Mouse::Meta::Method::Accessor' }
409 sub install_accessors{
412 my $metaclass = $attribute->{associated_class};
413 my $accessor_class = $attribute->accessor_metaclass;
415 foreach my $type(qw(accessor reader writer predicate clearer)){
416 if(exists $attribute->{$type}){
417 my $generator = '_generate_' . $type;
418 my $code = $accessor_class->$generator($attribute, $metaclass);
419 $metaclass->add_method($attribute->{$type} => $code);
420 $attribute->associate_method($code);
425 if(exists $attribute->{handles}){
426 my %handles = $attribute->_canonicalize_handles($attribute->{handles});
427 my $reader = $attribute->get_read_method_ref;
429 while(my($handle_name, $method_to_call) = each %handles){
430 my $code = $accessor_class->_generate_delegation($attribute, $metaclass,
431 $reader, $handle_name, $method_to_call);
433 $metaclass->add_method($handle_name => $code);
434 $attribute->associate_method($code);
439 if($attribute->can('create') != \&create){
440 # backword compatibility
441 $attribute->create($metaclass, $attribute->name, %{$attribute});
450 my $metaclass = (ref $self && $self->associated_class) || 'Mouse::Meta::Class';
451 $metaclass->throw_error(@_, depth => 1);
460 Mouse::Meta::Attribute - The Mouse attribute metaclass
464 =head2 C<< new(%options) -> Mouse::Meta::Attribute >>
466 Instantiates a new Mouse::Meta::Attribute. Does nothing else.
468 It adds the following options to the constructor:
472 =item C<< is => 'ro', 'rw', 'bare' >>
474 This provides a shorthand for specifying the C<reader>, C<writer>, or
475 C<accessor> names. If the attribute is read-only ('ro') then it will
476 have a C<reader> method with the same attribute as the name.
478 If it is read-write ('rw') then it will have an C<accessor> method
479 with the same name. If you provide an explicit C<writer> for a
480 read-write attribute, then you will have a C<reader> with the same
481 name as the attribute, and a C<writer> with the name you provided.
483 Use 'bare' when you are deliberately not installing any methods
484 (accessor, reader, etc.) associated with this attribute; otherwise,
485 Moose will issue a deprecation warning when this attribute is added to a
488 =item C<< isa => Type >>
490 This option accepts a type. The type can be a string, which should be
491 a type name. If the type name is unknown, it is assumed to be a class
494 This option can also accept a L<Moose::Meta::TypeConstraint> object.
496 If you I<also> provide a C<does> option, then your C<isa> option must
497 be a class name, and that class must do the role specified with
500 =item C<< does => Role >>
502 This is short-hand for saying that the attribute's type must be an
503 object which does the named role.
505 B<This option is not yet supported.>
507 =item C<< coerce => Bool >>
509 This option is only valid for objects with a type constraint
510 (C<isa>). If this is true, then coercions will be applied whenever
511 this attribute is set.
513 You can make both this and the C<weak_ref> option true.
515 =item C<< trigger => CodeRef >>
517 This option accepts a subroutine reference, which will be called after
518 the attribute is set.
520 =item C<< required => Bool >>
522 An attribute which is required must be provided to the constructor. An
523 attribute which is required can also have a C<default> or C<builder>,
524 which will satisfy its required-ness.
526 A required attribute must have a C<default>, C<builder> or a
527 non-C<undef> C<init_arg>
529 =item C<< lazy => Bool >>
531 A lazy attribute must have a C<default> or C<builder>. When an
532 attribute is lazy, the default value will not be calculated until the
535 =item C<< weak_ref => Bool >>
537 If this is true, the attribute's value will be stored as a weak
540 =item C<< auto_deref => Bool >>
542 If this is true, then the reader will dereference the value when it is
543 called. The attribute must have a type constraint which defines the
544 attribute as an array or hash reference.
546 =item C<< lazy_build => Bool >>
548 Setting this to true makes the attribute lazy and provides a number of
556 is equivalent to this:
561 builder => '_build_size',
562 clearer => 'clear_size',
563 predicate => 'has_size',
568 =head2 C<< associate_method(Method) >>
570 Associates a method with the attribute. Typically, this is called internally
571 when an attribute generates its accessors.
573 Currently the argument I<Method> is ignored in Mouse.
575 =head2 C<< verify_against_type_constraint(Item) -> TRUE | ERROR >>
577 Checks that the given value passes this attribute's type constraint. Returns C<true>
578 on success, otherwise C<confess>es.
580 =head2 C<< clone_and_inherit_options(options) -> Mouse::Meta::Attribute >>
582 Creates a new attribute in the owner class, inheriting options from parent classes.
583 Accessors and helper methods are installed. Some error checking is done.
585 =head2 C<< get_read_method_ref >>
\r
587 =head2 C<< get_write_method_ref >>
\r
589 Returns the subroutine reference of a method suitable for reading or
\r
590 writing the attribute's value in the associated class. These methods
\r
591 always return a subroutine reference, regardless of whether or not the
\r
592 attribute is read- or write-only.
596 L<Moose::Meta::Attribute>
598 L<Class::MOP::Attribute>