added Meta::Class->add_attribute_list for Moose compatibility
[gitmo/Mouse.git] / lib / Mouse / Meta / Attribute.pm
CommitLineData
306290e8 1package Mouse::Meta::Attribute;
c3398f5b 2use strict;
3use warnings;
3b8fe109 4require overload;
c3398f5b 5
6use Carp 'confess';
6c169c50 7use Scalar::Util ();
c3398f5b 8
9sub new {
2608b115 10 my ($class, $name, %options) = @_;
c3398f5b 11
2608b115 12 $options{name} = $name;
2e7e86c6 13
2608b115 14 $options{init_arg} = $name
15 unless exists $options{init_arg};
45959ffa 16
2608b115 17 $options{is} ||= '';
c3398f5b 18
2608b115 19 bless \%options, $class;
c3398f5b 20}
21
f6715552 22sub name { $_[0]->{name} }
23sub associated_class { $_[0]->{associated_class} }
24sub _is_metadata { $_[0]->{is} }
25sub is_required { $_[0]->{required} }
26sub default { $_[0]->{default} }
27sub is_lazy { $_[0]->{lazy} }
28sub is_lazy_build { $_[0]->{lazy_build} }
29sub predicate { $_[0]->{predicate} }
30sub clearer { $_[0]->{clearer} }
31sub handles { $_[0]->{handles} }
32sub is_weak_ref { $_[0]->{weak_ref} }
33sub init_arg { $_[0]->{init_arg} }
34sub type_constraint { $_[0]->{type_constraint} }
35sub trigger { $_[0]->{trigger} }
36sub builder { $_[0]->{builder} }
37sub should_auto_deref { $_[0]->{auto_deref} }
38sub should_coerce { $_[0]->{should_coerce} }
39sub find_type_constraint { $_[0]->{find_type_constraint} }
c3398f5b 40
f6715552 41sub has_default { exists $_[0]->{default} }
42sub has_predicate { exists $_[0]->{predicate} }
43sub has_clearer { exists $_[0]->{clearer} }
44sub has_handles { exists $_[0]->{handles} }
45sub has_type_constraint { exists $_[0]->{type_constraint} }
46sub has_trigger { exists $_[0]->{trigger} }
47sub has_builder { exists $_[0]->{builder} }
eec1bb49 48
1bfebf5f 49sub _create_args {
50 $_[0]->{_create_args} = $_[1] if @_ > 1;
51 $_[0]->{_create_args}
52}
53
7f7406a5 54sub inlined_name {
55 my $self = shift;
56 my $name = $self->name;
57 my $key = "'" . $name . "'";
58 return $key;
59}
60
c3398f5b 61sub generate_accessor {
62 my $attribute = shift;
63
32af3489 64 my $name = $attribute->name;
65 my $default = $attribute->default;
32af3489 66 my $constraint = $attribute->find_type_constraint;
67 my $builder = $attribute->builder;
68 my $trigger = $attribute->trigger;
69 my $is_weak = $attribute->is_weak_ref;
70 my $should_deref = $attribute->should_auto_deref;
71 my $should_coerce = $attribute->should_coerce;
4e757c98 72
85ccd3e9 73 my $self = '$_[0]';
85ccd3e9 74 my $key = $attribute->inlined_name;
c3398f5b 75
321e5271 76 my $accessor =
77 '#line ' . __LINE__ . ' "' . __FILE__ . "\"\n" .
78 "sub {\n";
2434d21b 79 if ($attribute->_is_metadata eq 'rw') {
321e5271 80 $accessor .=
81 '#line ' . __LINE__ . ' "' . __FILE__ . "\"\n" .
82 'if (@_ >= 2) {' . "\n";
7de13475 83
84 my $value = '$_[1]';
a707f587 85
a08e715f 86 if ($constraint) {
eec1bb49 87 $accessor .= 'my $val = ';
32af3489 88 if ($should_coerce) {
321e5271 89 $accessor .=
90 "\n".
91 '#line ' . __LINE__ . ' "' . __FILE__ . "\"\n" .
92 'Mouse::Util::TypeConstraints->typecast_constraints("'.$attribute->associated_class->name.'", $attribute->{find_type_constraint}, $attribute->{type_constraint}, '.$value.');';
eec1bb49 93 } else {
94 $accessor .= $value.';';
4188b837 95 }
321e5271 96 $accessor .=
97 "\n".
98 '#line ' . __LINE__ . ' "' . __FILE__ . "\"\n" .
99 'unless ($constraint->($val)) {
c91d12e0 100 $attribute->verify_type_constraint_error($name, $val, $attribute->type_constraint);
b3b74cc6 101 }' . "\n";
eec1bb49 102 $value = '$val';
a707f587 103 }
104
ccd73de7 105 # if there's nothing left to do for the attribute we can return during
106 # this setter
107 $accessor .= 'return ' if !$is_weak && !$trigger && !$should_deref;
c3398f5b 108
2b9094e8 109 $accessor .= $self.'->{'.$key.'} = '.$value.';' . "\n";
110
ccd73de7 111 if ($is_weak) {
6c169c50 112 $accessor .= 'Scalar::Util::weaken('.$self.'->{'.$key.'}) if ref('.$self.'->{'.$key.'});' . "\n";
c3398f5b 113 }
114
a08e715f 115 if ($trigger) {
88b6c018 116 $accessor .= '$trigger->('.$self.', '.$value.');' . "\n";
c3398f5b 117 }
118
85ccd3e9 119 $accessor .= "}\n";
c3398f5b 120 }
121 else {
85ccd3e9 122 $accessor .= 'confess "Cannot assign a value to a read-only accessor" if scalar(@_) >= 2;' . "\n";
c3398f5b 123 }
124
3aadb773 125 if ($attribute->is_lazy) {
85ccd3e9 126 $accessor .= $self.'->{'.$key.'} = ';
9367e029 127
128 $accessor .= $attribute->has_builder
85ccd3e9 129 ? $self.'->$builder'
130 : ref($default) eq 'CODE'
131 ? '$default->('.$self.')'
132 : '$default';
133 $accessor .= ' if !exists '.$self.'->{'.$key.'};' . "\n";
c3398f5b 134 }
135
ccd73de7 136 if ($should_deref) {
eec1bb49 137 my $type_constraint = $attribute->type_constraint;
138 if (!ref($type_constraint) && $type_constraint eq 'ArrayRef') {
3cf68001 139 $accessor .= 'if (wantarray) {
85ccd3e9 140 return @{ '.$self.'->{'.$key.'} || [] };
7de13475 141 }';
3cf68001 142 }
143 else {
144 $accessor .= 'if (wantarray) {
85ccd3e9 145 return %{ '.$self.'->{'.$key.'} || {} };
7de13475 146 }';
3cf68001 147 }
148 }
149
85ccd3e9 150 $accessor .= 'return '.$self.'->{'.$key.'};
c3398f5b 151 }';
152
71b948d1 153 my $sub = eval $accessor;
154 confess $@ if $@;
155 return $sub;
c3398f5b 156}
157
158sub generate_predicate {
159 my $attribute = shift;
d10fd510 160 my $key = $attribute->inlined_name;
c3398f5b 161
d10fd510 162 my $predicate = 'sub { exists($_[0]->{'.$key.'}) }';
c3398f5b 163
71b948d1 164 my $sub = eval $predicate;
165 confess $@ if $@;
166 return $sub;
c3398f5b 167}
168
169sub generate_clearer {
170 my $attribute = shift;
d10fd510 171 my $key = $attribute->inlined_name;
c3398f5b 172
d10fd510 173 my $clearer = 'sub { delete($_[0]->{'.$key.'}) }';
c3398f5b 174
71b948d1 175 my $sub = eval $clearer;
176 confess $@ if $@;
177 return $sub;
c3398f5b 178}
179
180sub generate_handles {
181 my $attribute = shift;
2434d21b 182 my $reader = $attribute->name;
c3cc3642 183 my %handles = $attribute->_canonicalize_handles($attribute->handles);
c3398f5b 184
185 my %method_map;
186
c3cc3642 187 for my $local_method (keys %handles) {
188 my $remote_method = $handles{$local_method};
c3398f5b 189
190 my $method = 'sub {
191 my $self = shift;
0ecefe82 192 $self->'.$reader.'->'.$remote_method.'(@_)
c3398f5b 193 }';
194
195 $method_map{$local_method} = eval $method;
71b948d1 196 confess $@ if $@;
c3398f5b 197 }
198
199 return \%method_map;
200}
201
202sub create {
203 my ($self, $class, $name, %args) = @_;
204
1bfebf5f 205 $args{name} = $name;
181502b9 206 $args{associated_class} = $class;
1bfebf5f 207
93d190e0 208 %args = $self->canonicalize_args($name, %args);
1bbaa8ed 209 $self->validate_args($name, \%args);
45ea8620 210
32af3489 211 $args{should_coerce} = delete $args{coerce}
4188b837 212 if exists $args{coerce};
213
eec1bb49 214 if (exists $args{isa}) {
c1c94293 215 confess "Got isa => $args{isa}, but Mouse does not yet support parameterized types for containers other than ArrayRef and HashRef (rt.cpan.org #39795)"
315b97c2 216 if $args{isa} =~ /^([^\[]+)\[.+\]$/ &&
217 $1 ne 'ArrayRef' &&
a510e63c 218 $1 ne 'HashRef' &&
219 $1 ne 'Maybe'
220 ;
5fa003bf 221
eec1bb49 222 my $type_constraint = delete $args{isa};
321e5271 223 $type_constraint =~ s/\s+//g;
224 my $code = Mouse::Util::TypeConstraints::find_or_create_isa_type_constraint($type_constraint);
225 $args{type_constraint} = $type_constraint =~ /\|/ ?
226 [ split (/\|/, $type_constraint ) ] :
227 $type_constraint
228 ;
eec1bb49 229 $args{find_type_constraint} = $code;
230 }
186657a9 231
2608b115 232 my $attribute = $self->new($name, %args);
1bfebf5f 233
724c77c0 234 $attribute->_create_args(\%args);
c3398f5b 235
724c77c0 236 $class->add_attribute($attribute);
b2500191 237
c3398f5b 238 # install an accessor
2434d21b 239 if ($attribute->_is_metadata eq 'rw' || $attribute->_is_metadata eq 'ro') {
c3398f5b 240 my $accessor = $attribute->generate_accessor;
724c77c0 241 $class->add_method($name => $accessor);
c3398f5b 242 }
243
c3398f5b 244 for my $method (qw/predicate clearer/) {
2434d21b 245 my $predicate = "has_$method";
246 if ($attribute->$predicate) {
c3398f5b 247 my $generator = "generate_$method";
248 my $coderef = $attribute->$generator;
724c77c0 249 $class->add_method($attribute->$method => $coderef);
c3398f5b 250 }
251 }
252
2434d21b 253 if ($attribute->has_handles) {
c3398f5b 254 my $method_map = $attribute->generate_handles;
255 for my $method_name (keys %$method_map) {
724c77c0 256 $class->add_method($method_name => $method_map->{$method_name});
c3398f5b 257 }
258 }
259
260 return $attribute;
261}
262
93d190e0 263sub canonicalize_args {
264 my $self = shift;
265 my $name = shift;
266 my %args = @_;
267
268 if ($args{lazy_build}) {
269 $args{lazy} = 1;
270 $args{required} = 1;
271 $args{builder} = "_build_${name}"
272 if !exists($args{builder});
273 if ($name =~ /^_/) {
274 $args{clearer} = "_clear${name}" if !exists($args{clearer});
275 $args{predicate} = "_has${name}" if !exists($args{predicate});
276 }
277 else {
278 $args{clearer} = "clear_${name}" if !exists($args{clearer});
279 $args{predicate} = "has_${name}" if !exists($args{predicate});
280 }
281 }
282
283 return %args;
284}
285
8fd9e611 286sub validate_args {
287 my $self = shift;
288 my $name = shift;
1bbaa8ed 289 my $args = shift;
8fd9e611 290
93d190e0 291 confess "You can not use lazy_build and default for the same attribute ($name)"
1bbaa8ed 292 if $args->{lazy_build} && exists $args->{default};
93d190e0 293
8fd9e611 294 confess "You cannot have lazy attribute ($name) without specifying a default value for it"
1bbaa8ed 295 if $args->{lazy}
296 && !exists($args->{default})
297 && !exists($args->{builder});
8fd9e611 298
299 confess "References are not allowed as default values, you must wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])"
1bbaa8ed 300 if ref($args->{default})
301 && ref($args->{default}) ne 'CODE';
8fd9e611 302
97661b77 303 confess "You cannot auto-dereference without specifying a type constraint on attribute ($name)"
1bbaa8ed 304 if $args->{auto_deref} && !exists($args->{isa});
8fd9e611 305
97661b77 306 confess "You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute ($name)"
1bbaa8ed 307 if $args->{auto_deref}
308 && $args->{isa} ne 'ArrayRef'
309 && $args->{isa} ne 'HashRef';
8fd9e611 310
506db557 311 if ($args->{trigger}) {
a08e715f 312 if (ref($args->{trigger}) eq 'HASH') {
313 Carp::carp "HASH-based form of trigger has been removed. Only the coderef form of triggers are now supported.";
844fa049 314 }
506db557 315
844fa049 316 confess "Trigger must be a CODE ref on attribute ($name)"
a08e715f 317 if ref($args->{trigger}) ne 'CODE';
506db557 318 }
6c5498d0 319
8fd9e611 320 return 1;
321}
322
20e25eb9 323sub verify_against_type_constraint {
8a7f2a8a 324 return 1 unless $_[0]->{type_constraint};
5aa30ced 325
8a7f2a8a 326 local $_ = $_[1];
327 return 1 if $_[0]->{find_type_constraint}->($_);
5aa30ced 328
8a7f2a8a 329 my $self = shift;
b3b74cc6 330 $self->verify_type_constraint_error($self->name, $_, $self->type_constraint);
331}
5aa30ced 332
b3b74cc6 333sub verify_type_constraint_error {
334 my($self, $name, $value, $type) = @_;
335 $type = ref($type) eq 'ARRAY' ? join '|', @{ $type } : $type;
c91d12e0 336 my $display = defined($value) ? overload::StrVal($value) : 'undef';
f3e05dfd 337 Carp::confess("Attribute ($name) does not pass the type constraint because: Validation failed for \'$type\' failed with value $display");
5aa30ced 338}
339
8a7f2a8a 340sub coerce_constraint { ## my($self, $value) = @_;
341 my $type = $_[0]->{type_constraint}
342 or return $_[1];
3b46bd49 343 return Mouse::Util::TypeConstraints->typecast_constraints($_[0]->associated_class->name, $_[0]->find_type_constraint, $type, $_[1]);
4188b837 344}
345
af745d5a 346sub _canonicalize_handles {
347 my $self = shift;
348 my $handles = shift;
349
350 if (ref($handles) eq 'HASH') {
351 return %$handles;
352 }
353 elsif (ref($handles) eq 'ARRAY') {
354 return map { $_ => $_ } @$handles;
355 }
356 else {
357 confess "Unable to canonicalize the 'handles' option with $handles";
358 }
359}
360
1bfebf5f 361sub clone_parent {
362 my $self = shift;
363 my $class = shift;
364 my $name = shift;
365 my %args = ($self->get_parent_args($class, $name), @_);
366
367 $self->create($class, $name, %args);
368}
369
370sub get_parent_args {
371 my $self = shift;
372 my $class = shift;
373 my $name = shift;
374
724c77c0 375 for my $super ($class->linearized_isa) {
bb733405 376 my $super_attr = $super->can("meta") && $super->meta->get_attribute($name)
1bfebf5f 377 or next;
378 return %{ $super_attr->_create_args };
379 }
380
381 confess "Could not find an attribute by the name of '$name' to inherit from";
382}
383
c3398f5b 3841;
385
386__END__
387
388=head1 NAME
389
306290e8 390Mouse::Meta::Attribute - attribute metaclass
c3398f5b 391
392=head1 METHODS
393
306290e8 394=head2 new %args -> Mouse::Meta::Attribute
c3398f5b 395
306290e8 396Instantiates a new Mouse::Meta::Attribute. Does nothing else.
c3398f5b 397
306290e8 398=head2 create OwnerClass, AttributeName, %args -> Mouse::Meta::Attribute
c3398f5b 399
400Creates a new attribute in OwnerClass. Accessors and helper methods are
401installed. Some error checking is done.
402
403=head2 name -> AttributeName
404
181502b9 405=head2 associated_class -> OwnerClass
c3398f5b 406
ab27a55e 407=head2 is_required -> Bool
c3398f5b 408
ab27a55e 409=head2 default -> Item
c3398f5b 410
ab27a55e 411=head2 has_default -> Bool
412
413=head2 is_lazy -> Bool
414
415=head2 predicate -> MethodName | Undef
416
417=head2 has_predicate -> Bool
418
419=head2 clearer -> MethodName | Undef
420
421=head2 has_clearer -> Bool
c3398f5b 422
423=head2 handles -> { LocalName => RemoteName }
424
ab27a55e 425=head2 has_handles -> Bool
426
3645b316 427=head2 is_weak_ref -> Bool
c3398f5b 428
429=head2 init_arg -> Str
430
ab27a55e 431=head2 type_constraint -> Str
432
433=head2 has_type_constraint -> Bool
434
435=head2 trigger => CODE | Undef
436
437=head2 has_trigger -> Bool
438
439=head2 builder => MethodName | Undef
440
441=head2 has_builder -> Bool
442
93f08899 443=head2 is_lazy_build => Bool
444
0fff36e6 445=head2 should_auto_deref -> Bool
446
c3398f5b 447Informational methods.
448
449=head2 generate_accessor -> CODE
450
451Creates a new code reference for the attribute's accessor.
452
453=head2 generate_predicate -> CODE
454
455Creates a new code reference for the attribute's predicate.
456
457=head2 generate_clearer -> CODE
458
459Creates a new code reference for the attribute's clearer.
460
461=head2 generate_handles -> { MethodName => CODE }
462
463Creates a new code reference for each of the attribute's handles methods.
464
fb706f5c 465=head2 find_type_constraint -> CODE
466
467Returns a code reference which can be used to check that a given value passes
468this attribute's type constraint;
469
20e25eb9 470=head2 verify_against_type_constraint Item -> 1 | ERROR
fb706f5c 471
472Checks that the given value passes this attribute's type constraint. Returns 1
473on success, otherwise C<confess>es.
474
93d190e0 475=head2 canonicalize_args Name, %args -> %args
476
477Canonicalizes some arguments to create. In particular, C<lazy_build> is
478canonicalized into C<lazy>, C<builder>, etc.
479
1bbaa8ed 480=head2 validate_args Name, \%args -> 1 | ERROR
93d190e0 481
482Checks that the arguments to create the attribute (ie those specified by
483C<has>) are valid.
484
f7b11a21 485=head2 clone_parent OwnerClass, AttributeName, %args -> Mouse::Meta::Attribute
486
487Creates a new attribute in OwnerClass, inheriting options from parent classes.
488Accessors and helper methods are installed. Some error checking is done.
489
490=head2 get_parent_args OwnerClass, AttributeName -> Hash
491
492Returns the options that the parent class of C<OwnerClass> used for attribute
493C<AttributeName>.
494
c3398f5b 495=cut
496