adding in the linearized_isa method
[gitmo/Class-MOP.git] / lib / Class / MOP / Attribute.pm
1
2 package Class::MOP::Attribute;
3
4 use strict;
5 use warnings;
6
7 use Class::MOP::Method::Accessor;
8
9 use Carp         'confess';
10 use Scalar::Util 'blessed', 'reftype', 'weaken';
11
12 our $VERSION   = '0.17';
13 our $AUTHORITY = 'cpan:STEVAN';
14
15 use base 'Class::MOP::Object';
16
17 sub meta {
18     require Class::MOP::Class;
19     Class::MOP::Class->initialize(blessed($_[0]) || $_[0]);
20 }
21
22 # NOTE: (meta-circularity)
23 # This method will be replaced in the
24 # boostrap section of Class::MOP, by
25 # a new version which uses the
26 # &Class::MOP::Class::construct_instance
27 # method to build an attribute meta-object
28 # which itself is described with attribute
29 # meta-objects.
30 #     - Ain't meta-circularity grand? :)
31 sub new {
32     my $class   = shift;
33     my $name    = shift;
34     my %options = @_;
35
36     (defined $name && $name)
37         || confess "You must provide a name for the attribute";
38
39     $options{init_arg} = $name
40         if not exists $options{init_arg};
41     if(exists $options{builder}){
42         confess("builder must be a defined scalar value which is a method name")
43             if ref $options{builder} || !(defined $options{builder});
44         confess("Setting both default and builder is not allowed.")
45             if exists $options{default};
46     } else {
47         (is_default_a_coderef(\%options))
48             || confess("References are not allowed as default values, you must ".
49                        "wrap then in a CODE reference (ex: sub { [] } and not [])")
50                 if exists $options{default} && ref $options{default};
51     }
52     bless {
53         '$!name'      => $name,
54         '$!accessor'  => $options{accessor},
55         '$!reader'    => $options{reader},
56         '$!writer'    => $options{writer},
57         '$!predicate' => $options{predicate},
58         '$!clearer'   => $options{clearer},
59         '$!builder'   => $options{builder},
60         '$!init_arg'  => $options{init_arg},
61         '$!default'   => $options{default},
62         # keep a weakened link to the
63         # class we are associated with
64         '$!associated_class' => undef,
65         # and a list of the methods
66         # associated with this attr
67         '@!associated_methods' => [],
68     } => $class;
69 }
70
71 # NOTE:
72 # this is a primative (and kludgy) clone operation
73 # for now, it will be replaced in the Class::MOP
74 # bootstrap with a proper one, however we know
75 # that this one will work fine for now.
76 sub clone {
77     my $self    = shift;
78     my %options = @_;
79     (blessed($self))
80         || confess "Can only clone an instance";
81     return bless { %{$self}, %options } => blessed($self);
82 }
83
84 sub initialize_instance_slot {
85     my ($self, $meta_instance, $instance, $params) = @_;
86     my $init_arg = $self->{'$!init_arg'};
87     # try to fetch the init arg from the %params ...
88
89     # if nothing was in the %params, we can use the
90     # attribute's default value (if it has one)
91     if(exists $params->{$init_arg}){
92         $meta_instance->set_slot_value($instance, $self->name, $params->{$init_arg});
93     } 
94     elsif (defined $self->{'$!default'}) {
95         $meta_instance->set_slot_value($instance, $self->name, $self->default($instance));
96     } 
97     elsif (defined( my $builder = $self->{'$!builder'})) {
98         if ($builder = $instance->can($builder)) {
99             $meta_instance->set_slot_value($instance, $self->name, $instance->$builder);
100         } 
101         else {
102             confess(blessed($instance)." does not support builder method '". $self->{'$!builder'} ."' for attribute '" . $self->name . "'");
103         }
104     }
105 }
106
107 # NOTE:
108 # the next bunch of methods will get bootstrapped
109 # away in the Class::MOP bootstrapping section
110
111 sub name { $_[0]->{'$!name'} }
112
113 sub associated_class   { $_[0]->{'$!associated_class'}   }
114 sub associated_methods { $_[0]->{'@!associated_methods'} }
115
116 sub has_accessor  { defined($_[0]->{'$!accessor'})  ? 1 : 0 }
117 sub has_reader    { defined($_[0]->{'$!reader'})    ? 1 : 0 }
118 sub has_writer    { defined($_[0]->{'$!writer'})    ? 1 : 0 }
119 sub has_predicate { defined($_[0]->{'$!predicate'}) ? 1 : 0 }
120 sub has_clearer   { defined($_[0]->{'$!clearer'})   ? 1 : 0 }
121 sub has_builder   { defined($_[0]->{'$!builder'})   ? 1 : 0 }
122 sub has_init_arg  { defined($_[0]->{'$!init_arg'})  ? 1 : 0 }
123 sub has_default   { defined($_[0]->{'$!default'})   ? 1 : 0 }
124
125 sub accessor  { $_[0]->{'$!accessor'}  }
126 sub reader    { $_[0]->{'$!reader'}    }
127 sub writer    { $_[0]->{'$!writer'}    }
128 sub predicate { $_[0]->{'$!predicate'} }
129 sub clearer   { $_[0]->{'$!clearer'}   }
130 sub builder   { $_[0]->{'$!builder'}   }
131 sub init_arg  { $_[0]->{'$!init_arg'}  }
132
133 # end bootstrapped away method section.
134 # (all methods below here are kept intact)
135
136 sub get_read_method  { $_[0]->reader || $_[0]->accessor }
137 sub get_write_method { $_[0]->writer || $_[0]->accessor }
138
139 sub is_default_a_coderef {
140     ('CODE' eq (reftype($_[0]->{'$!default'} || $_[0]->{default}) || ''))
141 }
142
143 sub default {
144     my ($self, $instance) = @_;
145     if (defined $instance && $self->is_default_a_coderef) {
146         # if the default is a CODE ref, then
147         # we pass in the instance and default
148         # can return a value based on that
149         # instance. Somewhat crude, but works.
150         return $self->{'$!default'}->($instance);
151     }
152     $self->{'$!default'};
153 }
154
155 # slots
156
157 sub slots { (shift)->name }
158
159 # class association
160
161 sub attach_to_class {
162     my ($self, $class) = @_;
163     (blessed($class) && $class->isa('Class::MOP::Class'))
164         || confess "You must pass a Class::MOP::Class instance (or a subclass)";
165     weaken($self->{'$!associated_class'} = $class);
166 }
167
168 sub detach_from_class {
169     my $self = shift;
170     $self->{'$!associated_class'} = undef;
171 }
172
173 # method association
174
175 sub associate_method {
176     my ($self, $method) = @_;
177     push @{$self->{'@!associated_methods'}} => $method;
178 }
179
180 ## Slot management
181
182 sub set_value {
183     my ($self, $instance, $value) = @_;
184
185     Class::MOP::Class->initialize(blessed($instance))
186                      ->get_meta_instance
187                      ->set_slot_value($instance, $self->name, $value);
188 }
189
190 sub get_value {
191     my ($self, $instance) = @_;
192
193     Class::MOP::Class->initialize(blessed($instance))
194                      ->get_meta_instance
195                      ->get_slot_value($instance, $self->name);
196 }
197
198 sub has_value {
199     my ($self, $instance) = @_;
200
201     Class::MOP::Class->initialize(blessed($instance))
202                      ->get_meta_instance
203                      ->is_slot_initialized($instance, $self->name);
204 }
205
206 sub clear_value {
207     my ($self, $instance) = @_;
208
209     Class::MOP::Class->initialize(blessed($instance))
210                      ->get_meta_instance
211                      ->deinitialize_slot($instance, $self->name);
212 }
213
214 ## load em up ...
215
216 sub accessor_metaclass { 'Class::MOP::Method::Accessor' }
217
218 sub process_accessors {
219     my ($self, $type, $accessor, $generate_as_inline_methods) = @_;
220     if (reftype($accessor)) {
221         (reftype($accessor) eq 'HASH')
222             || confess "bad accessor/reader/writer/predicate/clearer format, must be a HASH ref";
223         my ($name, $method) = %{$accessor};
224         $method = $self->accessor_metaclass->wrap($method);
225         $self->associate_method($method);
226         return ($name, $method);
227     }
228     else {
229         my $inline_me = ($generate_as_inline_methods && $self->associated_class->instance_metaclass->is_inlinable);
230         my $method;
231         eval {
232             $method = $self->accessor_metaclass->new(
233                 attribute     => $self,
234                 is_inline     => $inline_me,
235                 accessor_type => $type,
236             );
237         };
238         confess "Could not create the '$type' method for " . $self->name . " because : $@" if $@;
239         $self->associate_method($method);
240         return ($accessor, $method);
241     }
242 }
243
244 sub install_accessors {
245     my $self   = shift;
246     my $inline = shift;
247     my $class  = $self->associated_class;
248
249     $class->add_method(
250         $self->process_accessors('accessor' => $self->accessor(), $inline)
251     ) if $self->has_accessor();
252
253     $class->add_method(
254         $self->process_accessors('reader' => $self->reader(), $inline)
255     ) if $self->has_reader();
256
257     $class->add_method(
258         $self->process_accessors('writer' => $self->writer(), $inline)
259     ) if $self->has_writer();
260
261     $class->add_method(
262         $self->process_accessors('predicate' => $self->predicate(), $inline)
263     ) if $self->has_predicate();
264
265     $class->add_method(
266         $self->process_accessors('clearer' => $self->clearer(), $inline)
267     ) if $self->has_clearer();
268
269     return;
270 }
271
272 {
273     my $_remove_accessor = sub {
274         my ($accessor, $class) = @_;
275         if (reftype($accessor) && reftype($accessor) eq 'HASH') {
276             ($accessor) = keys %{$accessor};
277         }
278         my $method = $class->get_method($accessor);
279         $class->remove_method($accessor)
280             if (blessed($method) && $method->isa('Class::MOP::Method::Accessor'));
281     };
282
283     sub remove_accessors {
284         my $self = shift;
285         # TODO:
286         # we really need to make sure to remove from the
287         # associates methods here as well. But this is
288         # such a slimly used method, I am not worried
289         # about it right now.
290         $_remove_accessor->($self->accessor(),  $self->associated_class()) if $self->has_accessor();
291         $_remove_accessor->($self->reader(),    $self->associated_class()) if $self->has_reader();
292         $_remove_accessor->($self->writer(),    $self->associated_class()) if $self->has_writer();
293         $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
294         $_remove_accessor->($self->clearer(),   $self->associated_class()) if $self->has_clearer();
295         return;
296     }
297
298 }
299
300 1;
301
302 __END__
303
304 =pod
305
306 =head1 NAME
307
308 Class::MOP::Attribute - Attribute Meta Object
309
310 =head1 SYNOPSIS
311
312   Class::MOP::Attribute->new('$foo' => (
313       accessor  => 'foo',        # dual purpose get/set accessor
314       predicate => 'has_foo'     # predicate check for defined-ness
315       init_arg  => '-foo',       # class->new will look for a -foo key
316       default   => 'BAR IS BAZ!' # if no -foo key is provided, use this
317   ));
318
319   Class::MOP::Attribute->new('$.bar' => (
320       reader    => 'bar',        # getter
321       writer    => 'set_bar',    # setter
322       predicate => 'has_bar'     # predicate check for defined-ness
323       init_arg  => ':bar',       # class->new will look for a :bar key
324       # no default value means it is undef
325   ));
326
327 =head1 DESCRIPTION
328
329 The Attribute Protocol is almost entirely an invention of this module,
330 and is completely optional to this MOP. This is because Perl 5 does not
331 have consistent notion of what is an attribute of a class. There are
332 so many ways in which this is done, and very few (if any) are
333 easily discoverable by this module.
334
335 So, all that said, this module attempts to inject some order into this
336 chaos, by introducing a consistent API which can be used to create
337 object attributes.
338
339 =head1 METHODS
340
341 =head2 Creation
342
343 =over 4
344
345 =item B<new ($name, ?%options)>
346
347 An attribute must (at the very least), have a C<$name>. All other
348 C<%options> are contained added as key-value pairs. Acceptable keys
349 are as follows:
350
351 =over 4
352
353 =item I<init_arg>
354
355 This should be a string value representing the expected key in
356 an initialization hash. For instance, if we have an I<init_arg>
357 value of C<-foo>, then the following code will Just Work.
358
359   MyClass->meta->construct_instance(-foo => "Hello There");
360
361 In an init_arg is not assigned, it will automatically use the
362 value of C<$name>.
363
364 =item I<default>
365
366 The value of this key is the default value which
367 C<Class::MOP::Class::construct_instance> will initialize the
368 attribute to.
369
370 =item I<builder>
371
372 The value of this key is the name of the method that will be
373 called to obtain the value used to initialize the attribute.
374 This should be a method in the class associated with the attribute,
375 not a method in the attribute class itself.
376
377 B<NOTE:>
378 If the value is a simple scalar (string or number), then it can
379 be just passed as is. However, if you wish to initialize it with
380 a HASH or ARRAY ref, then you need to wrap that inside a CODE
381 reference, like so:
382
383   Class::MOP::Attribute->new('@foo' => (
384       default => sub { [] },
385   ));
386
387   # or ...
388
389   Class::MOP::Attribute->new('%foo' => (
390       default => sub { {} },
391   ));
392
393 If you wish to initialize an attribute with a CODE reference
394 itself, then you need to wrap that in a subroutine as well, like
395 so:
396
397   Class::MOP::Attribute->new('&foo' => (
398       default => sub { sub { print "Hello World" } },
399   ));
400
401 And lastly, if the value of your attribute is dependent upon
402 some other aspect of the instance structure, then you can take
403 advantage of the fact that when the I<default> value is a CODE
404 reference, it is passed the raw (unblessed) instance structure
405 as it's only argument. So you can do things like this:
406
407   Class::MOP::Attribute->new('$object_identity' => (
408       default => sub { Scalar::Util::refaddr($_[0]) },
409   ));
410
411 This last feature is fairly limited as there is no gurantee of
412 the order of attribute initializations, so you cannot perform
413 any kind of dependent initializations. However, if this is
414 something you need, you could subclass B<Class::MOP::Class> and
415 this class to acheive it. However, this is currently left as
416 an exercise to the reader :).
417
418 =back
419
420 The I<accessor>, I<reader>, I<writer>, I<predicate> and I<clearer> keys can
421 contain either; the name of the method and an appropriate default one will be
422 generated for you, B<or> a HASH ref containing exactly one key (which will be
423 used as the name of the method) and one value, which should contain a CODE
424 reference which will be installed as the method itself.
425
426 =over 4
427
428 =item I<accessor>
429
430 The I<accessor> is a standard perl-style read/write accessor. It will
431 return the value of the attribute, and if a value is passed as an argument,
432 it will assign that value to the attribute.
433
434 B<NOTE:>
435 This method will properly handle the following code, by assigning an
436 C<undef> value to the attribute.
437
438   $object->set_something(undef);
439
440 =item I<reader>
441
442 This is a basic read-only accessor, it will just return the value of
443 the attribute.
444
445 =item I<writer>
446
447 This is a basic write accessor, it accepts a single argument, and
448 assigns that value to the attribute. This method does not intentially
449 return a value, however perl will return the result of the last
450 expression in the subroutine, which returns in this returning the
451 same value that it was passed.
452
453 B<NOTE:>
454 This method will properly handle the following code, by assigning an
455 C<undef> value to the attribute.
456
457   $object->set_something();
458
459 =item I<predicate>
460
461 This is a basic test to see if the value of the attribute is not
462 C<undef>. It will return true (C<1>) if the attribute's value is
463 defined, and false (C<0>) otherwise.
464
465 =item I<clearer>
466
467 This is the a method that will uninitialize the attr, reverting lazy values
468 back to their "unfulfilled" state.
469
470 =back
471
472 =item B<clone (%options)>
473
474 =item B<initialize_instance_slot ($instance, $params)>
475
476 =back
477
478 =head2 Value management
479
480 These methods are basically "backdoors" to the instance, which can be used
481 to bypass the regular accessors, but still stay within the context of the MOP.
482
483 These methods are not for general use, and should only be used if you really
484 know what you are doing.
485
486 =over 4
487
488 =item B<set_value ($instance, $value)>
489
490 Set the value without going through the accessor. Note that this may be done to
491 even attributes with just read only accessors.
492
493 =item B<get_value ($instance)>
494
495 Return the value without going through the accessor. Note that this may be done
496 even to attributes with just write only accessors.
497
498 =item B<has_value ($instance)>
499
500 Returns a boolean indicating if the item in the C<$instance> has a value in it.
501 This is basically what the default C<predicate> method calls.
502
503 =item B<clear_value ($instance)>
504
505 This will clear the value in the C<$instance>. This is basically what the default
506 C<clearer> would call. Note that this may be done even if the attirbute does not
507 have any associated read, write or clear methods.
508
509 =back
510
511 =head2 Informational
512
513 These are all basic read-only value accessors for the values
514 passed into C<new>. I think they are pretty much self-explanitory.
515
516 =over 4
517
518 =item B<name>
519
520 =item B<accessor>
521
522 =item B<reader>
523
524 =item B<writer>
525
526 =item B<predicate>
527
528 =item B<clearer>
529
530 =item B<init_arg>
531
532 =item B<is_default_a_coderef>
533
534 =item B<default (?$instance)>
535
536 As noted in the documentation for C<new> above, if the I<default>
537 value is a CODE reference, this accessor will pass a single additional
538 argument C<$instance> into it and return the value.
539
540 =item B<slots>
541
542 Returns a list of slots required by the attribute. This is usually
543 just one, which is the name of the attribute.
544
545 =item B<get_read_method>
546
547 =item B<get_write_method>
548
549 Return the name of a method suitable for reading / writing the value of the
550 attribute in the associated class. Suitable for use whether C<reader> and
551 C<writer> or C<accessor> was used.
552
553 =back
554
555 =head2 Informational predicates
556
557 These are all basic predicate methods for the values passed into C<new>.
558
559 =over 4
560
561 =item B<has_accessor>
562
563 =item B<has_reader>
564
565 =item B<has_writer>
566
567 =item B<has_predicate>
568
569 =item B<has_clearer>
570
571 =item B<has_init_arg>
572
573 =item B<has_default>
574
575 =item B<has_builder>
576
577 =back
578
579 =head2 Class association
580
581 These methods allow you to manage the attributes association with
582 the class that contains it. These methods should not be used
583 lightly, nor are they very magical, they are mostly used internally
584 and by metaclass instances.
585
586 =over 4
587
588 =item B<associated_class>
589
590 This returns the metaclass this attribute is associated with.
591
592 =item B<attach_to_class ($class)>
593
594 This will store a weaken reference to C<$class> internally. You should
595 note that just changing the class assocation will not remove the attribute
596 from it's old class, and initialize it (and it's accessors) in the new
597 C<$class>. It is up to you to do this manually.
598
599 =item B<detach_from_class>
600
601 This will remove the weakened reference to the class. It does B<not>
602 remove the attribute itself from the class (or remove it's accessors),
603 you must do that yourself if you want too. Actually if that is what
604 you want to do, you should probably be looking at
605 L<Class::MOP::Class::remove_attribute> instead.
606
607 =back
608
609 =head2 Attribute Accessor generation
610
611 =over 4
612
613 =item B<accessor_metaclass>
614
615 Accessors are generated by an accessor metaclass, which is usually
616 a subclass of C<Class::MOP::Method::Accessor>. This method returns
617 the name of the accessor metaclass that this attribute uses.
618
619 =item B<associate_method ($method)>
620
621 This will associate a C<$method> with the given attribute which is
622 used internally by the accessor generator.
623
624 =item B<associated_methods>
625
626 This will return the list of methods which have been associated with
627 the C<associate_method> methods.
628
629 =item B<install_accessors>
630
631 This allows the attribute to generate and install code for it's own
632 I<accessor/reader/writer/predicate> methods. This is called by
633 C<Class::MOP::Class::add_attribute>.
634
635 This method will call C<process_accessors> for each of the possible
636 method types (accessor, reader, writer & predicate).
637
638 =item B<process_accessors ($type, $value)>
639
640 This takes a C<$type> (accessor, reader, writer or predicate), and
641 a C<$value> (the value passed into the constructor for each of the
642 different types). It will then either generate the method itself
643 (using the C<generate_*_method> methods listed below) or it will
644 use the custom method passed through the constructor.
645
646 =item B<remove_accessors>
647
648 This allows the attribute to remove the method for it's own
649 I<accessor/reader/writer/predicate/clearer>. This is called by
650 C<Class::MOP::Class::remove_attribute>.
651
652 NOTE: This does not currently remove methods from the list returned
653 by C<associated_methods>, that is on the TODO list.
654
655 =back
656
657 =head2 Introspection
658
659 =over 4
660
661 =item B<meta>
662
663 This will return a B<Class::MOP::Class> instance which is related
664 to this class.
665
666 It should also be noted that B<Class::MOP> will actually bootstrap
667 this module by installing a number of attribute meta-objects into
668 it's metaclass. This will allow this class to reap all the benifits
669 of the MOP when subclassing it.
670
671 =back
672
673 =head1 AUTHORS
674
675 Stevan Little E<lt>stevan@iinteractive.comE<gt>
676
677 =head1 COPYRIGHT AND LICENSE
678
679 Copyright 2006, 2007 by Infinity Interactive, Inc.
680
681 L<http://www.iinteractive.com>
682
683 This library is free software; you can redistribute it and/or modify
684 it under the same terms as Perl itself.
685
686 =cut
687
688