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