9ffac5257b7bfaf07f1e92ec6cd6e4cf870f6b26
[gitmo/Mouse.git] / lib / Mouse / Meta / Attribute.pm
1 package Mouse::Meta::Attribute;
2 use strict;
3 use warnings;
4
5 use Carp ();
6
7 use Mouse::Util qw(:meta);
8
9 use Mouse::Meta::TypeConstraint;
10 use Mouse::Meta::Method::Accessor;
11
12
13 sub _process_options{
14     my($class, $name, $args) = @_;
15
16
17     # XXX: for backward compatibility (with method modifiers)
18     if($class->can('canonicalize_args') != \&canonicalize_args){
19         %{$args} = $class->canonicalize_args($name, %{$args});
20     }
21
22     # taken from Class::MOP::Attribute::new
23
24     defined($name)
25         or $class->throw_error('You must provide a name for the attribute');
26
27     if(!exists $args->{init_arg}){
28         $args->{init_arg} = $name;
29     }
30
31     # 'required' requires eigher 'init_arg', 'builder', or 'default'
32     my $can_be_required = defined( $args->{init_arg} );
33
34     if(exists $args->{builder}){
35         # XXX:
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};
41
42         $can_be_required++;
43     }
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 [])");
48         }
49         $can_be_required++;
50     }
51
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");
54     }
55
56     # taken from Mouse::Meta::Attribute->new and _process_args->
57
58     if(exists $args->{is}){
59         my $is = $args->{is};
60
61         if($is eq 'ro'){
62             $args->{reader} ||= $name;
63         }
64         elsif($is eq 'rw'){
65             if(exists $args->{writer}){
66                 $args->{reader} ||= $name;
67              }
68              else{
69                 $args->{accessor} ||= $name;
70              }
71         }
72         elsif($is eq 'bare'){
73             # do nothing, but don't complain (later) about missing methods
74         }
75         else{
76             $is = 'undef' if !defined $is;
77             $class->throw_error("I do not understand this option (is => $is) on attribute ($name)");
78         }
79     }
80
81     my $tc;
82     if(exists $args->{isa}){
83         $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_isa_type_constraint($args->{isa});
84     }
85     elsif(exists $args->{does}){
86         # TODO
87         # $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_does_type_constraint($args->{does});
88     }
89     $tc = $args->{type_constraint};
90
91     if($args->{coerce}){
92         defined($tc)
93             || $class->throw_error("You cannot have coercion without specifying a type constraint on attribute ($name)");
94
95         $args->{weak_ref}
96             && $class->throw_error("You cannot have a weak reference to a coerced value on attribute ($name)");
97     }
98
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)");
102
103         $args->{lazy}      = 1;
104         $args->{builder} ||= "_build_${name}";
105         if ($name =~ /^_/) {
106             $args->{clearer}   ||= "_clear${name}";
107             $args->{predicate} ||= "_has${name}";
108         }
109         else {
110             $args->{clearer}   ||= "clear_${name}";
111             $args->{predicate} ||= "has_${name}";
112         }
113     }
114
115     if ($args->{auto_deref}) {
116         defined($tc)
117             || $class->throw_error("You cannot auto-dereference without specifying a type constraint on attribute ($name)");
118
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)");
121     }
122
123     if (exists $args->{trigger}) {
124         ('CODE' eq ref $args->{trigger})
125             || $class->throw_error("Trigger must be a CODE ref on attribute ($name)");
126     }
127
128     if ($args->{lazy}) {
129         (exists $args->{default} || defined $args->{builder})
130             || $class->throw_error("You cannot have lazy attribute ($name) without specifying a default value for it");
131     }
132
133     return;
134 }
135
136 sub new {
137     my $class = shift;
138     my $name  = shift;
139
140     my %args  = (@_ == 1) ? %{ $_[0] } : @_;
141
142     $class->_process_options($name, \%args);
143
144     $args{name} = $name;
145
146     my $self = bless \%args, $class;
147
148     # extra attributes
149     if($class ne __PACKAGE__){
150         $class->meta->_initialize_object($self, \%args);
151     }
152
153 # XXX: there is no fast way to check attribute validity
154 #    my @bad = ...;
155 #    if(@bad){
156 #        @bad = sort @bad;
157 #        Carp::cluck("Found unknown argument(s) passed to '$name' attribute constructor in '$class': @bad");
158 #    }
159
160     return $self;
161 }
162
163 # readers
164
165 sub name                 { $_[0]->{name}                   }
166 sub associated_class     { $_[0]->{associated_class}       }
167
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}                }
174
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}        }
183
184 sub trigger              { $_[0]->{trigger}                }
185 sub builder              { $_[0]->{builder}                }
186 sub should_auto_deref    { $_[0]->{auto_deref}             }
187 sub should_coerce        { $_[0]->{coerce}                 }
188
189 # predicates
190
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}         }
197
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}         }
202
203 sub has_read_method      { exists $_[0]->{reader} || exists $_[0]->{accessor} }
204 sub has_write_method     { exists $_[0]->{writer} || exists $_[0]->{accessor} }
205
206 sub _create_args { # DEPRECATED
207     $_[0]->{_create_args} = $_[1] if @_ > 1;
208     $_[0]->{_create_args}
209 }
210
211 sub interpolate_class{
212     my($class, $args) = @_;
213
214     if(my $metaclass = delete $args->{metaclass}){
215         $class = Mouse::Util::resolve_metaclass_alias( Attribute => $metaclass );
216     }
217
218     my @traits;
219     if(my $traits_ref = delete $args->{traits}){
220
221         for (my $i = 0; $i < @{$traits_ref}; $i++) {
222             my $trait = Mouse::Util::resolve_metaclass_alias(Attribute => $traits_ref->[$i], trait => 1);
223
224             next if $class->does($trait);
225
226             push @traits, $trait;
227
228             # are there options?
229             push @traits, $traits_ref->[++$i]
230                 if ref($traits_ref->[$i+1]);
231         }
232
233         if (@traits) {
234             $class = Mouse::Meta::Class->create_anon_class(
235                 superclasses => [ $class ],
236                 roles        => \@traits,
237                 cache        => 1,
238             )->name;
239         }
240     }
241
242     return( $class, @traits );
243 }
244
245 sub canonicalize_args{ # DEPRECATED
246     my ($self, $name, %args) = @_;
247
248     Carp::cluck("$self->canonicalize_args has been deprecated."
249         . "Use \$self->_process_options instead.")
250             if _MOUSE_VERBOSE;
251
252     return %args;
253 }
254
255 sub create {
256     my ($self, $class, $name, %args) = @_;
257
258     Carp::cluck("$self->create has been deprecated."
259         . "Use \$meta->add_attribute and \$attr->install_accessors instead.")
260             if _MOUSE_VERBOSE;
261
262     # noop
263     return $self;
264 }
265
266 sub _coerce_and_verify {
267     my($self, $value, $instance) = @_;
268
269     my $type_constraint = $self->{type_constraint};
270
271     return $value if !$type_constraint;
272
273     if ($self->should_coerce && $type_constraint->has_coercion) {
274         $value = $type_constraint->coerce($value);
275     }
276
277     return $value if $type_constraint->check($value);
278
279     $self->verify_against_type_constraint($value);
280
281     return $value;
282 }
283
284 sub verify_against_type_constraint {
285     my ($self, $value) = @_;
286
287     my $type_constraint = $self->{type_constraint};
288     return 1 if !$type_constraint;;
289     return 1 if $type_constraint->check($value);
290
291     $self->verify_type_constraint_error($self->name, $value, $type_constraint);
292 }
293
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));
297 }
298
299 sub coerce_constraint { # DEPRECATED
300     my $type = $_[0]->{type_constraint}
301         or return $_[1];
302
303     Carp::cluck("coerce_constraint() has been deprecated, which was an internal utility anyway");
304
305     return Mouse::Util::TypeConstraints->typecast_constraints($_[0]->associated_class->name, $type, $_[1]);
306 }
307
308 sub clone_and_inherit_options{
309     my($self, %args) = @_;
310
311     my($attribute_class, @traits) = ref($self)->interpolate_class(\%args);
312
313     $args{traits} = \@traits if @traits;
314     return $attribute_class->new($self->name, %{$self}, %args);
315 }
316
317 sub clone_parent { # DEPRECATED
318     my $self  = shift;
319     my $class = shift;
320     my $name  = shift;
321     my %args  = ($self->get_parent_args($class, $name), @_);
322
323     Carp::cluck("$self->clone_parent has been deprecated."
324         . "Use \$meta->add_attribute and \$attr->install_accessors instead.")
325         if _MOUSE_VERBOSE;
326
327     $self->clone_and_inherited_args($class, $name, %args);
328 }
329
330 sub get_parent_args { # DEPRECATED
331     my $self  = shift;
332     my $class = shift;
333     my $name  = shift;
334
335     for my $super ($class->linearized_isa) {
336         my $super_attr = $super->can("meta") && $super->meta->get_attribute($name)
337             or next;
338         return %{ $super_attr->_create_args };
339     }
340
341     $self->throw_error("Could not find an attribute by the name of '$name' to inherit from");
342 }
343
344
345 sub get_read_method { # DEPRECATED
346     $_[0]->{reader} || $_[0]->{accessor}
347 }
348 sub get_write_method { # DEPRECATED
349     $_[0]->{writer} || $_[0]->{accessor}
350 }
351
352 sub get_read_method_ref{
353     my($self) = @_;
354
355     $self->{_read_method_ref} ||= do{
356         my $metaclass = $self->associated_class
357             or $self->throw_error('No asocciated class for ' . $self->name);
358
359         my $reader = $self->{reader} || $self->{accessor};
360         if($reader){
361             $metaclass->name->can($reader);
362         }
363         else{
364             $self->accessor_metaclass->_generate_reader($self, $metaclass);
365         }
366     };
367 }
368
369 sub get_write_method_ref{
370     my($self) = @_;
371
372     $self->{_write_method_ref} ||= do{
373         my $metaclass = $self->associated_class
374             or $self->throw_error('No asocciated class for ' . $self->name);
375
376         my $reader = $self->{writer} || $self->{accessor};
377         if($reader){
378             $metaclass->name->can($reader);
379         }
380         else{
381             $self->accessor_metaclass->_generate_writer($self, $metaclass);
382         }
383     };
384 }
385
386 sub _canonicalize_handles {
387     my($self, $handles) = @_;
388
389     if (ref($handles) eq 'HASH') {
390         return %$handles;
391     }
392     elsif (ref($handles) eq 'ARRAY') {
393         return map { $_ => $_ } @$handles;
394     }
395     else {
396         $self->throw_error("Unable to canonicalize the 'handles' option with $handles");
397     }
398 }
399
400
401 sub associate_method{
402     my ($attribute, $method) = @_;
403     $attribute->{associated_methods}++;
404     return;
405 }
406
407 sub accessor_metaclass(){ 'Mouse::Meta::Method::Accessor' }
408
409 sub install_accessors{
410     my($attribute) = @_;
411
412     my $metaclass      = $attribute->{associated_class};
413     my $accessor_class = $attribute->accessor_metaclass;
414
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);
421         }
422     }
423
424     # install delegation
425     if(exists $attribute->{handles}){
426         my %handles = $attribute->_canonicalize_handles($attribute->{handles});
427         my $reader  = $attribute->get_read_method_ref;
428
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);
432
433             $metaclass->add_method($handle_name => $code);
434             $attribute->associate_method($code);
435         }
436     }
437
438
439     if($attribute->can('create') != \&create){
440         # backword compatibility
441         $attribute->create($metaclass, $attribute->name, %{$attribute});
442     }
443
444     return;
445 }
446
447 sub throw_error{
448     my $self = shift;
449
450     my $metaclass = (ref $self && $self->associated_class) || 'Mouse::Meta::Class';
451     $metaclass->throw_error(@_, depth => 1);
452 }
453
454 1;
455
456 __END__
457
458 =head1 NAME
459
460 Mouse::Meta::Attribute - The Mouse attribute metaclass
461
462 =head1 METHODS
463
464 =head2 C<< new(%options) -> Mouse::Meta::Attribute >>
465
466 Instantiates a new Mouse::Meta::Attribute. Does nothing else.
467
468 It adds the following options to the constructor:
469
470 =over 4
471
472 =item C<< is => 'ro', 'rw', 'bare' >>
473
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.
477
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.
482
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
486 metaclass.
487
488 =item C<< isa => Type >>
489
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
492 name.
493
494 This option can also accept a L<Moose::Meta::TypeConstraint> object.
495
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
498 C<does>.
499
500 =item C<< does => Role >>
501
502 This is short-hand for saying that the attribute's type must be an
503 object which does the named role.
504
505 B<This option is not yet supported.>
506
507 =item C<< coerce => Bool >>
508
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.
512
513 You can make both this and the C<weak_ref> option true.
514
515 =item C<< trigger => CodeRef >>
516
517 This option accepts a subroutine reference, which will be called after
518 the attribute is set.
519
520 =item C<< required => Bool >>
521
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.
525
526 A required attribute must have a C<default>, C<builder> or a
527 non-C<undef> C<init_arg>
528
529 =item C<< lazy => Bool >>
530
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
533 attribute is read.
534
535 =item C<< weak_ref => Bool >>
536
537 If this is true, the attribute's value will be stored as a weak
538 reference.
539
540 =item C<< auto_deref => Bool >>
541
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.
545
546 =item C<< lazy_build => Bool >>
547
548 Setting this to true makes the attribute lazy and provides a number of
549 default methods.
550
551   has 'size' => (
552       is         => 'ro',
553       lazy_build => 1,
554   );
555
556 is equivalent to this:
557
558   has 'size' => (
559       is        => 'ro',
560       lazy      => 1,
561       builder   => '_build_size',
562       clearer   => 'clear_size',
563       predicate => 'has_size',
564   );
565
566 =back
567
568 =head2 C<< associate_method(Method) >>
569
570 Associates a method with the attribute. Typically, this is called internally
571 when an attribute generates its accessors.
572
573 Currently the argument I<Method> is ignored in Mouse.
574
575 =head2 C<< verify_against_type_constraint(Item) -> TRUE | ERROR >>
576
577 Checks that the given value passes this attribute's type constraint. Returns C<true>
578 on success, otherwise C<confess>es.
579
580 =head2 C<< clone_and_inherit_options(options) -> Mouse::Meta::Attribute >>
581
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.
584
585 =head2 C<< get_read_method_ref >>\r
586 \r
587 =head2 C<< get_write_method_ref >>\r
588 \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.
593
594 =head1 SEE ALSO
595
596 L<Moose::Meta::Attribute>
597
598 L<Class::MOP::Attribute>
599
600 =cut
601