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