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