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