Some errors for auto_deref
[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     confess "You cannot have lazy attribute ($name) without specifying a default value for it"
159         if $args{lazy} && !exists($args{default}) && !exists($args{builder});
160
161     confess "References are not allowed as default values, you must wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])"
162         if ref($args{default})
163         && ref($args{default}) ne 'CODE';
164
165     confess "You cannot auto-dereference without specifying a type constraint on attribute $name"
166         if $args{auto_deref} && !exists($args{isa});
167
168     confess "You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute $name"
169         if $args{auto_deref}
170         && $args{isa} ne 'ArrayRef'
171         && $args{isa} ne 'HashRef';
172
173     $args{type_constraint} = delete $args{isa}
174         if exists $args{isa};
175
176     my $attribute = $self->new(%args, name => $name, class => $class);
177     my $meta = $class->meta;
178
179     $meta->add_attribute($attribute);
180
181     # install an accessor
182     if ($attribute->_is_metadata eq 'rw' || $attribute->_is_metadata eq 'ro') {
183         my $accessor = $attribute->generate_accessor;
184         no strict 'refs';
185         *{ $class . '::' . $name } = $accessor;
186     }
187
188     for my $method (qw/predicate clearer/) {
189         my $predicate = "has_$method";
190         if ($attribute->$predicate) {
191             my $generator = "generate_$method";
192             my $coderef = $attribute->$generator;
193             no strict 'refs';
194             *{ $class . '::' . $attribute->$method } = $coderef;
195         }
196     }
197
198     if ($attribute->has_handles) {
199         my $method_map = $attribute->generate_handles;
200         for my $method_name (keys %$method_map) {
201             no strict 'refs';
202             *{ $class . '::' . $method_name } = $method_map->{$method_name};
203         }
204     }
205
206     return $attribute;
207 }
208
209 sub find_type_constraint {
210     my $self = shift;
211     my $type = $self->type_constraint;
212
213     return unless $type;
214
215     my $checker = Mouse::TypeRegistry->optimized_constraints->{$type};
216     return $checker if $checker;
217
218     return sub { blessed($_) && blessed($_) eq $type };
219 }
220
221 sub verify_type_constraint {
222     my $self = shift;
223     local $_ = shift;
224
225     my $type = $self->type_constraint
226         or return 1;
227     my $constraint = $self->find_type_constraint;
228
229     return 1 if $constraint->($_);
230
231     my $name = $self->name;
232     my $display = defined($_) ? overload::StrVal($_) : 'undef';
233     Carp::confess("Attribute ($name) does not pass the type constraint because: Validation failed for \'$type\' failed with value $display");
234 }
235
236 sub _canonicalize_handles {
237     my $self    = shift;
238     my $handles = shift;
239
240     if (ref($handles) eq 'HASH') {
241         return %$handles;
242     }
243     elsif (ref($handles) eq 'ARRAY') {
244         return map { $_ => $_ } @$handles;
245     }
246     else {
247         confess "Unable to canonicalize the 'handles' option with $handles";
248     }
249 }
250
251 1;
252
253 __END__
254
255 =head1 NAME
256
257 Mouse::Meta::Attribute - attribute metaclass
258
259 =head1 METHODS
260
261 =head2 new %args -> Mouse::Meta::Attribute
262
263 Instantiates a new Mouse::Meta::Attribute. Does nothing else.
264
265 =head2 create OwnerClass, AttributeName, %args -> Mouse::Meta::Attribute
266
267 Creates a new attribute in OwnerClass. Accessors and helper methods are
268 installed. Some error checking is done.
269
270 =head2 name -> AttributeName
271
272 =head2 class -> OwnerClass
273
274 =head2 is_required -> Bool
275
276 =head2 default -> Item
277
278 =head2 has_default -> Bool
279
280 =head2 is_lazy -> Bool
281
282 =head2 predicate -> MethodName | Undef
283
284 =head2 has_predicate -> Bool
285
286 =head2 clearer -> MethodName | Undef
287
288 =head2 has_clearer -> Bool
289
290 =head2 handles -> { LocalName => RemoteName }
291
292 =head2 has_handles -> Bool
293
294 =head2 is_weak_ref -> Bool
295
296 =head2 init_arg -> Str
297
298 =head2 type_constraint -> Str
299
300 =head2 has_type_constraint -> Bool
301
302 =head2 trigger => CODE | Undef
303
304 =head2 has_trigger -> Bool
305
306 =head2 builder => MethodName | Undef
307
308 =head2 has_builder -> Bool
309
310 Informational methods.
311
312 =head2 generate_accessor -> CODE
313
314 Creates a new code reference for the attribute's accessor.
315
316 =head2 generate_predicate -> CODE
317
318 Creates a new code reference for the attribute's predicate.
319
320 =head2 generate_clearer -> CODE
321
322 Creates a new code reference for the attribute's clearer.
323
324 =head2 generate_handles -> { MethodName => CODE }
325
326 Creates a new code reference for each of the attribute's handles methods.
327
328 =head2 find_type_constraint -> CODE
329
330 Returns a code reference which can be used to check that a given value passes
331 this attribute's type constraint;
332
333 =head2 verify_type_constraint Item -> 1 | ERROR
334
335 Checks that the given value passes this attribute's type constraint. Returns 1
336 on success, otherwise C<confess>es.
337
338 =cut
339