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