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