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