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