Checking in changes prior to tagging of version 0.50_03. Changelog diff is:
[gitmo/Mouse.git] / lib / Mouse / Meta / Attribute.pm
CommitLineData
306290e8 1package Mouse::Meta::Attribute;
bc69ee88 2use Mouse::Util qw(:meta); # enables strict and warnings
c3398f5b 3
2efc0af1 4use Carp ();
2efc0af1 5
684db121 6use Mouse::Meta::TypeConstraint;
d7d8d49b 7
7d2a0f10 8my %valid_options = map { $_ => undef } (
9 'accessor',
10 'auto_deref',
11 'builder',
12 'clearer',
13 'coerce',
14 'default',
15 'documentation',
16 'does',
17 'handles',
18 'init_arg',
19 'is',
20 'isa',
21 'lazy',
22 'lazy_build',
23 'name',
24 'predicate',
25 'reader',
26 'required',
27 'traits',
28 'trigger',
29 'type_constraint',
30 'weak_ref',
31 'writer',
32
33 # internally used
34 'associated_class',
35 'associated_methods',
36
37 # Moose defines, but Mouse doesn't
38 #'definition_context',
39 #'initializer',
40 #'insertion_order',
41
42 # special case for AttributeHelpers
43 'provides',
44 'curries',
45);
87ca293b 46
47sub new {
48 my $class = shift;
49 my $name = shift;
50
2053291d 51 my $args = $class->Mouse::Object::BUILDARGS(@_);
ba1f50a2 52
53 # XXX: for backward compatibility (with method modifiers)
54 if($class->can('canonicalize_args') != \&canonicalize_args){
2053291d 55 %{$args} = $class->canonicalize_args($name, %{$args});
ba1f50a2 56 }
57
2053291d 58 $class->_process_options($name, $args);
87ca293b 59
2053291d 60 $args->{name} = $name;
87ca293b 61
7d2a0f10 62 # check options
63 # (1) known by core
64 my @bad = grep{ !exists $valid_options{$_} } keys %{$args};
65
66 # (2) known by subclasses
67 if(@bad && $class ne __PACKAGE__){
68 my %valid_attrs = (
69 map { $_ => undef }
70 grep { defined }
71 map { $_->init_arg() }
72 $class->meta->get_all_attributes()
73 );
74 @bad = grep{ !exists $valid_attrs{$_} } @bad;
75 }
76
77 # (3) bad options found
78 if(@bad){
79 @bad = sort @bad;
80 Carp::cluck("Found unknown argument(s) passed to '$name' attribute constructor in '$class': @bad");
81 }
82
2053291d 83 my $self = bless $args, $class;
2efc0af1 84
1b9e472d 85 # extra attributes
86 if($class ne __PACKAGE__){
2053291d 87 $class->meta->_initialize_object($self, $args);
90fe520e 88 }
c3398f5b 89
926290ac 90 return $self;
c3398f5b 91}
92
43165725 93sub has_read_method { $_[0]->has_reader || $_[0]->has_accessor }
94sub has_write_method { $_[0]->has_writer || $_[0]->has_accessor }
1b9e472d 95
df77fd72 96sub _create_args { # DEPRECATED
1bfebf5f 97 $_[0]->{_create_args} = $_[1] if @_ > 1;
98 $_[0]->{_create_args}
99}
100
87ca293b 101sub interpolate_class{
8cf51b82 102 my($class, $args) = @_;
c3398f5b 103
1b9e472d 104 if(my $metaclass = delete $args->{metaclass}){
105 $class = Mouse::Util::resolve_metaclass_alias( Attribute => $metaclass );
106 }
1bfebf5f 107
87ca293b 108 my @traits;
1b9e472d 109 if(my $traits_ref = delete $args->{traits}){
87ca293b 110
f3f04eed 111 for (my $i = 0; $i < @{$traits_ref}; $i++) {
112 my $trait = Mouse::Util::resolve_metaclass_alias(Attribute => $traits_ref->[$i], trait => 1);
b2500191 113
f3f04eed 114 next if $class->does($trait);
74be9f76 115
f3f04eed 116 push @traits, $trait;
1b9e472d 117
f3f04eed 118 # are there options?
119 push @traits, $traits_ref->[++$i]
120 if ref($traits_ref->[$i+1]);
121 }
c3398f5b 122
1b9e472d 123 if (@traits) {
124 $class = Mouse::Meta::Class->create_anon_class(
125 superclasses => [ $class ],
126 roles => \@traits,
127 cache => 1,
128 )->name;
1b9e472d 129 }
74be9f76 130 }
131
87ca293b 132 return( $class, @traits );
1b9e472d 133}
134
df77fd72 135sub canonicalize_args{ # DEPRECATED
1b9e472d 136 my ($self, $name, %args) = @_;
137
138 Carp::cluck("$self->canonicalize_args has been deprecated."
da23cd4a 139 . "Use \$self->_process_options instead.");
1b9e472d 140
141 return %args;
142}
143
ce5920b7 144sub create { # DEPRECATED
1b9e472d 145 my ($self, $class, $name, %args) = @_;
146
147 Carp::cluck("$self->create has been deprecated."
da23cd4a 148 . "Use \$meta->add_attribute and \$attr->install_accessors instead.");
1b9e472d 149
150 # noop
151 return $self;
c3398f5b 152}
153
ffbbf459 154sub _coerce_and_verify {
155 my($self, $value, $instance) = @_;
156
157 my $type_constraint = $self->{type_constraint};
4331a3f9 158 return $value if !defined $type_constraint;
ffbbf459 159
160 if ($self->should_coerce && $type_constraint->has_coercion) {
161 $value = $type_constraint->coerce($value);
162 }
163
ffbbf459 164 $self->verify_against_type_constraint($value);
165
166 return $value;
167}
168
20e25eb9 169sub verify_against_type_constraint {
f55f60dd 170 my ($self, $value) = @_;
5aa30ced 171
ffbbf459 172 my $type_constraint = $self->{type_constraint};
4331a3f9 173 return 1 if !$type_constraint;
ffbbf459 174 return 1 if $type_constraint->check($value);
5aa30ced 175
da23cd4a 176 $self->_throw_type_constraint_error($value, $type_constraint);
b3b74cc6 177}
5aa30ced 178
da23cd4a 179sub _throw_type_constraint_error {
2a96ea85 180 my($self, $value, $type) = @_;
181
182 $self->throw_error(
183 sprintf q{Attribute (%s) does not pass the type constraint because: %s},
184 $self->name,
185 $type->get_message($value),
186 );
5aa30ced 187}
188
1b9e472d 189sub clone_and_inherit_options{
2053291d 190 my $self = shift;
191 my $args = $self->Mouse::Object::BUILDARGS(@_);
8cf51b82 192
2053291d 193 my($attribute_class, @traits) = ref($self)->interpolate_class($args);
1b9e472d 194
2053291d 195 $args->{traits} = \@traits if @traits;
4f41d79b 196 # do not inherit the 'handles' attribute
197 foreach my $name(keys %{$self}){
2053291d 198 if(!exists $args->{$name} && $name ne 'handles'){
199 $args->{$name} = $self->{$name};
4f41d79b 200 }
201 }
7d2a0f10 202
203 # remove temporary caches
204 foreach my $attr(keys %{$args}){
205 if($attr =~ /\A _/xms){
206 delete $args->{$attr};
207 }
208 }
209
2053291d 210 return $attribute_class->new($self->name, $args);
1b9e472d 211}
212
df77fd72 213sub clone_parent { # DEPRECATED
1bfebf5f 214 my $self = shift;
215 my $class = shift;
216 my $name = shift;
217 my %args = ($self->get_parent_args($class, $name), @_);
218
1b9e472d 219 Carp::cluck("$self->clone_parent has been deprecated."
da23cd4a 220 . "Use \$meta->add_attribute and \$attr->install_accessors instead.");
1b9e472d 221
7ca5c5fb 222 $self->clone_and_inherited_args($class, $name, %args);
1bfebf5f 223}
224
df77fd72 225sub get_parent_args { # DEPRECATED
1bfebf5f 226 my $self = shift;
227 my $class = shift;
228 my $name = shift;
229
724c77c0 230 for my $super ($class->linearized_isa) {
bb733405 231 my $super_attr = $super->can("meta") && $super->meta->get_attribute($name)
1bfebf5f 232 or next;
233 return %{ $super_attr->_create_args };
234 }
235
fce211ae 236 $self->throw_error("Could not find an attribute by the name of '$name' to inherit from");
237}
238
2a464664 239
0126c27c 240sub get_read_method {
751de1a1 241 return $_[0]->reader || $_[0]->accessor
df77fd72 242}
0126c27c 243sub get_write_method {
751de1a1 244 return $_[0]->writer || $_[0]->accessor
245}
246
247sub _get_accessor_method_ref {
248 my($self, $type, $generator) = @_;
249
250 my $metaclass = $self->associated_class
251 || $self->throw_error('No asocciated class for ' . $self->name);
252
253 my $accessor = $self->$type();
254 if($accessor){
255 return $metaclass->get_method_body($accessor);
256 }
257 else{
258 return $self->accessor_metaclass->$generator($self, $metaclass);
259 }
df77fd72 260}
2a464664 261
262sub get_read_method_ref{
263 my($self) = @_;
751de1a1 264 return $self->{_read_method_ref} ||= $self->_get_accessor_method_ref('get_read_method', '_generate_reader');
2a464664 265}
266
267sub get_write_method_ref{
268 my($self) = @_;
751de1a1 269 return $self->{_write_method_ref} ||= $self->_get_accessor_method_ref('get_write_method', '_generate_writer');
270}
2a464664 271
751de1a1 272sub set_value {
273 my($self, $object, $value) = @_;
274 return $self->get_write_method_ref()->($object, $value);
275}
276
277sub get_value {
278 my($self, $object) = @_;
279 return $self->get_read_method_ref()->($object);
2a464664 280}
281
751de1a1 282sub has_value {
283 my($self, $object) = @_;
060f9228 284 my $accessor_ref = $self->{_predicate_ref}
751de1a1 285 ||= $self->_get_accessor_method_ref('predicate', '_generate_predicate');
286
060f9228 287 return $accessor_ref->($object);
751de1a1 288}
289
290sub clear_value {
291 my($self, $object) = @_;
060f9228 292 my $accessor_ref = $self->{_crealer_ref}
751de1a1 293 ||= $self->_get_accessor_method_ref('clearer', '_generate_clearer');
294
060f9228 295 return $accessor_ref->($object);
751de1a1 296}
297
298
04493075 299sub associate_method{
e5e22afd 300 my ($attribute, $method_name) = @_;
04493075 301 $attribute->{associated_methods}++;
302 return;
303}
304
1b9e472d 305sub install_accessors{
306 my($attribute) = @_;
307
93540011 308 my $metaclass = $attribute->associated_class;
4ab51fb0 309 my $accessor_class = $attribute->accessor_metaclass;
1b9e472d 310
4ab51fb0 311 foreach my $type(qw(accessor reader writer predicate clearer)){
1b9e472d 312 if(exists $attribute->{$type}){
4ab51fb0 313 my $generator = '_generate_' . $type;
314 my $code = $accessor_class->$generator($attribute, $metaclass);
315 $metaclass->add_method($attribute->{$type} => $code);
e5e22afd 316 $attribute->associate_method($attribute->{$type});
4ab51fb0 317 }
318 }
7ca5c5fb 319
4ab51fb0 320 # install delegation
321 if(exists $attribute->{handles}){
322 my %handles = $attribute->_canonicalize_handles($attribute->{handles});
feaa7084 323
cbb81058 324 while(my($handle, $method_to_call) = each %handles){
325 $metaclass->add_method($handle =>
326 $attribute->_make_delegation_method(
327 $handle, $method_to_call));
4ab51fb0 328
cbb81058 329 $attribute->associate_method($handle);
1b9e472d 330 }
331 }
332
333 if($attribute->can('create') != \&create){
7ca5c5fb 334 # backword compatibility
1b9e472d 335 $attribute->create($metaclass, $attribute->name, %{$attribute});
336 }
337
d503a4f3 338 if(!$attribute->{associated_methods} && ($attribute->{is} || '') ne 'bare'){
339 Carp::cluck(
340 'Attribute (' . $attribute->name . ') of class ' . $metaclass->name
341 . ' has no associated methods (did you mean to provide an "is" argument?)');
342 }
343
1b9e472d 344 return;
345}
346
cbb81058 347sub delegation_metaclass() { 'Mouse::Meta::Method::Delegation' }
348
349sub _canonicalize_handles {
350 my($self, $handles) = @_;
351
352 if (ref($handles) eq 'HASH') {
353 return %$handles;
354 }
355 elsif (ref($handles) eq 'ARRAY') {
356 return map { $_ => $_ } @$handles;
357 }
7bc01428 358 elsif ( ref($handles) eq 'CODE' ) {
359 my $class_or_role = ( $self->{isa} || $self->{does} )
360 || $self->throw_error( "Cannot find delegate metaclass for attribute " . $self->name );
361 return $handles->( $self, Mouse::Meta::Class->initialize("$class_or_role"));
362 }
cbb81058 363 elsif (ref($handles) eq 'Regexp') {
364 my $class_or_role = ($self->{isa} || $self->{does})
365 || $self->throw_error("Cannot delegate methods based on a Regexp without a type constraint (isa)");
366
367 my $meta = Mouse::Meta::Class->initialize("$class_or_role"); # "" for stringify
368 return map { $_ => $_ }
369 grep { !Mouse::Object->can($_) && $_ =~ $handles }
370 Mouse::Util::is_a_metarole($meta)
371 ? $meta->get_method_list
372 : $meta->get_all_method_names;
373 }
374 else {
375 $self->throw_error("Unable to canonicalize the 'handles' option with $handles");
376 }
377}
378
379sub _make_delegation_method {
380 my($self, $handle, $method_to_call) = @_;
381 my $delegator = $self->delegation_metaclass;
382 Mouse::Util::load_class($delegator);
383
21ee5bbb 384 return $delegator->_generate_delegation($self, $handle, $method_to_call);
cbb81058 385}
386
fce211ae 387sub throw_error{
388 my $self = shift;
389
390 my $metaclass = (ref $self && $self->associated_class) || 'Mouse::Meta::Class';
391 $metaclass->throw_error(@_, depth => 1);
1bfebf5f 392}
393
c3398f5b 3941;
c3398f5b 395__END__
396
397=head1 NAME
398
bedd575c 399Mouse::Meta::Attribute - The Mouse attribute metaclass
c3398f5b 400
a25ca8d6 401=head1 VERSION
402
4bc73e47 403This document describes Mouse version 0.50_03
a25ca8d6 404
c3398f5b 405=head1 METHODS
406
1820fffe 407=head2 C<< new(%options) -> Mouse::Meta::Attribute >>
c3398f5b 408
306290e8 409Instantiates a new Mouse::Meta::Attribute. Does nothing else.
c3398f5b 410
1820fffe 411It adds the following options to the constructor:
c3398f5b 412
1820fffe 413=over 4
c3398f5b 414
612d3e1a 415=item C<< is => 'ro', 'rw', 'bare' >>
c3398f5b 416
1820fffe 417This provides a shorthand for specifying the C<reader>, C<writer>, or
418C<accessor> names. If the attribute is read-only ('ro') then it will
419have a C<reader> method with the same attribute as the name.
c3398f5b 420
1820fffe 421If it is read-write ('rw') then it will have an C<accessor> method
422with the same name. If you provide an explicit C<writer> for a
423read-write attribute, then you will have a C<reader> with the same
424name as the attribute, and a C<writer> with the name you provided.
c3398f5b 425
1820fffe 426Use 'bare' when you are deliberately not installing any methods
427(accessor, reader, etc.) associated with this attribute; otherwise,
428Moose will issue a deprecation warning when this attribute is added to a
429metaclass.
c3398f5b 430
612d3e1a 431=item C<< isa => Type >>
ab27a55e 432
1820fffe 433This option accepts a type. The type can be a string, which should be
434a type name. If the type name is unknown, it is assumed to be a class
435name.
ab27a55e 436
1820fffe 437This option can also accept a L<Moose::Meta::TypeConstraint> object.
ab27a55e 438
1820fffe 439If you I<also> provide a C<does> option, then your C<isa> option must
440be a class name, and that class must do the role specified with
441C<does>.
ab27a55e 442
612d3e1a 443=item C<< does => Role >>
ab27a55e 444
1820fffe 445This is short-hand for saying that the attribute's type must be an
446object which does the named role.
c3398f5b 447
1820fffe 448B<This option is not yet supported.>
c3398f5b 449
612d3e1a 450=item C<< coerce => Bool >>
ab27a55e 451
1820fffe 452This option is only valid for objects with a type constraint
453(C<isa>). If this is true, then coercions will be applied whenever
454this attribute is set.
c3398f5b 455
1820fffe 456You can make both this and the C<weak_ref> option true.
c3398f5b 457
612d3e1a 458=item C<< trigger => CodeRef >>
ab27a55e 459
1820fffe 460This option accepts a subroutine reference, which will be called after
461the attribute is set.
ab27a55e 462
612d3e1a 463=item C<< required => Bool >>
ab27a55e 464
1820fffe 465An attribute which is required must be provided to the constructor. An
466attribute which is required can also have a C<default> or C<builder>,
467which will satisfy its required-ness.
ab27a55e 468
1820fffe 469A required attribute must have a C<default>, C<builder> or a
470non-C<undef> C<init_arg>
ab27a55e 471
612d3e1a 472=item C<< lazy => Bool >>
ab27a55e 473
1820fffe 474A lazy attribute must have a C<default> or C<builder>. When an
475attribute is lazy, the default value will not be calculated until the
476attribute is read.
93f08899 477
612d3e1a 478=item C<< weak_ref => Bool >>
0fff36e6 479
1820fffe 480If this is true, the attribute's value will be stored as a weak
481reference.
c3398f5b 482
612d3e1a 483=item C<< auto_deref => Bool >>
fb706f5c 484
1820fffe 485If this is true, then the reader will dereference the value when it is
486called. The attribute must have a type constraint which defines the
487attribute as an array or hash reference.
488
612d3e1a 489=item C<< lazy_build => Bool >>
1820fffe 490
491Setting this to true makes the attribute lazy and provides a number of
492default methods.
fb706f5c 493
1820fffe 494 has 'size' => (
495 is => 'ro',
496 lazy_build => 1,
497 );
93d190e0 498
1820fffe 499is equivalent to this:
93d190e0 500
1820fffe 501 has 'size' => (
502 is => 'ro',
503 lazy => 1,
504 builder => '_build_size',
505 clearer => 'clear_size',
506 predicate => 'has_size',
507 );
93d190e0 508
1820fffe 509=back
510
e5e22afd 511=head2 C<< associate_method(MethodName) >>
31c5194b 512
513Associates a method with the attribute. Typically, this is called internally
514when an attribute generates its accessors.
515
e5e22afd 516Currently the argument I<MethodName> is ignored in Mouse.
31c5194b 517
1820fffe 518=head2 C<< verify_against_type_constraint(Item) -> TRUE | ERROR >>
519
520Checks that the given value passes this attribute's type constraint. Returns C<true>
521on success, otherwise C<confess>es.
93d190e0 522
1820fffe 523=head2 C<< clone_and_inherit_options(options) -> Mouse::Meta::Attribute >>
f7b11a21 524
612d3e1a 525Creates a new attribute in the owner class, inheriting options from parent classes.
f7b11a21 526Accessors and helper methods are installed. Some error checking is done.
527
9ae9702e 528=head2 C<< get_read_method_ref >>
529
530=head2 C<< get_write_method_ref >>
531
532Returns the subroutine reference of a method suitable for reading or
533writing the attribute's value in the associated class. These methods
534always return a subroutine reference, regardless of whether or not the
df77fd72 535attribute is read- or write-only.
536
1820fffe 537=head1 SEE ALSO
f7b11a21 538
1820fffe 539L<Moose::Meta::Attribute>
f7b11a21 540
31c5194b 541L<Class::MOP::Attribute>
542
c3398f5b 543=cut
544