Fix t/010_basics/007_always_strict_warnings.t; Now Mouse::Exporter exists.
[gitmo/Mouse.git] / lib / Mouse / Meta / Attribute.pm
CommitLineData
306290e8 1package Mouse::Meta::Attribute;
c3398f5b 2use strict;
3use warnings;
4
2efc0af1 5use Carp ();
2efc0af1 6
53875581 7use Mouse::Util qw(:meta);
6d28c5cf 8
684db121 9use Mouse::Meta::TypeConstraint;
90fe520e 10use Mouse::Meta::Method::Accessor;
c3398f5b 11
4ab51fb0 12
87ca293b 13sub _process_options{
14 my($class, $name, $args) = @_;
c3398f5b 15
04493075 16
17 # XXX: for backward compatibility (with method modifiers)
18 if($class->can('canonicalize_args') != \&canonicalize_args){
19 %{$args} = $class->canonicalize_args($name, %{$args});
20 }
21
2efc0af1 22 # taken from Class::MOP::Attribute::new
23
24 defined($name)
25 or $class->throw_error('You must provide a name for the attribute');
2e7e86c6 26
1b9e472d 27 if(!exists $args->{init_arg}){
28 $args->{init_arg} = $name;
2efc0af1 29 }
30
31 # 'required' requires eigher 'init_arg', 'builder', or 'default'
1b9e472d 32 my $can_be_required = defined( $args->{init_arg} );
2efc0af1 33
1b9e472d 34 if(exists $args->{builder}){
c6d8f5ca 35 # XXX:
36 # Moose refuses a CODE ref builder, but Mouse doesn't for backward compatibility
37 # This feature will be changed in a future. (gfx)
121acb8a 38 $class->throw_error('builder must be a defined scalar value which is a method name')
c6d8f5ca 39 #if ref $args->{builder} || !defined $args->{builder};
40 if !defined $args->{builder};
2efc0af1 41
42 $can_be_required++;
43 }
1b9e472d 44 elsif(exists $args->{default}){
45 if(ref $args->{default} && ref($args->{default}) ne 'CODE'){
2efc0af1 46 $class->throw_error("References are not allowed as default values, you must "
47 . "wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])");
48 }
49 $can_be_required++;
50 }
51
1b9e472d 52 if( $args->{required} && !$can_be_required ) {
121acb8a 53 $class->throw_error("You cannot have a required attribute ($name) without a default, builder, or an init_arg");
2efc0af1 54 }
55
1b9e472d 56 # taken from Mouse::Meta::Attribute->new and _process_args->
2efc0af1 57
1b9e472d 58 if(exists $args->{is}){
59 my $is = $args->{is};
2efc0af1 60
61 if($is eq 'ro'){
1b9e472d 62 $args->{reader} ||= $name;
2efc0af1 63 }
64 elsif($is eq 'rw'){
1b9e472d 65 if(exists $args->{writer}){
66 $args->{reader} ||= $name;
2efc0af1 67 }
68 else{
1b9e472d 69 $args->{accessor} ||= $name;
2efc0af1 70 }
71 }
72 elsif($is eq 'bare'){
73 # do nothing, but don't complain (later) about missing methods
74 }
75 else{
76 $is = 'undef' if !defined $is;
77 $class->throw_error("I do not understand this option (is => $is) on attribute ($name)");
78 }
79 }
80
81 my $tc;
1b9e472d 82 if(exists $args->{isa}){
83 $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_isa_type_constraint($args->{isa});
2efc0af1 84 }
1b9e472d 85 elsif(exists $args->{does}){
4a29b63e 86 # TODO
87 # $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_does_type_constraint($args->{does});
2efc0af1 88 }
1b9e472d 89 $tc = $args->{type_constraint};
2efc0af1 90
1b9e472d 91 if($args->{coerce}){
2efc0af1 92 defined($tc)
93 || $class->throw_error("You cannot have coercion without specifying a type constraint on attribute ($name)");
94
1b9e472d 95 $args->{weak_ref}
121acb8a 96 && $class->throw_error("You cannot have a weak reference to a coerced value on attribute ($name)");
2efc0af1 97 }
98
1b9e472d 99 if ($args->{lazy_build}) {
100 exists($args->{default})
121acb8a 101 && $class->throw_error("You can not use lazy_build and default for the same attribute ($name)");
102
1b9e472d 103 $args->{lazy} = 1;
104 $args->{builder} ||= "_build_${name}";
121acb8a 105 if ($name =~ /^_/) {
1b9e472d 106 $args->{clearer} ||= "_clear${name}";
107 $args->{predicate} ||= "_has${name}";
121acb8a 108 }
109 else {
1b9e472d 110 $args->{clearer} ||= "clear_${name}";
111 $args->{predicate} ||= "has_${name}";
121acb8a 112 }
2efc0af1 113 }
114
1b9e472d 115 if ($args->{auto_deref}) {
121acb8a 116 defined($tc)
117 || $class->throw_error("You cannot auto-dereference without specifying a type constraint on attribute ($name)");
2efc0af1 118
121acb8a 119 ( $tc->is_a_type_of('ArrayRef') || $tc->is_a_type_of('HashRef') )
120 || $class->throw_error("You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute ($name)");
2efc0af1 121 }
122
1b9e472d 123 if (exists $args->{trigger}) {
124 ('CODE' eq ref $args->{trigger})
121acb8a 125 || $class->throw_error("Trigger must be a CODE ref on attribute ($name)");
2efc0af1 126 }
45959ffa 127
1b9e472d 128 if ($args->{lazy}) {
129 (exists $args->{default} || defined $args->{builder})
121acb8a 130 || $class->throw_error("You cannot have lazy attribute ($name) without specifying a default value for it");
2efc0af1 131 }
90fe520e 132
87ca293b 133 return;
134}
135
136sub new {
137 my $class = shift;
138 my $name = shift;
139
140 my %args = (@_ == 1) ? %{ $_[0] } : @_;
141
142 $class->_process_options($name, \%args);
143
144 $args{name} = $name;
145
926290ac 146 my $self = bless \%args, $class;
2efc0af1 147
1b9e472d 148 # extra attributes
149 if($class ne __PACKAGE__){
926290ac 150 $class->meta->_initialize_object($self, \%args);
90fe520e 151 }
c3398f5b 152
2efc0af1 153# XXX: there is no fast way to check attribute validity
1b9e472d 154# my @bad = ...;
2efc0af1 155# if(@bad){
156# @bad = sort @bad;
157# Carp::cluck("Found unknown argument(s) passed to '$name' attribute constructor in '$class': @bad");
158# }
159
926290ac 160 return $self;
c3398f5b 161}
162
90fe520e 163# readers
164
f6715552 165sub name { $_[0]->{name} }
166sub associated_class { $_[0]->{associated_class} }
90fe520e 167
168sub accessor { $_[0]->{accessor} }
169sub reader { $_[0]->{reader} }
170sub writer { $_[0]->{writer} }
171sub predicate { $_[0]->{predicate} }
172sub clearer { $_[0]->{clearer} }
173sub handles { $_[0]->{handles} }
174
f6715552 175sub _is_metadata { $_[0]->{is} }
176sub is_required { $_[0]->{required} }
177sub default { $_[0]->{default} }
178sub is_lazy { $_[0]->{lazy} }
179sub is_lazy_build { $_[0]->{lazy_build} }
f6715552 180sub is_weak_ref { $_[0]->{weak_ref} }
181sub init_arg { $_[0]->{init_arg} }
182sub type_constraint { $_[0]->{type_constraint} }
2efc0af1 183
f6715552 184sub trigger { $_[0]->{trigger} }
185sub builder { $_[0]->{builder} }
186sub should_auto_deref { $_[0]->{auto_deref} }
2efc0af1 187sub should_coerce { $_[0]->{coerce} }
c3398f5b 188
90fe520e 189# predicates
190
191sub has_accessor { exists $_[0]->{accessor} }
192sub has_reader { exists $_[0]->{reader} }
193sub has_writer { exists $_[0]->{writer} }
f6715552 194sub has_predicate { exists $_[0]->{predicate} }
195sub has_clearer { exists $_[0]->{clearer} }
196sub has_handles { exists $_[0]->{handles} }
90fe520e 197
198sub has_default { exists $_[0]->{default} }
f6715552 199sub has_type_constraint { exists $_[0]->{type_constraint} }
200sub has_trigger { exists $_[0]->{trigger} }
201sub has_builder { exists $_[0]->{builder} }
eec1bb49 202
1b9e472d 203sub has_read_method { exists $_[0]->{reader} || exists $_[0]->{accessor} }
204sub has_write_method { exists $_[0]->{writer} || exists $_[0]->{accessor} }
205
df77fd72 206sub _create_args { # DEPRECATED
1bfebf5f 207 $_[0]->{_create_args} = $_[1] if @_ > 1;
208 $_[0]->{_create_args}
209}
210
87ca293b 211sub interpolate_class{
8cf51b82 212 my($class, $args) = @_;
c3398f5b 213
1b9e472d 214 if(my $metaclass = delete $args->{metaclass}){
215 $class = Mouse::Util::resolve_metaclass_alias( Attribute => $metaclass );
216 }
1bfebf5f 217
87ca293b 218 my @traits;
1b9e472d 219 if(my $traits_ref = delete $args->{traits}){
87ca293b 220
1b9e472d 221 for (my $i = 0; $i < @{$traits_ref}; $i++) {
222 my $trait = Mouse::Util::resolve_metaclass_alias(Attribute => $traits_ref->[$i], trait => 1);
b2500191 223
1b9e472d 224 next if $class->does($trait);
74be9f76 225
1b9e472d 226 push @traits, $trait;
227
228 # are there options?
229 push @traits, $traits_ref->[++$i]
230 if ref($traits_ref->[$i+1]);
c3398f5b 231 }
c3398f5b 232
1b9e472d 233 if (@traits) {
234 $class = Mouse::Meta::Class->create_anon_class(
235 superclasses => [ $class ],
236 roles => \@traits,
237 cache => 1,
238 )->name;
1b9e472d 239 }
74be9f76 240 }
241
87ca293b 242 return( $class, @traits );
1b9e472d 243}
244
df77fd72 245sub canonicalize_args{ # DEPRECATED
1b9e472d 246 my ($self, $name, %args) = @_;
247
248 Carp::cluck("$self->canonicalize_args has been deprecated."
04493075 249 . "Use \$self->_process_options instead.")
250 if _MOUSE_VERBOSE;
1b9e472d 251
252 return %args;
253}
254
255sub create {
256 my ($self, $class, $name, %args) = @_;
257
258 Carp::cluck("$self->create has been deprecated."
04493075 259 . "Use \$meta->add_attribute and \$attr->install_accessors instead.")
260 if _MOUSE_VERBOSE;
1b9e472d 261
262 # noop
263 return $self;
c3398f5b 264}
265
ffbbf459 266sub _coerce_and_verify {
267 my($self, $value, $instance) = @_;
268
269 my $type_constraint = $self->{type_constraint};
270
271 return $value if !$type_constraint;
272
273 if ($self->should_coerce && $type_constraint->has_coercion) {
274 $value = $type_constraint->coerce($value);
275 }
276
277 return $value if $type_constraint->check($value);
278
279 $self->verify_against_type_constraint($value);
280
281 return $value;
282}
283
20e25eb9 284sub verify_against_type_constraint {
f55f60dd 285 my ($self, $value) = @_;
5aa30ced 286
ffbbf459 287 my $type_constraint = $self->{type_constraint};
288 return 1 if !$type_constraint;;
289 return 1 if $type_constraint->check($value);
5aa30ced 290
ffbbf459 291 $self->verify_type_constraint_error($self->name, $value, $type_constraint);
b3b74cc6 292}
5aa30ced 293
b3b74cc6 294sub verify_type_constraint_error {
295 my($self, $name, $value, $type) = @_;
fce211ae 296 $self->throw_error("Attribute ($name) does not pass the type constraint because: " . $type->get_message($value));
5aa30ced 297}
298
df77fd72 299sub coerce_constraint { # DEPRECATED
8a7f2a8a 300 my $type = $_[0]->{type_constraint}
301 or return $_[1];
e763d56e 302
303 Carp::cluck("coerce_constraint() has been deprecated, which was an internal utility anyway");
304
7ca5c5fb 305 return Mouse::Util::TypeConstraints->typecast_constraints($_[0]->associated_class->name, $type, $_[1]);
4188b837 306}
307
1b9e472d 308sub clone_and_inherit_options{
8cf51b82 309 my($self, %args) = @_;
310
311 my($attribute_class, @traits) = ref($self)->interpolate_class(\%args);
1b9e472d 312
8cf51b82 313 $args{traits} = \@traits if @traits;
314 return $attribute_class->new($self->name, %{$self}, %args);
1b9e472d 315}
316
df77fd72 317sub clone_parent { # DEPRECATED
1bfebf5f 318 my $self = shift;
319 my $class = shift;
320 my $name = shift;
321 my %args = ($self->get_parent_args($class, $name), @_);
322
1b9e472d 323 Carp::cluck("$self->clone_parent has been deprecated."
04493075 324 . "Use \$meta->add_attribute and \$attr->install_accessors instead.")
325 if _MOUSE_VERBOSE;
1b9e472d 326
7ca5c5fb 327 $self->clone_and_inherited_args($class, $name, %args);
1bfebf5f 328}
329
df77fd72 330sub get_parent_args { # DEPRECATED
1bfebf5f 331 my $self = shift;
332 my $class = shift;
333 my $name = shift;
334
724c77c0 335 for my $super ($class->linearized_isa) {
bb733405 336 my $super_attr = $super->can("meta") && $super->meta->get_attribute($name)
1bfebf5f 337 or next;
338 return %{ $super_attr->_create_args };
339 }
340
fce211ae 341 $self->throw_error("Could not find an attribute by the name of '$name' to inherit from");
342}
343
2a464664 344
df77fd72 345sub get_read_method { # DEPRECATED
346 $_[0]->{reader} || $_[0]->{accessor}
347}
348sub get_write_method { # DEPRECATED
349 $_[0]->{writer} || $_[0]->{accessor}
350}
2a464664 351
352sub get_read_method_ref{
353 my($self) = @_;
354
355 $self->{_read_method_ref} ||= do{
356 my $metaclass = $self->associated_class
357 or $self->throw_error('No asocciated class for ' . $self->name);
358
359 my $reader = $self->{reader} || $self->{accessor};
360 if($reader){
361 $metaclass->name->can($reader);
362 }
363 else{
4ab51fb0 364 $self->accessor_metaclass->_generate_reader($self, $metaclass);
2a464664 365 }
366 };
367}
368
369sub get_write_method_ref{
370 my($self) = @_;
371
372 $self->{_write_method_ref} ||= do{
373 my $metaclass = $self->associated_class
374 or $self->throw_error('No asocciated class for ' . $self->name);
375
376 my $reader = $self->{writer} || $self->{accessor};
377 if($reader){
378 $metaclass->name->can($reader);
379 }
380 else{
4ab51fb0 381 $self->accessor_metaclass->_generate_writer($self, $metaclass);
2a464664 382 }
383 };
384}
385
4ab51fb0 386sub _canonicalize_handles {
387 my($self, $handles) = @_;
388
389 if (ref($handles) eq 'HASH') {
390 return %$handles;
391 }
392 elsif (ref($handles) eq 'ARRAY') {
393 return map { $_ => $_ } @$handles;
394 }
395 else {
396 $self->throw_error("Unable to canonicalize the 'handles' option with $handles");
397 }
398}
399
400
04493075 401sub associate_method{
402 my ($attribute, $method) = @_;
403 $attribute->{associated_methods}++;
404 return;
405}
406
4ab51fb0 407sub accessor_metaclass(){ 'Mouse::Meta::Method::Accessor' }
408
1b9e472d 409sub install_accessors{
410 my($attribute) = @_;
411
4ab51fb0 412 my $metaclass = $attribute->{associated_class};
413 my $accessor_class = $attribute->accessor_metaclass;
1b9e472d 414
4ab51fb0 415 foreach my $type(qw(accessor reader writer predicate clearer)){
1b9e472d 416 if(exists $attribute->{$type}){
4ab51fb0 417 my $generator = '_generate_' . $type;
418 my $code = $accessor_class->$generator($attribute, $metaclass);
419 $metaclass->add_method($attribute->{$type} => $code);
420 $attribute->associate_method($code);
421 }
422 }
7ca5c5fb 423
4ab51fb0 424 # install delegation
425 if(exists $attribute->{handles}){
426 my %handles = $attribute->_canonicalize_handles($attribute->{handles});
427 my $reader = $attribute->get_read_method_ref;
7ca5c5fb 428
4ab51fb0 429 while(my($handle_name, $method_to_call) = each %handles){
430 my $code = $accessor_class->_generate_delegation($attribute, $metaclass,
431 $reader, $handle_name, $method_to_call);
432
433 $metaclass->add_method($handle_name => $code);
434 $attribute->associate_method($code);
1b9e472d 435 }
436 }
437
4ab51fb0 438
1b9e472d 439 if($attribute->can('create') != \&create){
7ca5c5fb 440 # backword compatibility
1b9e472d 441 $attribute->create($metaclass, $attribute->name, %{$attribute});
442 }
443
444 return;
445}
446
fce211ae 447sub throw_error{
448 my $self = shift;
449
450 my $metaclass = (ref $self && $self->associated_class) || 'Mouse::Meta::Class';
451 $metaclass->throw_error(@_, depth => 1);
1bfebf5f 452}
453
c3398f5b 4541;
455
456__END__
457
458=head1 NAME
459
bedd575c 460Mouse::Meta::Attribute - The Mouse attribute metaclass
c3398f5b 461
462=head1 METHODS
463
1820fffe 464=head2 C<< new(%options) -> Mouse::Meta::Attribute >>
c3398f5b 465
306290e8 466Instantiates a new Mouse::Meta::Attribute. Does nothing else.
c3398f5b 467
1820fffe 468It adds the following options to the constructor:
c3398f5b 469
1820fffe 470=over 4
c3398f5b 471
612d3e1a 472=item C<< is => 'ro', 'rw', 'bare' >>
c3398f5b 473
1820fffe 474This provides a shorthand for specifying the C<reader>, C<writer>, or
475C<accessor> names. If the attribute is read-only ('ro') then it will
476have a C<reader> method with the same attribute as the name.
c3398f5b 477
1820fffe 478If it is read-write ('rw') then it will have an C<accessor> method
479with the same name. If you provide an explicit C<writer> for a
480read-write attribute, then you will have a C<reader> with the same
481name as the attribute, and a C<writer> with the name you provided.
c3398f5b 482
1820fffe 483Use 'bare' when you are deliberately not installing any methods
484(accessor, reader, etc.) associated with this attribute; otherwise,
485Moose will issue a deprecation warning when this attribute is added to a
486metaclass.
c3398f5b 487
612d3e1a 488=item C<< isa => Type >>
ab27a55e 489
1820fffe 490This option accepts a type. The type can be a string, which should be
491a type name. If the type name is unknown, it is assumed to be a class
492name.
ab27a55e 493
1820fffe 494This option can also accept a L<Moose::Meta::TypeConstraint> object.
ab27a55e 495
1820fffe 496If you I<also> provide a C<does> option, then your C<isa> option must
497be a class name, and that class must do the role specified with
498C<does>.
ab27a55e 499
612d3e1a 500=item C<< does => Role >>
ab27a55e 501
1820fffe 502This is short-hand for saying that the attribute's type must be an
503object which does the named role.
c3398f5b 504
1820fffe 505B<This option is not yet supported.>
c3398f5b 506
612d3e1a 507=item C<< coerce => Bool >>
ab27a55e 508
1820fffe 509This option is only valid for objects with a type constraint
510(C<isa>). If this is true, then coercions will be applied whenever
511this attribute is set.
c3398f5b 512
1820fffe 513You can make both this and the C<weak_ref> option true.
c3398f5b 514
612d3e1a 515=item C<< trigger => CodeRef >>
ab27a55e 516
1820fffe 517This option accepts a subroutine reference, which will be called after
518the attribute is set.
ab27a55e 519
612d3e1a 520=item C<< required => Bool >>
ab27a55e 521
1820fffe 522An attribute which is required must be provided to the constructor. An
523attribute which is required can also have a C<default> or C<builder>,
524which will satisfy its required-ness.
ab27a55e 525
1820fffe 526A required attribute must have a C<default>, C<builder> or a
527non-C<undef> C<init_arg>
ab27a55e 528
612d3e1a 529=item C<< lazy => Bool >>
ab27a55e 530
1820fffe 531A lazy attribute must have a C<default> or C<builder>. When an
532attribute is lazy, the default value will not be calculated until the
533attribute is read.
93f08899 534
612d3e1a 535=item C<< weak_ref => Bool >>
0fff36e6 536
1820fffe 537If this is true, the attribute's value will be stored as a weak
538reference.
c3398f5b 539
612d3e1a 540=item C<< auto_deref => Bool >>
fb706f5c 541
1820fffe 542If this is true, then the reader will dereference the value when it is
543called. The attribute must have a type constraint which defines the
544attribute as an array or hash reference.
545
612d3e1a 546=item C<< lazy_build => Bool >>
1820fffe 547
548Setting this to true makes the attribute lazy and provides a number of
549default methods.
fb706f5c 550
1820fffe 551 has 'size' => (
552 is => 'ro',
553 lazy_build => 1,
554 );
93d190e0 555
1820fffe 556is equivalent to this:
93d190e0 557
1820fffe 558 has 'size' => (
559 is => 'ro',
560 lazy => 1,
561 builder => '_build_size',
562 clearer => 'clear_size',
563 predicate => 'has_size',
564 );
93d190e0 565
1820fffe 566=back
567
31c5194b 568=head2 C<< associate_method(Method) >>
569
570Associates a method with the attribute. Typically, this is called internally
571when an attribute generates its accessors.
572
573Currently the argument I<Method> is ignored in Mouse.
574
1820fffe 575=head2 C<< verify_against_type_constraint(Item) -> TRUE | ERROR >>
576
577Checks that the given value passes this attribute's type constraint. Returns C<true>
578on success, otherwise C<confess>es.
93d190e0 579
1820fffe 580=head2 C<< clone_and_inherit_options(options) -> Mouse::Meta::Attribute >>
f7b11a21 581
612d3e1a 582Creates a new attribute in the owner class, inheriting options from parent classes.
f7b11a21 583Accessors and helper methods are installed. Some error checking is done.
584
deb9a0f3 585=head2 C<< get_read_method_ref >>\r
df77fd72 586\r
deb9a0f3 587=head2 C<< get_write_method_ref >>\r
df77fd72 588\r
589Returns the subroutine reference of a method suitable for reading or\r
590writing the attribute's value in the associated class. These methods\r
591always return a subroutine reference, regardless of whether or not the\r
592attribute is read- or write-only.
593
1820fffe 594=head1 SEE ALSO
f7b11a21 595
1820fffe 596L<Moose::Meta::Attribute>
f7b11a21 597
31c5194b 598L<Class::MOP::Attribute>
599
c3398f5b 600=cut
601