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