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