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