Warn about missing associated methoes, instead of die.
[gitmo/Mouse.git] / lib / Mouse / Meta / Attribute.pm
1 package Mouse::Meta::Attribute;
2 use strict;
3 use warnings;
4
5 use Carp 'confess';
6 use Scalar::Util ();
7 use Mouse::Meta::TypeConstraint;
8
9 sub new {
10     my ($class, $name, %options) = @_;
11
12     $options{name} = $name;
13
14     $options{init_arg} = $name
15         unless exists $options{init_arg};
16
17     $options{is} ||= '';
18
19     bless \%options, $class;
20 }
21
22 sub name                 { $_[0]->{name}                   }
23 sub associated_class     { $_[0]->{associated_class}       }
24 sub _is_metadata         { $_[0]->{is}                     }
25 sub is_required          { $_[0]->{required}               }
26 sub default              { $_[0]->{default}                }
27 sub is_lazy              { $_[0]->{lazy}                   }
28 sub is_lazy_build        { $_[0]->{lazy_build}             }
29 sub predicate            { $_[0]->{predicate}              }
30 sub clearer              { $_[0]->{clearer}                }
31 sub handles              { $_[0]->{handles}                }
32 sub is_weak_ref          { $_[0]->{weak_ref}               }
33 sub init_arg             { $_[0]->{init_arg}               }
34 sub type_constraint      { $_[0]->{type_constraint}        }
35 sub find_type_constraint {
36     Carp::carp("This method was deprecated");
37     $_[0]->type_constraint();
38 }
39 sub trigger              { $_[0]->{trigger}                }
40 sub builder              { $_[0]->{builder}                }
41 sub should_auto_deref    { $_[0]->{auto_deref}             }
42 sub should_coerce        { $_[0]->{should_coerce}          }
43
44 sub has_default          { exists $_[0]->{default}         }
45 sub has_predicate        { exists $_[0]->{predicate}       }
46 sub has_clearer          { exists $_[0]->{clearer}         }
47 sub has_handles          { exists $_[0]->{handles}         }
48 sub has_type_constraint  { exists $_[0]->{type_constraint} }
49 sub has_trigger          { exists $_[0]->{trigger}         }
50 sub has_builder          { exists $_[0]->{builder}         }
51
52 sub _create_args {
53     $_[0]->{_create_args} = $_[1] if @_ > 1;
54     $_[0]->{_create_args}
55 }
56
57 sub _inlined_name {
58     my $self = shift;
59     return sprintf '"%s"', quotemeta $self->name;
60 }
61
62 sub _generate_accessor{
63     my ($attribute) = @_;
64
65     my $name          = $attribute->name;
66     my $default       = $attribute->default;
67     my $constraint    = $attribute->type_constraint;
68     my $builder       = $attribute->builder;
69     my $trigger       = $attribute->trigger;
70     my $is_weak       = $attribute->is_weak_ref;
71     my $should_deref  = $attribute->should_auto_deref;
72     my $should_coerce = $attribute->should_coerce;
73
74     my $compiled_type_constraint    = $constraint ? $constraint->{_compiled_type_constraint} : undef;
75
76     my $self  = '$_[0]';
77     my $key   = $attribute->_inlined_name;
78
79     my $accessor = 
80         '#line ' . __LINE__ . ' "' . __FILE__ . "\"\n" .
81         "sub {\n";
82     if ($attribute->_is_metadata eq 'rw') {
83         $accessor .= 
84             '#line ' . __LINE__ . ' "' . __FILE__ . "\"\n" .
85             'if (scalar(@_) >= 2) {' . "\n";
86
87         my $value = '$_[1]';
88
89         if ($constraint) {
90             if ($should_coerce) {
91                 $accessor .=
92                     "\n".
93                     '#line ' . __LINE__ . ' "' . __FILE__ . "\"\n" .
94                     'my $val = Mouse::Util::TypeConstraints->typecast_constraints("'.$attribute->associated_class->name.'", $attribute->{type_constraint}, '.$value.');';
95                 $value = '$val';
96             }
97             if ($compiled_type_constraint) {
98                 $accessor .= 
99                     "\n".
100                     '#line ' . __LINE__ . ' "' . __FILE__ . "\"\n" .
101                     'unless ($compiled_type_constraint->('.$value.')) {
102                         $attribute->verify_type_constraint_error($name, '.$value.', $attribute->{type_constraint});
103                     }' . "\n";
104             } else {
105                 $accessor .= 
106                     "\n".
107                     '#line ' . __LINE__ . ' "' . __FILE__ . "\"\n" .
108                     'unless ($constraint->check('.$value.')) {
109                         $attribute->verify_type_constraint_error($name, '.$value.', $attribute->{type_constraint});
110                     }' . "\n";
111             }
112         }
113
114         # if there's nothing left to do for the attribute we can return during
115         # this setter
116         $accessor .= 'return ' if !$is_weak && !$trigger && !$should_deref;
117
118         $accessor .= $self.'->{'.$key.'} = '.$value.';' . "\n";
119
120         if ($is_weak) {
121             $accessor .= 'Scalar::Util::weaken('.$self.'->{'.$key.'}) if ref('.$self.'->{'.$key.'});' . "\n";
122         }
123
124         if ($trigger) {
125             $accessor .= '$trigger->('.$self.', '.$value.');' . "\n";
126         }
127
128         $accessor .= "}\n";
129     }
130     else {
131         $accessor .= 'Carp::confess("Cannot assign a value to a read-only accessor") if scalar(@_) >= 2;' . "\n";
132     }
133
134     if ($attribute->is_lazy) {
135         $accessor .= $self.'->{'.$key.'} = ';
136
137         $accessor .= $attribute->has_builder
138                 ? $self.'->$builder'
139                     : ref($default) eq 'CODE'
140                     ? '$default->('.$self.')'
141                     : '$default';
142         $accessor .= ' if !exists '.$self.'->{'.$key.'};' . "\n";
143     }
144
145     if ($should_deref) {
146         if (ref($constraint) && $constraint->name =~ '^ArrayRef\b') {
147             $accessor .= 'if (wantarray) {
148                 return @{ '.$self.'->{'.$key.'} || [] };
149             }';
150         }
151         else {
152             $accessor .= 'if (wantarray) {
153                 return %{ '.$self.'->{'.$key.'} || {} };
154             }';
155         }
156     }
157
158     $accessor .= 'return '.$self.'->{'.$key.'};
159     }';
160
161     my $sub = eval $accessor;
162     Carp::confess($@) if $@;
163     return $sub;
164 }
165
166
167 sub _generate_predicate {
168     my $attribute = shift;
169     my $key = $attribute->_inlined_name;
170
171     my $predicate = 'sub { exists($_[0]->{'.$key.'}) }';
172
173     my $sub = eval $predicate;
174     confess $@ if $@;
175     return $sub;
176 }
177
178 sub _generate_clearer {
179     my $attribute = shift;
180     my $key = $attribute->_inlined_name;
181
182     my $clearer = 'sub { delete($_[0]->{'.$key.'}) }';
183
184     my $sub = eval $clearer;
185     confess $@ if $@;
186     return $sub;
187 }
188
189 sub _generate_handles {
190     my $attribute = shift;
191     my $reader = $attribute->name;
192     my %handles = $attribute->_canonicalize_handles($attribute->handles);
193
194     my %method_map;
195
196     for my $local_method (keys %handles) {
197         my $remote_method = $handles{$local_method};
198
199         my $method = 'sub {
200             my $self = shift;
201             $self->'.$reader.'->'.$remote_method.'(@_)
202         }';
203
204         $method_map{$local_method} = eval $method;
205         confess $@ if $@;
206     }
207
208     return \%method_map;
209 }
210
211 sub create {
212     my ($self, $class, $name, %args) = @_;
213
214     $args{name} = $name;
215     $args{associated_class} = $class;
216
217     %args = $self->canonicalize_args($name, %args);
218     $self->validate_args($name, \%args);
219
220     $args{should_coerce} = delete $args{coerce}
221         if exists $args{coerce};
222
223     if (exists $args{isa}) {
224         my $type_constraint = delete $args{isa};
225         $args{type_constraint}= Mouse::Util::TypeConstraints::find_or_create_isa_type_constraint($type_constraint);
226     }
227
228     my $attribute = $self->new($name, %args);
229
230     $attribute->_create_args(\%args);
231
232     $class->add_attribute($attribute);
233
234     my $associated_methods = 0;
235
236     my $is_metadata = $attribute->_is_metadata || '';
237
238     # install an accessor
239     if ($is_metadata eq 'rw' || $is_metadata eq 'ro') {
240         my $code = $attribute->_generate_accessor();
241         $class->add_method($name => $code);
242         $associated_methods++;
243     }
244
245     for my $method (qw/predicate clearer/) {
246         my $predicate = "has_$method";
247         if ($attribute->$predicate) {
248             my $generator = "_generate_$method";
249             my $coderef = $attribute->$generator;
250             $class->add_method($attribute->$method => $coderef);
251             $associated_methods++;
252         }
253     }
254
255     if ($attribute->has_handles) {
256         my $method_map = $attribute->_generate_handles;
257         for my $method_name (keys %$method_map) {
258             $class->add_method($method_name => $method_map->{$method_name});
259             $associated_methods++;
260         }
261     }
262
263     if($associated_methods == 0 && $is_metadata ne 'bare'){
264         Carp::cluck(qq{Attribute ($name) of class }.$class->name.qq{ has no associated methods (did you mean to provide an "is" argument?)});
265     }
266
267     return $attribute;
268 }
269
270 sub canonicalize_args {
271     my $self = shift;
272     my $name = shift;
273     my %args = @_;
274
275     if ($args{lazy_build}) {
276         $args{lazy}      = 1;
277         $args{required}  = 1;
278         $args{builder}   = "_build_${name}"
279             if !exists($args{builder});
280         if ($name =~ /^_/) {
281             $args{clearer}   = "_clear${name}" if !exists($args{clearer});
282             $args{predicate} = "_has${name}" if !exists($args{predicate});
283         }
284         else {
285             $args{clearer}   = "clear_${name}" if !exists($args{clearer});
286             $args{predicate} = "has_${name}" if !exists($args{predicate});
287         }
288     }
289
290     return %args;
291 }
292
293 sub validate_args {
294     my $self = shift;
295     my $name = shift;
296     my $args = shift;
297
298     confess "You can not use lazy_build and default for the same attribute ($name)"
299         if $args->{lazy_build} && exists $args->{default};
300
301     confess "You cannot have lazy attribute ($name) without specifying a default value for it"
302         if $args->{lazy}
303         && !exists($args->{default})
304         && !exists($args->{builder});
305
306     confess "References are not allowed as default values, you must wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])"
307         if ref($args->{default})
308         && ref($args->{default}) ne 'CODE';
309
310     confess "You cannot auto-dereference without specifying a type constraint on attribute ($name)"
311         if $args->{auto_deref} && !exists($args->{isa});
312
313     confess "You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute ($name)"
314         if $args->{auto_deref}
315         && $args->{isa} !~ /^(?:ArrayRef|HashRef)(?:\[.*\])?$/;
316
317     if ($args->{trigger}) {
318         if (ref($args->{trigger}) eq 'HASH') {
319             Carp::carp "HASH-based form of trigger has been removed. Only the coderef form of triggers are now supported.";
320         }
321
322         confess "Trigger must be a CODE ref on attribute ($name)"
323             if ref($args->{trigger}) ne 'CODE';
324     }
325
326     return 1;
327 }
328
329 sub verify_against_type_constraint {
330     my ($self, $value) = @_;
331     my $tc = $self->type_constraint;
332     return 1 unless $tc;
333
334     local $_ = $value;
335     return 1 if $tc->check($value);
336
337     $self->verify_type_constraint_error($self->name, $value, $tc);
338 }
339
340 sub verify_type_constraint_error {
341     my($self, $name, $value, $type) = @_;
342     Carp::confess("Attribute ($name) does not pass the type constraint because: " . $type->get_message($value));
343 }
344
345 sub coerce_constraint { ## my($self, $value) = @_;
346     my $type = $_[0]->{type_constraint}
347         or return $_[1];
348     return Mouse::Util::TypeConstraints->typecast_constraints($_[0]->associated_class->name, $_[0]->type_constraint, $_[1]);
349 }
350
351 sub _canonicalize_handles {
352     my $self    = shift;
353     my $handles = shift;
354
355     if (ref($handles) eq 'HASH') {
356         return %$handles;
357     }
358     elsif (ref($handles) eq 'ARRAY') {
359         return map { $_ => $_ } @$handles;
360     }
361     else {
362         confess "Unable to canonicalize the 'handles' option with $handles";
363     }
364 }
365
366 sub clone_parent {
367     my $self  = shift;
368     my $class = shift;
369     my $name  = shift;
370     my %args  = ($self->get_parent_args($class, $name), @_);
371
372     $self->create($class, $name, %args);
373 }
374
375 sub get_parent_args {
376     my $self  = shift;
377     my $class = shift;
378     my $name  = shift;
379
380     for my $super ($class->linearized_isa) {
381         my $super_attr = $super->can("meta") && $super->meta->get_attribute($name)
382             or next;
383         return %{ $super_attr->_create_args };
384     }
385
386     confess "Could not find an attribute by the name of '$name' to inherit from";
387 }
388
389 1;
390
391 __END__
392
393 =head1 NAME
394
395 Mouse::Meta::Attribute - attribute metaclass
396
397 =head1 METHODS
398
399 =head2 new %args -> Mouse::Meta::Attribute
400
401 Instantiates a new Mouse::Meta::Attribute. Does nothing else.
402
403 =head2 create OwnerClass, AttributeName, %args -> Mouse::Meta::Attribute
404
405 Creates a new attribute in OwnerClass. Accessors and helper methods are
406 installed. Some error checking is done.
407
408 =head2 name -> AttributeName
409
410 =head2 associated_class -> OwnerClass
411
412 =head2 is_required -> Bool
413
414 =head2 default -> Item
415
416 =head2 has_default -> Bool
417
418 =head2 is_lazy -> Bool
419
420 =head2 predicate -> MethodName | Undef
421
422 =head2 has_predicate -> Bool
423
424 =head2 clearer -> MethodName | Undef
425
426 =head2 has_clearer -> Bool
427
428 =head2 handles -> { LocalName => RemoteName }
429
430 =head2 has_handles -> Bool
431
432 =head2 is_weak_ref -> Bool
433
434 =head2 init_arg -> Str
435
436 =head2 type_constraint -> Str
437
438 =head2 has_type_constraint -> Bool
439
440 =head2 trigger => CODE | Undef
441
442 =head2 has_trigger -> Bool
443
444 =head2 builder => MethodName | Undef
445
446 =head2 has_builder -> Bool
447
448 =head2 is_lazy_build => Bool
449
450 =head2 should_auto_deref -> Bool
451
452 Informational methods.
453
454 =head2 verify_against_type_constraint Item -> 1 | ERROR
455
456 Checks that the given value passes this attribute's type constraint. Returns 1
457 on success, otherwise C<confess>es.
458
459 =head2 canonicalize_args Name, %args -> %args
460
461 Canonicalizes some arguments to create. In particular, C<lazy_build> is
462 canonicalized into C<lazy>, C<builder>, etc.
463
464 =head2 validate_args Name, \%args -> 1 | ERROR
465
466 Checks that the arguments to create the attribute (ie those specified by
467 C<has>) are valid.
468
469 =head2 clone_parent OwnerClass, AttributeName, %args -> Mouse::Meta::Attribute
470
471 Creates a new attribute in OwnerClass, inheriting options from parent classes.
472 Accessors and helper methods are installed. Some error checking is done.
473
474 =head2 get_parent_args OwnerClass, AttributeName -> Hash
475
476 Returns the options that the parent class of C<OwnerClass> used for attribute
477 C<AttributeName>.
478
479 =cut
480