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