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