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