preserve aliasing for delegated methods
[gitmo/Moose.git] / lib / Moose / Meta / Attribute.pm
CommitLineData
c0e30cf5 1
2package Moose::Meta::Attribute;
3
4use strict;
5use warnings;
6
21f1e231 7use Scalar::Util 'blessed', 'weaken';
1454efcc 8use Try::Tiny;
a909a4df 9use overload ();
a15dff8d 10
8de57178 11our $VERSION = '0.92';
d44714be 12our $AUTHORITY = 'cpan:STEVAN';
78cd1d3b 13
8ee73eeb 14use Moose::Meta::Method::Accessor;
a05f85c1 15use Moose::Meta::Method::Delegation;
d5c30e52 16use Moose::Util ();
a3c7e2fe 17use Moose::Util::TypeConstraints ();
bc1e29b5 18
c0e30cf5 19use base 'Class::MOP::Attribute';
20
452bac1b 21# options which are not directly used
22# but we store them for metadata purposes
98aae381 23__PACKAGE__->meta->add_attribute('isa' => (reader => '_isa_metadata'));
24__PACKAGE__->meta->add_attribute('does' => (reader => '_does_metadata'));
25__PACKAGE__->meta->add_attribute('is' => (reader => '_is_metadata'));
452bac1b 26
27# these are actual options for the attrs
1a563243 28__PACKAGE__->meta->add_attribute('required' => (reader => 'is_required' ));
29__PACKAGE__->meta->add_attribute('lazy' => (reader => 'is_lazy' ));
26fbace8 30__PACKAGE__->meta->add_attribute('lazy_build' => (reader => 'is_lazy_build' ));
1a563243 31__PACKAGE__->meta->add_attribute('coerce' => (reader => 'should_coerce' ));
32__PACKAGE__->meta->add_attribute('weak_ref' => (reader => 'is_weak_ref' ));
33__PACKAGE__->meta->add_attribute('auto_deref' => (reader => 'should_auto_deref'));
82168dbb 34__PACKAGE__->meta->add_attribute('type_constraint' => (
35 reader => 'type_constraint',
36 predicate => 'has_type_constraint',
37));
8c9d74e7 38__PACKAGE__->meta->add_attribute('trigger' => (
39 reader => 'trigger',
40 predicate => 'has_trigger',
41));
452bac1b 42__PACKAGE__->meta->add_attribute('handles' => (
43 reader => 'handles',
40ef30a5 44 writer => '_set_handles',
452bac1b 45 predicate => 'has_handles',
46));
ddbdc0cb 47__PACKAGE__->meta->add_attribute('documentation' => (
48 reader => 'documentation',
49 predicate => 'has_documentation',
50));
82a5b1a7 51__PACKAGE__->meta->add_attribute('traits' => (
52 reader => 'applied_traits',
53 predicate => 'has_applied_traits',
54));
82168dbb 55
d03bd989 56# we need to have a ->does method in here to
57# more easily support traits, and the introspection
0db4f1d7 58# of those traits. We extend the does check to look
59# for metatrait aliases.
60sub does {
61 my ($self, $role_name) = @_;
1454efcc 62 my $name = try {
0db4f1d7 63 Moose::Util::resolve_metatrait_alias(Attribute => $role_name)
64 };
65 return 0 if !defined($name); # failed to load class
e8895723 66 return $self->Moose::Object::does($name);
0db4f1d7 67}
587e457d 68
be05faea 69sub throw_error {
70 my $self = shift;
71 my $class = ( ref $self && $self->associated_class ) || "Moose::Meta::Class";
72 unshift @_, "message" if @_ % 2 == 1;
73 unshift @_, attr => $self if ref $self;
74 unshift @_, $class;
18748ad6 75 my $handler = $class->can("throw_error"); # to avoid incrementing depth by 1
76 goto $handler;
be05faea 77}
78
78cd1d3b 79sub new {
f3c4e20e 80 my ($class, $name, %options) = @_;
c32c2c61 81 $class->_process_options($name, \%options) unless $options{__hack_no_process_options}; # used from clone()... YECHKKK FIXME ICKY YUCK GROSS
aa4c3a8d 82
83 delete $options{__hack_no_process_options};
84
85 my %attrs =
86 ( map { $_ => 1 }
87 grep { defined }
88 map { $_->init_arg() }
89 $class->meta()->get_all_attributes()
90 );
91
92 my @bad = sort grep { ! $attrs{$_} } keys %options;
93
94 if (@bad)
95 {
96 Carp::cluck "Found unknown argument(s) passed to '$name' attribute constructor in '$class': @bad";
97 }
98
f3c4e20e 99 return $class->SUPER::new($name, %options);
1d768fb1 100}
101
d5c30e52 102sub interpolate_class_and_new {
aa4c3a8d 103 my ($class, $name, %args) = @_;
d5c30e52 104
aa4c3a8d 105 my ( $new_class, @traits ) = $class->interpolate_class(\%args);
d03bd989 106
aa4c3a8d 107 $new_class->new($name, %args, ( scalar(@traits) ? ( traits => \@traits ) : () ) );
d5c30e52 108}
109
110sub interpolate_class {
aa4c3a8d 111 my ($class, $options) = @_;
d5c30e52 112
c32c2c61 113 $class = ref($class) || $class;
114
aa4c3a8d 115 if ( my $metaclass_name = delete $options->{metaclass} ) {
c32c2c61 116 my $new_class = Moose::Util::resolve_metaclass_alias( Attribute => $metaclass_name );
d03bd989 117
c32c2c61 118 if ( $class ne $new_class ) {
119 if ( $new_class->can("interpolate_class") ) {
aa4c3a8d 120 return $new_class->interpolate_class($options);
c32c2c61 121 } else {
122 $class = $new_class;
123 }
124 }
d5c30e52 125 }
126
c32c2c61 127 my @traits;
128
aa4c3a8d 129 if (my $traits = $options->{traits}) {
8974015d 130 my $i = 0;
131 while ($i < @$traits) {
132 my $trait = $traits->[$i++];
133 next if ref($trait); # options to a trait we discarded
134
135 $trait = Moose::Util::resolve_metatrait_alias(Attribute => $trait)
136 || $trait;
137
138 next if $class->does($trait);
139
140 push @traits, $trait;
141
142 # are there options?
143 push @traits, $traits->[$i++]
144 if $traits->[$i] && ref($traits->[$i]);
145 }
965743fb 146
147 if (@traits) {
c32c2c61 148 my $anon_class = Moose::Meta::Class->create_anon_class(
149 superclasses => [ $class ],
150 roles => [ @traits ],
151 cache => 1,
152 );
153
154 $class = $anon_class->name;
155 }
d5c30e52 156 }
c32c2c61 157
158 return ( wantarray ? ( $class, @traits ) : $class );
d5c30e52 159}
160
e606ae5f 161# ...
162
163my @legal_options_for_inheritance = qw(
d03bd989 164 default coerce required
165 documentation lazy handles
e606ae5f 166 builder type_constraint
5f06098e 167 definition_context
d7e7abd9 168 lazy_build weak_ref
e606ae5f 169);
170
171sub legal_options_for_inheritance { @legal_options_for_inheritance }
172
173# NOTE/TODO
d03bd989 174# This method *must* be able to handle
175# Class::MOP::Attribute instances as
176# well. Yes, I know that is wrong, but
177# apparently we didn't realize it was
178# doing that and now we have some code
179# which is dependent on it. The real
180# solution of course is to push this
e606ae5f 181# feature back up into Class::MOP::Attribute
182# but I not right now, I am too lazy.
d03bd989 183# However if you are reading this and
184# looking for something to do,.. please
e606ae5f 185# be my guest.
186# - stevan
ce0e8d63 187sub clone_and_inherit_options {
188 my ($self, %options) = @_;
d03bd989 189
c32c2c61 190 my %copy = %options;
d03bd989 191
ce0e8d63 192 my %actual_options;
d03bd989 193
e606ae5f 194 # NOTE:
195 # we may want to extends a Class::MOP::Attribute
d03bd989 196 # in which case we need to be able to use the
197 # core set of legal options that have always
e606ae5f 198 # been here. But we allows Moose::Meta::Attribute
199 # instances to changes them.
200 # - SL
201 my @legal_options = $self->can('legal_options_for_inheritance')
202 ? $self->legal_options_for_inheritance
203 : @legal_options_for_inheritance;
d03bd989 204
e606ae5f 205 foreach my $legal_option (@legal_options) {
ce0e8d63 206 if (exists $options{$legal_option}) {
207 $actual_options{$legal_option} = $options{$legal_option};
208 delete $options{$legal_option};
209 }
d03bd989 210 }
26fbace8 211
ce0e8d63 212 if ($options{isa}) {
213 my $type_constraint;
8de73ff1 214 if (blessed($options{isa}) && $options{isa}->isa('Moose::Meta::TypeConstraint')) {
215 $type_constraint = $options{isa};
216 }
217 else {
d40ce9d5 218 $type_constraint = Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($options{isa});
8de73ff1 219 (defined $type_constraint)
be05faea 220 || $self->throw_error("Could not find the type constraint '" . $options{isa} . "'", data => $options{isa});
8de73ff1 221 }
5e98d2b6 222
8de73ff1 223 $actual_options{type_constraint} = $type_constraint;
ce0e8d63 224 delete $options{isa};
225 }
d03bd989 226
2ea379cb 227 if ($options{does}) {
228 my $type_constraint;
229 if (blessed($options{does}) && $options{does}->isa('Moose::Meta::TypeConstraint')) {
230 $type_constraint = $options{does};
231 }
232 else {
d40ce9d5 233 $type_constraint = Moose::Util::TypeConstraints::find_or_create_does_type_constraint($options{does});
2ea379cb 234 (defined $type_constraint)
be05faea 235 || $self->throw_error("Could not find the type constraint '" . $options{does} . "'", data => $options{does});
2ea379cb 236 }
237
238 $actual_options{type_constraint} = $type_constraint;
239 delete $options{does};
d03bd989 240 }
c32c2c61 241
cbd141ca 242 # NOTE:
d03bd989 243 # this doesn't apply to Class::MOP::Attributes,
cbd141ca 244 # so we can ignore it for them.
245 # - SL
246 if ($self->can('interpolate_class')) {
aa4c3a8d 247 ( $actual_options{metaclass}, my @traits ) = $self->interpolate_class(\%options);
c32c2c61 248
cbd141ca 249 my %seen;
250 my @all_traits = grep { $seen{$_}++ } @{ $self->applied_traits || [] }, @traits;
251 $actual_options{traits} = \@all_traits if @all_traits;
c32c2c61 252
cbd141ca 253 delete @options{qw(metaclass traits)};
254 }
c32c2c61 255
26fbace8 256 (scalar keys %options == 0)
be05faea 257 || $self->throw_error("Illegal inherited options => (" . (join ', ' => keys %options) . ")", data => \%options);
c32c2c61 258
259
ce0e8d63 260 $self->clone(%actual_options);
1d768fb1 261}
262
c32c2c61 263sub clone {
264 my ( $self, %params ) = @_;
265
aa4c3a8d 266 my $class = delete $params{metaclass} || ref $self;
c32c2c61 267
db72153d 268 my ( @init, @non_init );
c32c2c61 269
0772362a 270 foreach my $attr ( grep { $_->has_value($self) } Class::MOP::class_of($self)->get_all_attributes ) {
db72153d 271 push @{ $attr->has_init_arg ? \@init : \@non_init }, $attr;
272 }
c32c2c61 273
db72153d 274 my %new_params = ( ( map { $_->init_arg => $_->get_value($self) } @init ), %params );
c32c2c61 275
db72153d 276 my $name = delete $new_params{name};
c32c2c61 277
db72153d 278 my $clone = $class->new($name, %new_params, __hack_no_process_options => 1 );
c32c2c61 279
db72153d 280 foreach my $attr ( @non_init ) {
281 $attr->set_value($clone, $attr->get_value($self));
c32c2c61 282 }
db72153d 283
284 return $clone;
c32c2c61 285}
286
1d768fb1 287sub _process_options {
288 my ($class, $name, $options) = @_;
8de73ff1 289
f3c4e20e 290 if (exists $options->{is}) {
21f1e231 291
012fcbd1 292 ### -------------------------
293 ## is => ro, writer => _foo # turns into (reader => foo, writer => _foo) as before
294 ## is => rw, writer => _foo # turns into (reader => foo, writer => _foo)
295 ## is => rw, accessor => _foo # turns into (accessor => _foo)
296 ## is => ro, accessor => _foo # error, accesor is rw
297 ### -------------------------
d03bd989 298
8de73ff1 299 if ($options->{is} eq 'ro') {
be05faea 300 $class->throw_error("Cannot define an accessor name on a read-only attribute, accessors are read/write", data => $options)
21f1e231 301 if exists $options->{accessor};
8de73ff1 302 $options->{reader} ||= $name;
8de73ff1 303 }
304 elsif ($options->{is} eq 'rw') {
21f1e231 305 if ($options->{writer}) {
306 $options->{reader} ||= $name;
307 }
308 else {
309 $options->{accessor} ||= $name;
310 }
8de73ff1 311 }
ccd4cff9 312 elsif ($options->{is} eq 'bare') {
313 # do nothing, but don't complain (later) about missing methods
314 }
8de73ff1 315 else {
e606ae5f 316 $class->throw_error("I do not understand this option (is => " . $options->{is} . ") on attribute ($name)", data => $options->{is});
8de73ff1 317 }
f3c4e20e 318 }
8de73ff1 319
f3c4e20e 320 if (exists $options->{isa}) {
f3c4e20e 321 if (exists $options->{does}) {
1454efcc 322 if (try { $options->{isa}->can('does') }) {
f3c4e20e 323 ($options->{isa}->does($options->{does}))
e606ae5f 324 || $class->throw_error("Cannot have an isa option and a does option if the isa does not do the does on attribute ($name)", data => $options);
f3c4e20e 325 }
326 else {
e606ae5f 327 $class->throw_error("Cannot have an isa option which cannot ->does() on attribute ($name)", data => $options);
26fbace8 328 }
26fbace8 329 }
8de73ff1 330
f3c4e20e 331 # allow for anon-subtypes here ...
332 if (blessed($options->{isa}) && $options->{isa}->isa('Moose::Meta::TypeConstraint')) {
8de73ff1 333 $options->{type_constraint} = $options->{isa};
334 }
335 else {
620db045 336 $options->{type_constraint} = Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($options->{isa});
8de73ff1 337 }
f3c4e20e 338 }
339 elsif (exists $options->{does}) {
340 # allow for anon-subtypes here ...
341 if (blessed($options->{does}) && $options->{does}->isa('Moose::Meta::TypeConstraint')) {
238b424d 342 $options->{type_constraint} = $options->{does};
8de73ff1 343 }
344 else {
620db045 345 $options->{type_constraint} = Moose::Util::TypeConstraints::find_or_create_does_type_constraint($options->{does});
8de73ff1 346 }
f3c4e20e 347 }
8de73ff1 348
f3c4e20e 349 if (exists $options->{coerce} && $options->{coerce}) {
350 (exists $options->{type_constraint})
e606ae5f 351 || $class->throw_error("You cannot have coercion without specifying a type constraint on attribute ($name)", data => $options);
352 $class->throw_error("You cannot have a weak reference to a coerced value on attribute ($name)", data => $options)
8de73ff1 353 if $options->{weak_ref};
f3c4e20e 354 }
8de73ff1 355
0b7df53c 356 if (exists $options->{trigger}) {
21f1e231 357 ('CODE' eq ref $options->{trigger})
e606ae5f 358 || $class->throw_error("Trigger must be a CODE ref on attribute ($name)", data => $options->{trigger});
0b7df53c 359 }
360
f3c4e20e 361 if (exists $options->{auto_deref} && $options->{auto_deref}) {
362 (exists $options->{type_constraint})
e606ae5f 363 || $class->throw_error("You cannot auto-dereference without specifying a type constraint on attribute ($name)", data => $options);
f3c4e20e 364 ($options->{type_constraint}->is_a_type_of('ArrayRef') ||
8de73ff1 365 $options->{type_constraint}->is_a_type_of('HashRef'))
e606ae5f 366 || $class->throw_error("You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute ($name)", data => $options);
f3c4e20e 367 }
8de73ff1 368
f3c4e20e 369 if (exists $options->{lazy_build} && $options->{lazy_build} == 1) {
e606ae5f 370 $class->throw_error("You can not use lazy_build and default for the same attribute ($name)", data => $options)
8de73ff1 371 if exists $options->{default};
a6c84c69 372 $options->{lazy} = 1;
a6c84c69 373 $options->{builder} ||= "_build_${name}";
374 if ($name =~ /^_/) {
f3c4e20e 375 $options->{clearer} ||= "_clear${name}";
376 $options->{predicate} ||= "_has${name}";
d03bd989 377 }
a6c84c69 378 else {
f3c4e20e 379 $options->{clearer} ||= "clear_${name}";
380 $options->{predicate} ||= "has_${name}";
26fbace8 381 }
f3c4e20e 382 }
8de73ff1 383
f3c4e20e 384 if (exists $options->{lazy} && $options->{lazy}) {
9edba990 385 (exists $options->{default} || defined $options->{builder} )
be05faea 386 || $class->throw_error("You cannot have lazy attribute ($name) without specifying a default value for it", data => $options);
f3c4e20e 387 }
26fbace8 388
9edba990 389 if ( $options->{required} && !( ( !exists $options->{init_arg} || defined $options->{init_arg} ) || exists $options->{default} || defined $options->{builder} ) ) {
be05faea 390 $class->throw_error("You cannot have a required attribute ($name) without a default, builder, or an init_arg", data => $options);
9edba990 391 }
392
78cd1d3b 393}
c0e30cf5 394
d500266f 395sub initialize_instance_slot {
ddd0ec20 396 my ($self, $meta_instance, $instance, $params) = @_;
d500266f 397 my $init_arg = $self->init_arg();
398 # try to fetch the init arg from the %params ...
ddd0ec20 399
26fbace8 400 my $val;
1ed0b94f 401 my $value_is_set;
625d571f 402 if ( defined($init_arg) and exists $params->{$init_arg}) {
d500266f 403 $val = $params->{$init_arg};
d03bd989 404 $value_is_set = 1;
d500266f 405 }
406 else {
407 # skip it if it's lazy
408 return if $self->is_lazy;
409 # and die if it's required and doesn't have a default value
be05faea 410 $self->throw_error("Attribute (" . $self->name . ") is required", object => $instance, data => $params)
26fbace8 411 if $self->is_required && !$self->has_default && !$self->has_builder;
ddd0ec20 412
1ed0b94f 413 # if nothing was in the %params, we can use the
414 # attribute's default value (if it has one)
415 if ($self->has_default) {
416 $val = $self->default($instance);
417 $value_is_set = 1;
d03bd989 418 }
a6c84c69 419 elsif ($self->has_builder) {
e606ae5f 420 $val = $self->_call_builder($instance);
421 $value_is_set = 1;
a0748c37 422 }
26fbace8 423 }
424
1ed0b94f 425 return unless $value_is_set;
426
9c9563c7 427 $val = $self->_coerce_and_verify( $val, $instance );
ddd0ec20 428
759e4e8f 429 $self->set_initial_value($instance, $val);
312e0f0c 430
431 if ( ref $val && $self->is_weak_ref ) {
32881f68 432 $self->_weaken_value($instance);
312e0f0c 433 }
d500266f 434}
435
e606ae5f 436sub _call_builder {
437 my ( $self, $instance ) = @_;
438
439 my $builder = $self->builder();
440
441 return $instance->$builder()
442 if $instance->can( $self->builder );
443
444 $self->throw_error( blessed($instance)
445 . " does not support builder method '"
446 . $self->builder
447 . "' for attribute '"
448 . $self->name
449 . "'",
450 object => $instance,
451 );
452}
453
d617b644 454## Slot management
9e93dd19 455
8abe9636 456# FIXME:
d03bd989 457# this duplicates too much code from
458# Class::MOP::Attribute, we need to
8abe9636 459# refactor these bits eventually.
460# - SL
461sub _set_initial_slot_value {
462 my ($self, $meta_instance, $instance, $value) = @_;
463
464 my $slot_name = $self->name;
465
466 return $meta_instance->set_slot_value($instance, $slot_name, $value)
467 unless $self->has_initializer;
468
469 my ($type_constraint, $can_coerce);
470 if ($self->has_type_constraint) {
471 $type_constraint = $self->type_constraint;
472 $can_coerce = ($self->should_coerce && $type_constraint->has_coercion);
473 }
474
475 my $callback = sub {
9c9563c7 476 my $val = $self->_coerce_and_verify( shift, $instance );;
477
8abe9636 478 $meta_instance->set_slot_value($instance, $slot_name, $val);
479 };
d03bd989 480
8abe9636 481 my $initializer = $self->initializer;
482
483 # most things will just want to set a value, so make it first arg
484 $instance->$initializer($value, $callback, $self);
485}
486
946289d1 487sub set_value {
b6af66f8 488 my ($self, $instance, @args) = @_;
489 my $value = $args[0];
26fbace8 490
946289d1 491 my $attr_name = $self->name;
26fbace8 492
b6af66f8 493 if ($self->is_required and not @args) {
be05faea 494 $self->throw_error("Attribute ($attr_name) is required", object => $instance);
946289d1 495 }
26fbace8 496
9c9563c7 497 $value = $self->_coerce_and_verify( $value, $instance );
26fbace8 498
3dda07f5 499 my @old;
500 if ( $self->has_trigger && $self->has_value($instance) ) {
501 @old = $self->get_value($instance, 'for trigger');
502 }
503
312e0f0c 504 $self->SUPER::set_value($instance, $value);
26fbace8 505
312e0f0c 506 if ( ref $value && $self->is_weak_ref ) {
32881f68 507 $self->_weaken_value($instance);
946289d1 508 }
26fbace8 509
946289d1 510 if ($self->has_trigger) {
3dda07f5 511 $self->trigger->($instance, $value, @old);
946289d1 512 }
513}
514
32881f68 515sub _weaken_value {
312e0f0c 516 my ( $self, $instance ) = @_;
517
32881f68 518 my $meta_instance = Class::MOP::Class->initialize( blessed($instance) )
519 ->get_meta_instance;
312e0f0c 520
521 $meta_instance->weaken_slot_value( $instance, $self->name );
522}
523
946289d1 524sub get_value {
3dda07f5 525 my ($self, $instance, $for_trigger) = @_;
26fbace8 526
946289d1 527 if ($self->is_lazy) {
8de73ff1 528 unless ($self->has_value($instance)) {
e606ae5f 529 my $value;
8de73ff1 530 if ($self->has_default) {
e606ae5f 531 $value = $self->default($instance);
3f11800d 532 } elsif ( $self->has_builder ) {
e606ae5f 533 $value = $self->_call_builder($instance);
534 }
9c9563c7 535
536 $value = $self->_coerce_and_verify( $value, $instance );
537
e606ae5f 538 $self->set_initial_value($instance, $value);
8de73ff1 539 }
946289d1 540 }
26fbace8 541
3dda07f5 542 if ( $self->should_auto_deref && ! $for_trigger ) {
26fbace8 543
946289d1 544 my $type_constraint = $self->type_constraint;
545
546 if ($type_constraint->is_a_type_of('ArrayRef')) {
547 my $rv = $self->SUPER::get_value($instance);
548 return unless defined $rv;
549 return wantarray ? @{ $rv } : $rv;
26fbace8 550 }
946289d1 551 elsif ($type_constraint->is_a_type_of('HashRef')) {
552 my $rv = $self->SUPER::get_value($instance);
553 return unless defined $rv;
554 return wantarray ? %{ $rv } : $rv;
26fbace8 555 }
946289d1 556 else {
46cb090f 557 $self->throw_error("Can not auto de-reference the type constraint '" . $type_constraint->name . "'", object => $instance, type_constraint => $type_constraint);
946289d1 558 }
26fbace8 559
946289d1 560 }
561 else {
26fbace8 562
946289d1 563 return $self->SUPER::get_value($instance);
26fbace8 564 }
946289d1 565}
a15dff8d 566
26fbace8 567## installing accessors
c0e30cf5 568
246bbeef 569sub accessor_metaclass { 'Moose::Meta::Method::Accessor' }
570
571sub install_accessors {
ae907ae0 572 my $self = shift;
246bbeef 573 $self->SUPER::install_accessors(@_);
574 $self->install_delegation if $self->has_handles;
28af3424 575 return;
576}
577
9340e346 578sub _check_associated_methods {
28af3424 579 my $self = shift;
86cf196b 580 unless (
0bbd378f 581 @{ $self->associated_methods }
86cf196b 582 || ($self->_is_metadata || '') eq 'bare'
583 ) {
584 Carp::cluck(
8f4450f3 585 'Attribute (' . $self->name . ') of class '
586 . $self->associated_class->name
587 . ' has no associated methods'
86cf196b 588 . ' (did you mean to provide an "is" argument?)'
589 . "\n"
590 )
591 }
e606ae5f 592}
26fbace8 593
3b6e2290 594sub _process_accessors {
595 my $self = shift;
596 my ($type, $accessor, $generate_as_inline_methods) = @_;
597 $accessor = (keys %$accessor)[0] if (ref($accessor)||'') eq 'HASH';
99541dfd 598 my $method = $self->associated_class->get_method($accessor);
599 if ($method && !$method->isa('Class::MOP::Method::Accessor')
600 && (!$self->definition_context
601 || $method->package_name eq $self->definition_context->{package})) {
3b6e2290 602 Carp::cluck(
1d18c898 603 "You are overwriting a locally defined method ($accessor) with "
3b6e2290 604 . "an accessor"
605 );
606 }
607 $self->SUPER::_process_accessors(@_);
e606ae5f 608}
26fbace8 609
e1d6f0a3 610sub remove_accessors {
611 my $self = shift;
612 $self->SUPER::remove_accessors(@_);
613 $self->remove_delegation if $self->has_handles;
614 return;
615}
616
e606ae5f 617sub install_delegation {
618 my $self = shift;
26fbace8 619
e606ae5f 620 # NOTE:
621 # Here we canonicalize the 'handles' option
622 # this will sort out any details and always
623 # return an hash of methods which we want
624 # to delagate to, see that method for details
625 my %handles = $self->_canonicalize_handles;
626
e606ae5f 627
628 # install the delegation ...
629 my $associated_class = $self->associated_class;
630 foreach my $handle (keys %handles) {
631 my $method_to_call = $handles{$handle};
632 my $class_name = $associated_class->name;
633 my $name = "${class_name}::${handle}";
26fbace8 634
452bac1b 635 (!$associated_class->has_method($handle))
cee532a1 636 || $self->throw_error("You cannot overwrite a locally defined method ($handle) with a delegation", method_name => $handle);
26fbace8 637
e606ae5f 638 # NOTE:
639 # handles is not allowed to delegate
640 # any of these methods, as they will
641 # override the ones in your class, which
642 # is almost certainly not what you want.
4fe78472 643
e606ae5f 644 # FIXME warn when $handle was explicitly specified, but not if the source is a regex or something
645 #cluck("Not delegating method '$handle' because it is a core method") and
646 next if $class_name->isa("Moose::Object") and $handle =~ /^BUILD|DEMOLISH$/ || Moose::Object->can($handle);
26fbace8 647
46f7e6a5 648 my $method = $self->_make_delegation_method($handle, $method_to_call);
a05f85c1 649
650 $self->associated_class->add_method($method->name, $method);
0bbd378f 651 $self->associate_method($method);
d03bd989 652 }
452bac1b 653}
654
e1d6f0a3 655sub remove_delegation {
656 my $self = shift;
657 my %handles = $self->_canonicalize_handles;
658 my $associated_class = $self->associated_class;
659 foreach my $handle (keys %handles) {
660 $self->associated_class->remove_method($handle);
661 }
662}
663
98aae381 664# private methods to help delegation ...
665
452bac1b 666sub _canonicalize_handles {
667 my $self = shift;
668 my $handles = $self->handles;
c84f324f 669 if (my $handle_type = ref($handles)) {
670 if ($handle_type eq 'HASH') {
671 return %{$handles};
672 }
673 elsif ($handle_type eq 'ARRAY') {
674 return map { $_ => $_ } @{$handles};
675 }
676 elsif ($handle_type eq 'Regexp') {
677 ($self->has_type_constraint)
0286711b 678 || $self->throw_error("Cannot delegate methods based on a Regexp without a type constraint (isa)", data => $handles);
26fbace8 679 return map { ($_ => $_) }
c84f324f 680 grep { /$handles/ } $self->_get_delegate_method_list;
681 }
682 elsif ($handle_type eq 'CODE') {
683 return $handles->($self, $self->_find_delegate_metaclass);
684 }
6cbf4a23 685 elsif (blessed($handles) && $handles->isa('Moose::Meta::TypeConstraint::DuckType')) {
686 return map { $_ => $_ } @{ $handles->methods };
687 }
c84f324f 688 else {
be05faea 689 $self->throw_error("Unable to canonicalize the 'handles' option with $handles", data => $handles);
c84f324f 690 }
452bac1b 691 }
692 else {
c8d9f1e2 693 Class::MOP::load_class($handles);
694 my $role_meta = Class::MOP::class_of($handles);
c84f324f 695
696 (blessed $role_meta && $role_meta->isa('Moose::Meta::Role'))
425ca605 697 || $self->throw_error("Unable to canonicalize the 'handles' option with $handles because its metaclass is not a Moose::Meta::Role", data => $handles);
d03bd989 698
a8547bc0 699 return map { $_ => $_ }
700 grep { $_ ne 'meta' } (
26fbace8 701 $role_meta->get_method_list,
b07a4e6d 702 map { $_->name } $role_meta->get_required_method_list,
a8547bc0 703 );
452bac1b 704 }
705}
706
707sub _find_delegate_metaclass {
708 my $self = shift;
98aae381 709 if (my $class = $self->_isa_metadata) {
9031e2c4 710 # we might be dealing with a non-Moose class,
711 # and need to make our own metaclass. if there's
712 # already a metaclass, it will be returned
452bac1b 713 return Moose::Meta::Class->initialize($class);
714 }
98aae381 715 elsif (my $role = $self->_does_metadata) {
91e6653b 716 return Class::MOP::class_of($role);
452bac1b 717 }
718 else {
be05faea 719 $self->throw_error("Cannot find delegate metaclass for attribute " . $self->name);
452bac1b 720 }
721}
722
723sub _get_delegate_method_list {
724 my $self = shift;
725 my $meta = $self->_find_delegate_metaclass;
726 if ($meta->isa('Class::MOP::Class')) {
e606ae5f 727 return map { $_->name } # NOTE: !never! delegate &meta
728 grep { $_->package_name ne 'Moose::Object' && $_->name ne 'meta' }
729 $meta->get_all_methods;
452bac1b 730 }
731 elsif ($meta->isa('Moose::Meta::Role')) {
26fbace8 732 return $meta->get_method_list;
452bac1b 733 }
734 else {
be05faea 735 $self->throw_error("Unable to recognize the delegate metaclass '$meta'", data => $meta);
452bac1b 736 }
737}
738
bd1226e2 739sub delegation_metaclass { 'Moose::Meta::Method::Delegation' }
740
a05f85c1 741sub _make_delegation_method {
46f7e6a5 742 my ( $self, $handle_name, $method_to_call ) = @_;
a05f85c1 743
3c573ca4 744 my @curried_arguments;
2de18801 745
3c573ca4 746 ($method_to_call, @curried_arguments) = @$method_to_call
2de18801 747 if 'ARRAY' eq ref($method_to_call);
748
bd1226e2 749 return $self->delegation_metaclass->new(
46f7e6a5 750 name => $handle_name,
751 package_name => $self->associated_class->name,
752 attribute => $self,
753 delegate_to_method => $method_to_call,
3c573ca4 754 curried_arguments => \@curried_arguments,
a05f85c1 755 );
756}
757
9c9563c7 758sub _coerce_and_verify {
759 my $self = shift;
760 my $val = shift;
761 my $instance = shift;
762
763 return $val unless $self->has_type_constraint;
764
765 my $type_constraint = $self->type_constraint;
766 if ($self->should_coerce && $type_constraint->has_coercion) {
767 $val = $type_constraint->coerce($val);
768 }
769
770 $self->verify_against_type_constraint($val, instance => $instance);
771
772 return $val;
773}
774
5755a9b2 775sub verify_against_type_constraint {
2b86e02b 776 my $self = shift;
777 my $val = shift;
778
779 return 1 if !$self->has_type_constraint;
780
781 my $type_constraint = $self->type_constraint;
782
783 $type_constraint->check($val)
784 || $self->throw_error("Attribute ("
785 . $self->name
786 . ") does not pass the type constraint because: "
787 . $type_constraint->get_message($val), data => $val, @_);
788}
789
21f1e231 790package Moose::Meta::Attribute::Custom::Moose;
791sub register_implementation { 'Moose::Meta::Attribute' }
792
c0e30cf5 7931;
794
795__END__
796
797=pod
798
799=head1 NAME
800
6ba6d68c 801Moose::Meta::Attribute - The Moose attribute metaclass
c0e30cf5 802
803=head1 DESCRIPTION
804
93a708fd 805This class is a subclass of L<Class::MOP::Attribute> that provides
806additional Moose-specific functionality.
6ba6d68c 807
7854b409 808To really understand this class, you will need to start with the
809L<Class::MOP::Attribute> documentation. This class can be understood
810as a set of additional features on top of the basic feature provided
811by that parent class.
e522431d 812
d4b1449e 813=head1 INHERITANCE
814
815C<Moose::Meta::Attribute> is a subclass of L<Class::MOP::Attribute>.
816
c0e30cf5 817=head1 METHODS
818
93a708fd 819Many of the documented below override methods in
820L<Class::MOP::Attribute> and add Moose specific features.
6ba6d68c 821
93a708fd 822=head2 Creation
6ba6d68c 823
c0e30cf5 824=over 4
825
93a708fd 826=item B<< Moose::Meta::Attribute->new(%options) >>
c0e30cf5 827
93a708fd 828This method overrides the L<Class::MOP::Attribute> constructor.
c32c2c61 829
93a708fd 830Many of the options below are described in more detail in the
831L<Moose::Manual::Attributes> document.
6e2840b7 832
93a708fd 833It adds the following options to the constructor:
d500266f 834
93a708fd 835=over 8
452bac1b 836
996b8c8d 837=item * is => 'ro', 'rw', 'bare'
e1d6f0a3 838
93a708fd 839This provides a shorthand for specifying the C<reader>, C<writer>, or
840C<accessor> names. If the attribute is read-only ('ro') then it will
841have a C<reader> method with the same attribute as the name.
e606ae5f 842
93a708fd 843If it is read-write ('rw') then it will have an C<accessor> method
844with the same name. If you provide an explicit C<writer> for a
845read-write attribute, then you will have a C<reader> with the same
846name as the attribute, and a C<writer> with the name you provided.
e1d6f0a3 847
996b8c8d 848Use 'bare' when you are deliberately not installing any methods
849(accessor, reader, etc.) associated with this attribute; otherwise,
850Moose will issue a deprecation warning when this attribute is added to a
9340e346 851metaclass.
996b8c8d 852
93a708fd 853=item * isa => $type
39b3bc94 854
93a708fd 855This option accepts a type. The type can be a string, which should be
856a type name. If the type name is unknown, it is assumed to be a class
857name.
858
859This option can also accept a L<Moose::Meta::TypeConstraint> object.
860
861If you I<also> provide a C<does> option, then your C<isa> option must
862be a class name, and that class must do the role specified with
863C<does>.
864
865=item * does => $role
866
867This is short-hand for saying that the attribute's type must be an
868object which does the named role.
869
870=item * coerce => $bool
871
872This option is only valid for objects with a type constraint
873(C<isa>). If this is true, then coercions will be applied whenever
874this attribute is set.
875
876You can make both this and the C<weak_ref> option true.
877
878=item * trigger => $sub
879
880This option accepts a subroutine reference, which will be called after
881the attribute is set.
882
883=item * required => $bool
884
885An attribute which is required must be provided to the constructor. An
886attribute which is required can also have a C<default> or C<builder>,
36741534 887which will satisfy its required-ness.
93a708fd 888
889A required attribute must have a C<default>, C<builder> or a
890non-C<undef> C<init_arg>
891
892=item * lazy => $bool
893
894A lazy attribute must have a C<default> or C<builder>. When an
895attribute is lazy, the default value will not be calculated until the
896attribute is read.
897
898=item * weak_ref => $bool
899
900If this is true, the attribute's value will be stored as a weak
901reference.
902
903=item * auto_deref => $bool
904
905If this is true, then the reader will dereference the value when it is
906called. The attribute must have a type constraint which defines the
907attribute as an array or hash reference.
908
909=item * lazy_build => $bool
910
911Setting this to true makes the attribute lazy and provides a number of
912default methods.
913
914 has 'size' => (
915 is => 'ro',
916 lazy_build => 1,
917 );
918
919is equivalent to this:
920
921 has 'size' => (
922 is => 'ro',
923 lazy => 1,
924 builder => '_build_size',
925 clearer => 'clear_size',
926 predicate => 'has_size',
927 );
928
929=item * documentation
930
931An arbitrary string that can be retrieved later by calling C<<
932$attr->documentation >>.
933
934=back
935
936=item B<< $attr->clone(%options) >>
937
938This creates a new attribute based on attribute being cloned. You must
939supply a C<name> option to provide a new name for the attribute.
940
941The C<%options> can only specify options handled by
942L<Class::MOP::Attribute>.
943
36741534 944=back
945
93a708fd 946=head2 Value management
947
36741534 948=over 4
949
93a708fd 950=item B<< $attr->initialize_instance_slot($meta_instance, $instance, $params) >>
951
952This method is used internally to initialize the attribute's slot in
953the object C<$instance>.
954
955This overrides the L<Class::MOP::Attribute> method to handle lazy
956attributes, weak references, and type constraints.
bd1226e2 957
946289d1 958=item B<get_value>
959
960=item B<set_value>
961
6549b0d1 962 eval { $point->meta->get_attribute('x')->set_value($point, 'forty-two') };
bcbaa845 963 if($@) {
964 print "Oops: $@\n";
965 }
966
6549b0d1 967I<Attribute (x) does not pass the type constraint (Int) with 'forty-two'>
bcbaa845 968
969Before setting the value, a check is made on the type constraint of
970the attribute, if it has one, to see if the value passes it. If the
46cb090f 971value fails to pass, the set operation dies with a L<throw_error>.
bcbaa845 972
973Any coercion to convert values is done before checking the type constraint.
974
975To check a value against a type constraint before setting it, fetch the
ec00fa75 976attribute instance using L<Class::MOP::Class/find_attribute_by_name>,
bcbaa845 977fetch the type_constraint from the attribute using L<Moose::Meta::Attribute/type_constraint>
e606ae5f 978and call L<Moose::Meta::TypeConstraint/check>. See L<Moose::Cookbook::Basics::Recipe4>
bcbaa845 979for an example.
980
a15dff8d 981=back
982
93a708fd 983=head2 Attribute Accessor generation
6ba6d68c 984
a15dff8d 985=over 4
986
93a708fd 987=item B<< $attr->install_accessors >>
be05faea 988
93a708fd 989This method overrides the parent to also install delegation methods.
be05faea 990
7a582117 991If, after installing all methods, the attribute object has no associated
992methods, it throws an error unless C<< is => 'bare' >> was passed to the
993attribute constructor. (Trying to add an attribute that has no associated
994methods is almost always an error.)
995
36741534 996=item B<< $attr->remove_accessors >>
d5c30e52 997
93a708fd 998This method overrides the parent to also remove delegation methods.
d5c30e52 999
93a708fd 1000=item B<< $attr->install_delegation >>
1001
1002This method adds its delegation methods to the attribute's associated
1003class, if it has any to add.
1004
1005=item B<< $attr->remove_delegation >>
1006
1007This method remove its delegation methods from the attribute's
1008associated class.
d5c30e52 1009
93a708fd 1010=item B<< $attr->accessor_metaclass >>
9e93dd19 1011
93a708fd 1012Returns the accessor metaclass name, which defaults to
1013L<Moose::Meta::Method::Accessor>.
1014
1015=item B<< $attr->delegation_metaclass >>
1016
1017Returns the delegation metaclass name, which defaults to
1018L<Moose::Meta::Method::Delegation>.
1019
1020=back
1021
1022=head2 Additional Moose features
1023
1024These methods are not found in the superclass. They support features
1025provided by Moose.
1026
36741534 1027=over 4
1028
93a708fd 1029=item B<< $attr->does($role) >>
1030
1031This indicates whether the I<attribute itself> does the given
36741534 1032role. The role can be given as a full class name, or as a resolvable
93a708fd 1033trait name.
1034
1035Note that this checks the attribute itself, not its type constraint,
1036so it is checking the attribute's metaclass and any traits applied to
1037the attribute.
1038
1039=item B<< Moose::Meta::Class->interpolate_class_and_new($name, %options) >>
1040
1041This is an alternate constructor that handles the C<metaclass> and
1042C<traits> options.
9e93dd19 1043
93a708fd 1044Effectively, this method is a factory that finds or creates the
36741534 1045appropriate class for the given C<metaclass> and/or C<traits>.
e606ae5f 1046
93a708fd 1047Once it has the appropriate class, it will call C<< $class->new($name,
1048%options) >> on that class.
e606ae5f 1049
93a708fd 1050=item B<< $attr->clone_and_inherit_options(%options) >>
a15dff8d 1051
93a708fd 1052This method supports the C<has '+foo'> feature. It does various bits
1053of processing on the supplied C<%options> before ultimately calling
1054the C<clone> method.
6ba6d68c 1055
93a708fd 1056One of its main tasks is to make sure that the C<%options> provided
1057only includes the options returned by the
1058C<legal_options_for_inheritance> method.
a15dff8d 1059
93a708fd 1060=item B<< $attr->legal_options_for_inheritance >>
a15dff8d 1061
93a708fd 1062This returns a whitelist of options that can be overridden in a
1063subclass's attribute definition.
2b86e02b 1064
93a708fd 1065This exists to allow a custom metaclass to change or add to the list
1066of options which can be changed.
2b86e02b 1067
93a708fd 1068=item B<< $attr->type_constraint >>
452bac1b 1069
93a708fd 1070Returns the L<Moose::Meta::TypeConstraint> object for this attribute,
1071if it has one.
452bac1b 1072
93a708fd 1073=item B<< $attr->has_type_constraint >>
452bac1b 1074
93a708fd 1075Returns true if this attribute has a type constraint.
452bac1b 1076
93a708fd 1077=item B<< $attr->verify_against_type_constraint($value) >>
a15dff8d 1078
93a708fd 1079Given a value, this method returns true if the value is valid for the
1080attribute's type constraint. If the value is not valid, it throws an
1081error.
4b598ea3 1082
93a708fd 1083=item B<< $attr->handles >>
ca01a97b 1084
93a708fd 1085This returns the value of the C<handles> option passed to the
1086constructor.
ca01a97b 1087
93a708fd 1088=item B<< $attr->has_handles >>
ca01a97b 1089
93a708fd 1090Returns true if this attribute performs delegation.
ca01a97b 1091
93a708fd 1092=item B<< $attr->is_weak_ref >>
26fbace8 1093
93a708fd 1094Returns true if this attribute stores its value as a weak reference.
26fbace8 1095
93a708fd 1096=item B<< $attr->is_required >>
26fbace8 1097
93a708fd 1098Returns true if this attribute is required to have a value.
26fbace8 1099
93a708fd 1100=item B<< $attr->is_lazy >>
58f85113 1101
93a708fd 1102Returns true if this attribute is lazy.
26fbace8 1103
93a708fd 1104=item B<< $attr->is_lazy_build >>
ca01a97b 1105
93a708fd 1106Returns true if the C<lazy_build> option was true when passed to the
1107constructor.
4b598ea3 1108
93a708fd 1109=item B<< $attr->should_coerce >>
6ba6d68c 1110
93a708fd 1111Returns true if the C<coerce> option passed to the constructor was
1112true.
536f0b17 1113
93a708fd 1114=item B<< $attr->should_auto_deref >>
536f0b17 1115
93a708fd 1116Returns true if the C<auto_deref> option passed to the constructor was
1117true.
536f0b17 1118
93a708fd 1119=item B<< $attr->trigger >>
8c9d74e7 1120
93a708fd 1121This is the subroutine reference that was in the C<trigger> option
1122passed to the constructor, if any.
02a0fb52 1123
36741534 1124=item B<< $attr->has_trigger >>
8c9d74e7 1125
93a708fd 1126Returns true if this attribute has a trigger set.
02a0fb52 1127
93a708fd 1128=item B<< $attr->documentation >>
ddbdc0cb 1129
93a708fd 1130Returns the value that was in the C<documentation> option passed to
1131the constructor, if any.
ddbdc0cb 1132
93a708fd 1133=item B<< $attr->has_documentation >>
ddbdc0cb 1134
93a708fd 1135Returns true if this attribute has any documentation.
ddbdc0cb 1136
93a708fd 1137=item B<< $attr->applied_traits >>
88f23977 1138
93a708fd 1139This returns an array reference of all the traits which were applied
1140to this attribute. If none were applied, this returns C<undef>.
88f23977 1141
93a708fd 1142=item B<< $attr->has_applied_traits >>
88f23977 1143
93a708fd 1144Returns true if this attribute has any traits applied.
88f23977 1145
c0e30cf5 1146=back
1147
1148=head1 BUGS
1149
26fbace8 1150All complex software has bugs lurking in it, and this module is no
c0e30cf5 1151exception. If you find a bug please either email me, or add the bug
1152to cpan-RT.
1153
c0e30cf5 1154=head1 AUTHOR
1155
1156Stevan Little E<lt>stevan@iinteractive.comE<gt>
1157
98aae381 1158Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
1159
c0e30cf5 1160=head1 COPYRIGHT AND LICENSE
1161
2840a3b2 1162Copyright 2006-2009 by Infinity Interactive, Inc.
c0e30cf5 1163
1164L<http://www.iinteractive.com>
1165
1166This library is free software; you can redistribute it and/or modify
26fbace8 1167it under the same terms as Perl itself.
c0e30cf5 1168
8a7a9c53 1169=cut