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