Add set_value/get_value/has_value/clear_value to Attribute
[gitmo/Mouse.git] / lib / Mouse / Meta / Attribute.pm
1 package Mouse::Meta::Attribute;
2 use Mouse::Util qw(:meta); # enables strict and warnings
3
4 use Carp ();
5
6 use Mouse::Meta::TypeConstraint;
7
8 #use Mouse::Meta::Method::Accessor;
9 use Mouse::Meta::Method::Delegation;
10
11 sub _process_options{
12     my($class, $name, $args) = @_;
13
14     # XXX: for backward compatibility (with method modifiers)
15     if($class->can('canonicalize_args') != \&canonicalize_args){
16         %{$args} = $class->canonicalize_args($name, %{$args});
17     }
18
19     # taken from Class::MOP::Attribute::new
20
21     defined($name)
22         or $class->throw_error('You must provide a name for the attribute');
23
24     if(!exists $args->{init_arg}){
25         $args->{init_arg} = $name;
26     }
27
28     # 'required' requires eigher 'init_arg', 'builder', or 'default'
29     my $can_be_required = defined( $args->{init_arg} );
30
31     if(exists $args->{builder}){
32         # XXX:
33         # Moose refuses a CODE ref builder, but Mouse doesn't for backward compatibility
34         # This feature will be changed in a future. (gfx)
35         $class->throw_error('builder must be a defined scalar value which is a method name')
36             #if ref $args->{builder} || !defined $args->{builder};
37             if !defined $args->{builder};
38
39         $can_be_required++;
40     }
41     elsif(exists $args->{default}){
42         if(ref $args->{default} && ref($args->{default}) ne 'CODE'){
43             $class->throw_error("References are not allowed as default values, you must "
44                               . "wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])");
45         }
46         $can_be_required++;
47     }
48
49     if( $args->{required} && !$can_be_required ) {
50         $class->throw_error("You cannot have a required attribute ($name) without a default, builder, or an init_arg");
51     }
52
53     # taken from Mouse::Meta::Attribute->new and _process_args->
54
55     if(exists $args->{is}){
56         my $is = $args->{is};
57
58         if($is eq 'ro'){
59             $args->{reader} ||= $name;
60         }
61         elsif($is eq 'rw'){
62             if(exists $args->{writer}){
63                 $args->{reader} ||= $name;
64              }
65              else{
66                 $args->{accessor} ||= $name;
67              }
68         }
69         elsif($is eq 'bare'){
70             # do nothing, but don't complain (later) about missing methods
71         }
72         else{
73             $is = 'undef' if !defined $is;
74             $class->throw_error("I do not understand this option (is => $is) on attribute ($name)");
75         }
76     }
77
78     my $tc;
79     if(exists $args->{isa}){
80         $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_isa_type_constraint($args->{isa});
81     }
82     elsif(exists $args->{does}){
83         $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_does_type_constraint($args->{does});
84     }
85     $tc = $args->{type_constraint};
86
87     if($args->{coerce}){
88         defined($tc)
89             || $class->throw_error("You cannot have coercion without specifying a type constraint on attribute ($name)");
90
91         $args->{weak_ref}
92             && $class->throw_error("You cannot have a weak reference to a coerced value on attribute ($name)");
93     }
94
95     if ($args->{lazy_build}) {
96         exists($args->{default})
97             && $class->throw_error("You can not use lazy_build and default for the same attribute ($name)");
98
99         $args->{lazy}      = 1;
100         $args->{builder} ||= "_build_${name}";
101         if ($name =~ /^_/) {
102             $args->{clearer}   ||= "_clear${name}";
103             $args->{predicate} ||= "_has${name}";
104         }
105         else {
106             $args->{clearer}   ||= "clear_${name}";
107             $args->{predicate} ||= "has_${name}";
108         }
109     }
110
111     if ($args->{auto_deref}) {
112         defined($tc)
113             || $class->throw_error("You cannot auto-dereference without specifying a type constraint on attribute ($name)");
114
115         ( $tc->is_a_type_of('ArrayRef') || $tc->is_a_type_of('HashRef') )
116             || $class->throw_error("You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute ($name)");
117     }
118
119     if (exists $args->{trigger}) {
120         ('CODE' eq ref $args->{trigger})
121             || $class->throw_error("Trigger must be a CODE ref on attribute ($name)");
122     }
123
124     if ($args->{lazy}) {
125         (exists $args->{default} || defined $args->{builder})
126             || $class->throw_error("You cannot have lazy attribute ($name) without specifying a default value for it");
127     }
128
129     return;
130 }
131
132 sub new {
133     my $class = shift;
134     my $name  = shift;
135
136     my %args  = (@_ == 1) ? %{ $_[0] } : @_;
137
138     $class->_process_options($name, \%args);
139
140     $args{name} = $name;
141
142     my $self = bless \%args, $class;
143
144     # extra attributes
145     if($class ne __PACKAGE__){
146         $class->meta->_initialize_object($self, \%args);
147     }
148
149 # XXX: there is no fast way to check attribute validity
150 #    my @bad = ...;
151 #    if(@bad){
152 #        @bad = sort @bad;
153 #        Carp::cluck("Found unknown argument(s) passed to '$name' attribute constructor in '$class': @bad");
154 #    }
155
156     return $self;
157 }
158
159 sub has_read_method      { $_[0]->has_reader || $_[0]->has_accessor }
160 sub has_write_method     { $_[0]->has_writer || $_[0]->has_accessor }
161
162 sub _create_args { # DEPRECATED
163     $_[0]->{_create_args} = $_[1] if @_ > 1;
164     $_[0]->{_create_args}
165 }
166
167 sub interpolate_class{
168     my($class, $args) = @_;
169
170     if(my $metaclass = delete $args->{metaclass}){
171         $class = Mouse::Util::resolve_metaclass_alias( Attribute => $metaclass );
172     }
173
174     my @traits;
175     if(my $traits_ref = delete $args->{traits}){
176
177         for (my $i = 0; $i < @{$traits_ref}; $i++) {
178             my $trait = Mouse::Util::resolve_metaclass_alias(Attribute => $traits_ref->[$i], trait => 1);
179
180             next if $class->does($trait);
181
182             push @traits, $trait;
183
184             # are there options?
185             push @traits, $traits_ref->[++$i]
186                 if ref($traits_ref->[$i+1]);
187         }
188
189         if (@traits) {
190             $class = Mouse::Meta::Class->create_anon_class(
191                 superclasses => [ $class ],
192                 roles        => \@traits,
193                 cache        => 1,
194             )->name;
195         }
196     }
197
198     return( $class, @traits );
199 }
200
201 sub canonicalize_args{ # DEPRECATED
202     my ($self, $name, %args) = @_;
203
204     Carp::cluck("$self->canonicalize_args has been deprecated."
205         . "Use \$self->_process_options instead.")
206             if Mouse::Util::_MOUSE_VERBOSE;
207
208     return %args;
209 }
210
211 sub create { # DEPRECATED
212     my ($self, $class, $name, %args) = @_;
213
214     Carp::cluck("$self->create has been deprecated."
215         . "Use \$meta->add_attribute and \$attr->install_accessors instead.")
216             if Mouse::Util::_MOUSE_VERBOSE;
217
218     # noop
219     return $self;
220 }
221
222 sub _coerce_and_verify {
223     my($self, $value, $instance) = @_;
224
225     my $type_constraint = $self->{type_constraint};
226     return $value if !defined $type_constraint;
227
228     if ($self->should_coerce && $type_constraint->has_coercion) {
229         $value = $type_constraint->coerce($value);
230     }
231
232     $self->verify_against_type_constraint($value);
233
234     return $value;
235 }
236
237 sub verify_against_type_constraint {
238     my ($self, $value) = @_;
239
240     my $type_constraint = $self->{type_constraint};
241     return 1 if !$type_constraint;
242     return 1 if $type_constraint->check($value);
243
244     $self->verify_type_constraint_error($self->name, $value, $type_constraint);
245 }
246
247 sub verify_type_constraint_error {
248     my($self, $name, $value, $type) = @_;
249     $self->throw_error("Attribute ($name) does not pass the type constraint because: "
250         . $type->get_message($value));
251 }
252
253 sub coerce_constraint { # DEPRECATED
254     my $type = $_[0]->{type_constraint}
255         or return $_[1];
256
257     Carp::cluck("coerce_constraint() has been deprecated, which was an internal utility anyway");
258
259     return Mouse::Util::TypeConstraints->typecast_constraints($_[0]->associated_class->name, $type, $_[1]);
260 }
261
262 sub clone_and_inherit_options{
263     my($self, %args) = @_;
264
265     my($attribute_class, @traits) = ref($self)->interpolate_class(\%args);
266
267     $args{traits} = \@traits if @traits;
268     # do not inherit the 'handles' attribute
269     foreach my $name(keys %{$self}){
270         if(!exists $args{$name} && $name ne 'handles'){
271             $args{$name} = $self->{$name};
272         }
273     }
274     return $attribute_class->new($self->name, %args);
275 }
276
277 sub clone_parent { # DEPRECATED
278     my $self  = shift;
279     my $class = shift;
280     my $name  = shift;
281     my %args  = ($self->get_parent_args($class, $name), @_);
282
283     Carp::cluck("$self->clone_parent has been deprecated."
284         . "Use \$meta->add_attribute and \$attr->install_accessors instead.")
285         if Mouse::Util::_MOUSE_VERBOSE;
286
287     $self->clone_and_inherited_args($class, $name, %args);
288 }
289
290 sub get_parent_args { # DEPRECATED
291     my $self  = shift;
292     my $class = shift;
293     my $name  = shift;
294
295     for my $super ($class->linearized_isa) {
296         my $super_attr = $super->can("meta") && $super->meta->get_attribute($name)
297             or next;
298         return %{ $super_attr->_create_args };
299     }
300
301     $self->throw_error("Could not find an attribute by the name of '$name' to inherit from");
302 }
303
304
305 sub get_read_method {
306     return $_[0]->reader || $_[0]->accessor
307 }
308 sub get_write_method {
309     return $_[0]->writer || $_[0]->accessor
310 }
311
312 sub _get_accessor_method_ref {
313     my($self, $type, $generator) = @_;
314
315     my $metaclass = $self->associated_class
316         || $self->throw_error('No asocciated class for ' . $self->name);
317
318     my $accessor = $self->$type();
319     if($accessor){
320         return $metaclass->get_method_body($accessor);
321     }
322     else{
323         return $self->accessor_metaclass->$generator($self, $metaclass);
324     }
325 }
326
327 sub get_read_method_ref{
328     my($self) = @_;
329
330     return $self->{_read_method_ref} ||= $self->_get_accessor_method_ref('get_read_method', '_generate_reader');
331 }
332
333 sub get_write_method_ref{
334     my($self) = @_;
335
336     return $self->{_write_method_ref} ||= $self->_get_accessor_method_ref('get_write_method', '_generate_writer');
337 }
338
339 sub set_value {
340     my($self, $object, $value) = @_;
341     return $self->get_write_method_ref()->($object, $value);
342 }
343
344 sub get_value {
345     my($self, $object) = @_;
346     return $self->get_read_method_ref()->($object);
347 }
348
349 sub has_value {
350     my($self, $object) = @_;
351     my $predicate_ref = $self->{_predicate_ref}
352         ||= $self->_get_accessor_method_ref('predicate', '_generate_predicate');
353
354     return $predicate_ref->($object);
355 }
356
357 sub clear_value {
358     my($self, $object) = @_;
359     my $predicate_ref = $self->{_crealer_ref}
360         ||= $self->_get_accessor_method_ref('clearer', '_generate_clearer');
361
362     return $predicate_ref->($object);
363 }
364
365
366 sub _canonicalize_handles {
367     my($self, $handles) = @_;
368
369     if (ref($handles) eq 'HASH') {
370         return %$handles;
371     }
372     elsif (ref($handles) eq 'ARRAY') {
373         return map { $_ => $_ } @$handles;
374     }
375     elsif (ref($handles) eq 'Regexp') {
376         my $class_or_role = ($self->{isa} || $self->{does})
377             || $self->throw_error("Cannot delegate methods based on a Regexp without a type constraint (isa)");
378
379         my $meta = Mouse::Meta::Class->initialize("$class_or_role"); # "" for stringify
380         return map  { $_ => $_ }
381                grep { !Mouse::Object->can($_) && $_ =~ $handles }
382                    Mouse::Util::is_a_metarole($meta)
383                         ? $meta->get_method_list
384                         : $meta->get_all_method_names;
385     }
386     else {
387         $self->throw_error("Unable to canonicalize the 'handles' option with $handles");
388     }
389 }
390
391 sub associate_method{
392     my ($attribute, $method_name) = @_;
393     $attribute->{associated_methods}++;
394     return;
395 }
396
397 sub delegation_metaclass() { 'Mouse::Meta::Method::Delegation' }
398
399 sub install_accessors{
400     my($attribute) = @_;
401
402     my $metaclass      = $attribute->associated_class;
403     my $accessor_class = $attribute->accessor_metaclass;
404
405     foreach my $type(qw(accessor reader writer predicate clearer)){
406         if(exists $attribute->{$type}){
407             my $generator = '_generate_' . $type;
408             my $code      = $accessor_class->$generator($attribute, $metaclass);
409             $metaclass->add_method($attribute->{$type} => $code);
410             $attribute->associate_method($attribute->{$type});
411         }
412     }
413
414     # install delegation
415     if(exists $attribute->{handles}){
416         my $delegation_class = $attribute->delegation_metaclass;
417         my %handles = $attribute->_canonicalize_handles($attribute->{handles});
418         my $reader  = $attribute->get_read_method_ref;
419
420         while(my($handle_name, $method_to_call) = each %handles){
421             my $code = $delegation_class->_generate_delegation($attribute, $metaclass,
422                 $reader, $handle_name, $method_to_call);
423
424             $metaclass->add_method($handle_name => $code);
425             $attribute->associate_method($handle_name);
426         }
427     }
428
429     if($attribute->can('create') != \&create){
430         # backword compatibility
431         $attribute->create($metaclass, $attribute->name, %{$attribute});
432     }
433
434     return;
435 }
436
437 sub throw_error{
438     my $self = shift;
439
440     my $metaclass = (ref $self && $self->associated_class) || 'Mouse::Meta::Class';
441     $metaclass->throw_error(@_, depth => 1);
442 }
443
444 1;
445 __END__
446
447 =head1 NAME
448
449 Mouse::Meta::Attribute - The Mouse attribute metaclass
450
451 =head1 VERSION
452
453 This document describes Mouse version 0.44
454
455 =head1 METHODS
456
457 =head2 C<< new(%options) -> Mouse::Meta::Attribute >>
458
459 Instantiates a new Mouse::Meta::Attribute. Does nothing else.
460
461 It adds the following options to the constructor:
462
463 =over 4
464
465 =item C<< is => 'ro', 'rw', 'bare' >>
466
467 This provides a shorthand for specifying the C<reader>, C<writer>, or
468 C<accessor> names. If the attribute is read-only ('ro') then it will
469 have a C<reader> method with the same attribute as the name.
470
471 If it is read-write ('rw') then it will have an C<accessor> method
472 with the same name. If you provide an explicit C<writer> for a
473 read-write attribute, then you will have a C<reader> with the same
474 name as the attribute, and a C<writer> with the name you provided.
475
476 Use 'bare' when you are deliberately not installing any methods
477 (accessor, reader, etc.) associated with this attribute; otherwise,
478 Moose will issue a deprecation warning when this attribute is added to a
479 metaclass.
480
481 =item C<< isa => Type >>
482
483 This option accepts a type. The type can be a string, which should be
484 a type name. If the type name is unknown, it is assumed to be a class
485 name.
486
487 This option can also accept a L<Moose::Meta::TypeConstraint> object.
488
489 If you I<also> provide a C<does> option, then your C<isa> option must
490 be a class name, and that class must do the role specified with
491 C<does>.
492
493 =item C<< does => Role >>
494
495 This is short-hand for saying that the attribute's type must be an
496 object which does the named role.
497
498 B<This option is not yet supported.>
499
500 =item C<< coerce => Bool >>
501
502 This option is only valid for objects with a type constraint
503 (C<isa>). If this is true, then coercions will be applied whenever
504 this attribute is set.
505
506 You can make both this and the C<weak_ref> option true.
507
508 =item C<< trigger => CodeRef >>
509
510 This option accepts a subroutine reference, which will be called after
511 the attribute is set.
512
513 =item C<< required => Bool >>
514
515 An attribute which is required must be provided to the constructor. An
516 attribute which is required can also have a C<default> or C<builder>,
517 which will satisfy its required-ness.
518
519 A required attribute must have a C<default>, C<builder> or a
520 non-C<undef> C<init_arg>
521
522 =item C<< lazy => Bool >>
523
524 A lazy attribute must have a C<default> or C<builder>. When an
525 attribute is lazy, the default value will not be calculated until the
526 attribute is read.
527
528 =item C<< weak_ref => Bool >>
529
530 If this is true, the attribute's value will be stored as a weak
531 reference.
532
533 =item C<< auto_deref => Bool >>
534
535 If this is true, then the reader will dereference the value when it is
536 called. The attribute must have a type constraint which defines the
537 attribute as an array or hash reference.
538
539 =item C<< lazy_build => Bool >>
540
541 Setting this to true makes the attribute lazy and provides a number of
542 default methods.
543
544   has 'size' => (
545       is         => 'ro',
546       lazy_build => 1,
547   );
548
549 is equivalent to this:
550
551   has 'size' => (
552       is        => 'ro',
553       lazy      => 1,
554       builder   => '_build_size',
555       clearer   => 'clear_size',
556       predicate => 'has_size',
557   );
558
559 =back
560
561 =head2 C<< associate_method(MethodName) >>
562
563 Associates a method with the attribute. Typically, this is called internally
564 when an attribute generates its accessors.
565
566 Currently the argument I<MethodName> is ignored in Mouse.
567
568 =head2 C<< verify_against_type_constraint(Item) -> TRUE | ERROR >>
569
570 Checks that the given value passes this attribute's type constraint. Returns C<true>
571 on success, otherwise C<confess>es.
572
573 =head2 C<< clone_and_inherit_options(options) -> Mouse::Meta::Attribute >>
574
575 Creates a new attribute in the owner class, inheriting options from parent classes.
576 Accessors and helper methods are installed. Some error checking is done.
577
578 =head2 C<< get_read_method_ref >>
579
580 =head2 C<< get_write_method_ref >>
581
582 Returns the subroutine reference of a method suitable for reading or
583 writing the attribute's value in the associated class. These methods
584 always return a subroutine reference, regardless of whether or not the
585 attribute is read- or write-only.
586
587 =head1 SEE ALSO
588
589 L<Moose::Meta::Attribute>
590
591 L<Class::MOP::Attribute>
592
593 =cut
594