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