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