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