immutable refacotring
[gitmo/Class-MOP.git] / lib / Class / MOP / Class.pm
CommitLineData
8b978dd5 1
2package Class::MOP::Class;
3
4use strict;
5use warnings;
6
ba38bf08 7use Class::MOP::Instance;
8use Class::MOP::Method::Wrapped;
9
8b978dd5 10use Carp 'confess';
77e5fce4 11use Scalar::Util 'blessed', 'reftype', 'weaken';
8b978dd5 12use Sub::Name 'subname';
96ceced8 13use B 'svref_2object';
8b978dd5 14
a651e249 15our $VERSION = '0.21';
f0480c45 16our $AUTHORITY = 'cpan:STEVAN';
8b978dd5 17
2243a22b 18use base 'Class::MOP::Module';
19
aa448b16 20# Self-introspection
2eb717d5 21
aa448b16 22sub meta { Class::MOP::Class->initialize(blessed($_[0]) || $_[0]) }
2eb717d5 23
8b978dd5 24# Creation
587aca23 25
be7677c7 26sub initialize {
27 my $class = shift;
28 my $package_name = shift;
29 (defined $package_name && $package_name && !blessed($package_name))
30 || confess "You must pass a package name and it cannot be blessed";
31 $class->construct_class_instance(':package' => $package_name, @_);
32}
33
34sub reinitialize {
35 my $class = shift;
36 my $package_name = shift;
37 (defined $package_name && $package_name && !blessed($package_name))
38 || confess "You must pass a package name and it cannot be blessed";
39 Class::MOP::remove_metaclass_by_name($package_name);
40 $class->construct_class_instance(':package' => $package_name, @_);
41}
651955fb 42
be7677c7 43# NOTE: (meta-circularity)
44# this is a special form of &construct_instance
45# (see below), which is used to construct class
46# meta-object instances for any Class::MOP::*
47# class. All other classes will use the more
48# normal &construct_instance.
49sub construct_class_instance {
50 my $class = shift;
51 my %options = @_;
52 my $package_name = $options{':package'};
53 (defined $package_name && $package_name)
54 || confess "You must pass a package name";
55 # NOTE:
56 # return the metaclass if we have it cached,
57 # and it is still defined (it has not been
58 # reaped by DESTROY yet, which can happen
59 # annoyingly enough during global destruction)
60 return Class::MOP::get_metaclass_by_name($package_name)
61 if Class::MOP::does_metaclass_exist($package_name);
62
63 # NOTE:
64 # we need to deal with the possibility
65 # of class immutability here, and then
66 # get the name of the class appropriately
67 $class = (blessed($class)
68 ? ($class->is_immutable
69 ? $class->get_mutable_metaclass_name()
70 : blessed($class))
71 : $class);
72
be7677c7 73 # now create the metaclass
74 my $meta;
75 if ($class =~ /^Class::MOP::Class$/) {
76 no strict 'refs';
77 $meta = bless {
78 # inherited from Class::MOP::Package
79 '$:package' => $package_name,
c4260b45 80
81 # NOTE:
82 # since the following attributes will
83 # actually be loaded from the symbol
84 # table, and actually bypass the instance
85 # entirely, we can just leave these things
86 # listed here for reference, because they
87 # should not actually have a value associated
88 # with the slot.
89 '%:namespace' => \undef,
be7677c7 90 # inherited from Class::MOP::Module
c4260b45 91 '$:version' => \undef,
92 '$:authority' => \undef,
93 # defined in Class::MOP::Class
c4260b45 94
7855ddba 95 '%:methods' => {},
c4260b45 96 '%:attributes' => {},
be7677c7 97 '$:attribute_metaclass' => $options{':attribute_metaclass'} || 'Class::MOP::Attribute',
98 '$:method_metaclass' => $options{':method_metaclass'} || 'Class::MOP::Method',
99 '$:instance_metaclass' => $options{':instance_metaclass'} || 'Class::MOP::Instance',
100 } => $class;
101 }
102 else {
103 # NOTE:
104 # it is safe to use meta here because
105 # class will always be a subclass of
106 # Class::MOP::Class, which defines meta
107 $meta = $class->meta->construct_instance(%options)
727919c5 108 }
109
be7677c7 110 # and check the metaclass compatibility
111 $meta->check_metaclass_compatability();
ff43b9d6 112
be7677c7 113 Class::MOP::store_metaclass_by_name($package_name, $meta);
b9d9fc0b 114
be7677c7 115 # NOTE:
116 # we need to weaken any anon classes
117 # so that they can call DESTROY properly
b9d9fc0b 118 Class::MOP::weaken_metaclass($package_name) if $meta->is_anon_class;
119
be7677c7 120 $meta;
121}
122
123sub check_metaclass_compatability {
124 my $self = shift;
125
126 # this is always okay ...
127 return if blessed($self) eq 'Class::MOP::Class' &&
128 $self->instance_metaclass eq 'Class::MOP::Instance';
129
130 my @class_list = $self->class_precedence_list;
131 shift @class_list; # shift off $self->name
373a16ae 132
be7677c7 133 foreach my $class_name (@class_list) {
134 my $meta = Class::MOP::get_metaclass_by_name($class_name) || next;
135
373a16ae 136 # NOTE:
137 # we need to deal with the possibility
138 # of class immutability here, and then
be7677c7 139 # get the name of the class appropriately
140 my $meta_type = ($meta->is_immutable
141 ? $meta->get_mutable_metaclass_name()
142 : blessed($meta));
143
144 ($self->isa($meta_type))
145 || confess $self->name . "->meta => (" . (blessed($self)) . ")" .
146 " is not compatible with the " .
147 $class_name . "->meta => (" . ($meta_type) . ")";
77e5fce4 148 # NOTE:
be7677c7 149 # we also need to check that instance metaclasses
150 # are compatabile in the same the class.
151 ($self->instance_metaclass->isa($meta->instance_metaclass))
152 || confess $self->name . "->meta => (" . ($self->instance_metaclass) . ")" .
153 " is not compatible with the " .
154 $class_name . "->meta => (" . ($meta->instance_metaclass) . ")";
155 }
156}
8b978dd5 157
6d5355c3 158## ANON classes
159
160{
161 # NOTE:
162 # this should be sufficient, if you have a
163 # use case where it is not, write a test and
164 # I will change it.
165 my $ANON_CLASS_SERIAL = 0;
b9d9fc0b 166
167 # NOTE:
168 # we need a sufficiently annoying prefix
169 # this should suffice for now, this is
170 # used in a couple of places below, so
171 # need to put it up here for now.
172 my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
173
174 sub is_anon_class {
175 my $self = shift;
a651e249 176 no warnings 'uninitialized';
b9d9fc0b 177 $self->name =~ /^$ANON_CLASS_PREFIX/ ? 1 : 0;
178 }
6d5355c3 179
180 sub create_anon_class {
181 my ($class, %options) = @_;
182 my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
88dd563c 183 return $class->create($package_name, %options);
b9d9fc0b 184 }
6d5355c3 185
b9d9fc0b 186 # NOTE:
187 # this will only get called for
188 # anon-classes, all other calls
189 # are assumed to occur during
190 # global destruction and so don't
191 # really need to be handled explicitly
192 sub DESTROY {
193 my $self = shift;
a651e249 194 no warnings 'uninitialized';
b9d9fc0b 195 return unless $self->name =~ /^$ANON_CLASS_PREFIX/;
196 my ($serial_id) = ($self->name =~ /^$ANON_CLASS_PREFIX(\d+)/);
197 no strict 'refs';
198 foreach my $key (keys %{$ANON_CLASS_PREFIX . $serial_id}) {
199 delete ${$ANON_CLASS_PREFIX . $serial_id}{$key};
200 }
201 delete ${'main::' . $ANON_CLASS_PREFIX}{$serial_id . '::'};
6d5355c3 202 }
b9d9fc0b 203
6d5355c3 204}
205
206# creating classes with MOP ...
207
8b978dd5 208sub create {
88dd563c 209 my $class = shift;
210 my $package_name = shift;
211
bfe4d0fc 212 (defined $package_name && $package_name)
8b978dd5 213 || confess "You must pass a package name";
88dd563c 214
215 (scalar @_ % 2 == 0)
216 || confess "You much pass all parameters as name => value pairs " .
217 "(I found an uneven number of params in \@_)";
218
219 my (%options) = @_;
220
8b978dd5 221 my $code = "package $package_name;";
88dd563c 222 $code .= "\$$package_name\:\:VERSION = '" . $options{version} . "';"
223 if exists $options{version};
224 $code .= "\$$package_name\:\:AUTHORITY = '" . $options{authority} . "';"
225 if exists $options{authority};
226
8b978dd5 227 eval $code;
228 confess "creation of $package_name failed : $@" if $@;
88dd563c 229
bfe4d0fc 230 my $meta = $class->initialize($package_name);
aa448b16 231
232 $meta->add_method('meta' => sub {
df7b4119 233 $class->initialize(blessed($_[0]) || $_[0]);
aa448b16 234 });
235
8b978dd5 236 $meta->superclasses(@{$options{superclasses}})
237 if exists $options{superclasses};
2eb717d5 238 # NOTE:
239 # process attributes first, so that they can
240 # install accessors, but locally defined methods
241 # can then overwrite them. It is maybe a little odd, but
242 # I think this should be the order of things.
243 if (exists $options{attributes}) {
cbd9f942 244 foreach my $attr (@{$options{attributes}}) {
245 $meta->add_attribute($attr);
2eb717d5 246 }
247 }
bfe4d0fc 248 if (exists $options{methods}) {
249 foreach my $method_name (keys %{$options{methods}}) {
250 $meta->add_method($method_name, $options{methods}->{$method_name});
251 }
2eb717d5 252 }
8b978dd5 253 return $meta;
254}
255
7b31baf4 256## Attribute readers
257
258# NOTE:
259# all these attribute readers will be bootstrapped
260# away in the Class::MOP bootstrap section
261
7b31baf4 262sub get_attribute_map { $_[0]->{'%:attributes'} }
263sub attribute_metaclass { $_[0]->{'$:attribute_metaclass'} }
264sub method_metaclass { $_[0]->{'$:method_metaclass'} }
2bab2be6 265sub instance_metaclass { $_[0]->{'$:instance_metaclass'} }
7b31baf4 266
0f71bc80 267# FIXME:
268# this is a prime canidate for conversion to XS
7855ddba 269sub get_method_map {
c4260b45 270 my $self = shift;
7855ddba 271 my $map = $self->{'%:methods'};
0f71bc80 272
273 my $class_name = $self->name;
274 my $method_metaclass = $self->method_metaclass;
275
92330ee2 276 foreach my $symbol ($self->list_all_package_symbols('CODE')) {
91e0eb4a 277 my $code = $self->get_package_symbol('&' . $symbol);
0f71bc80 278
b9575695 279 next if exists $map->{$symbol} &&
280 defined $map->{$symbol} &&
281 $map->{$symbol}->body == $code;
0f71bc80 282
283 my $gv = svref_2object($code)->GV;
284 next if ($gv->STASH->NAME || '') ne $class_name &&
285 ($gv->NAME || '') ne '__ANON__';
286
287 $map->{$symbol} = $method_metaclass->wrap($code);
7855ddba 288 }
0f71bc80 289
7855ddba 290 return $map;
c4260b45 291}
292
c9e77dbb 293# Instance Construction & Cloning
294
5f3c057a 295sub new_object {
296 my $class = shift;
651955fb 297 # NOTE:
298 # we need to protect the integrity of the
299 # Class::MOP::Class singletons here, so we
300 # delegate this to &construct_class_instance
301 # which will deal with the singletons
302 return $class->construct_class_instance(@_)
303 if $class->name->isa('Class::MOP::Class');
24869f62 304 return $class->construct_instance(@_);
5f3c057a 305}
e16da3e6 306
307sub construct_instance {
cbd9f942 308 my ($class, %params) = @_;
0e76a376 309 my $meta_instance = $class->get_meta_instance();
310 my $instance = $meta_instance->create_instance();
c9e77dbb 311 foreach my $attr ($class->compute_all_applicable_attributes()) {
f892c0f0 312 $attr->initialize_instance_slot($meta_instance, $instance, \%params);
cbd9f942 313 }
2d711cc8 314 return $instance;
315}
316
317sub get_meta_instance {
318 my $class = shift;
052c2a1a 319 return $class->instance_metaclass->new(
320 $class,
321 $class->compute_all_applicable_attributes()
322 );
e16da3e6 323}
324
5f3c057a 325sub clone_object {
326 my $class = shift;
7b31baf4 327 my $instance = shift;
651955fb 328 (blessed($instance) && $instance->isa($class->name))
329 || confess "You must pass an instance ($instance) of the metaclass (" . $class->name . ")";
330 # NOTE:
331 # we need to protect the integrity of the
332 # Class::MOP::Class singletons here, they
a740253a 333 # should not be cloned.
651955fb 334 return $instance if $instance->isa('Class::MOP::Class');
f7259199 335 $class->clone_instance($instance, @_);
5f3c057a 336}
337
c9e77dbb 338sub clone_instance {
651955fb 339 my ($class, $instance, %params) = @_;
340 (blessed($instance))
c9e77dbb 341 || confess "You can only clone instances, \$self is not a blessed instance";
f7259199 342 my $meta_instance = $class->get_meta_instance();
343 my $clone = $meta_instance->clone_instance($instance);
11977e43 344 foreach my $key (keys %params) {
f7259199 345 next unless $meta_instance->is_valid_slot($key);
346 $meta_instance->set_slot_value($clone, $key, $params{$key});
347 }
c9e77dbb 348 return $clone;
349}
350
8b978dd5 351# Inheritance
352
353sub superclasses {
354 my $self = shift;
8b978dd5 355 if (@_) {
356 my @supers = @_;
9d6dce77 357 @{$self->get_package_symbol('@ISA')} = @supers;
d82060fe 358 # NOTE:
359 # we need to check the metaclass
360 # compatability here so that we can
361 # be sure that the superclass is
362 # not potentially creating an issues
363 # we don't know about
364 $self->check_metaclass_compatability();
8b978dd5 365 }
9d6dce77 366 @{$self->get_package_symbol('@ISA')};
8b978dd5 367}
368
369sub class_precedence_list {
370 my $self = shift;
bfe4d0fc 371 # NOTE:
372 # We need to check for ciruclar inheirtance here.
373 # This will do nothing if all is well, and blow
374 # up otherwise. Yes, it's an ugly hack, better
375 # suggestions are welcome.
93b4e576 376 { ($self->name || return)->isa('This is a test for circular inheritance') }
8c936afc 377 # ... and now back to our regularly scheduled program
8b978dd5 378 (
379 $self->name,
380 map {
f7259199 381 $self->initialize($_)->class_precedence_list()
8b978dd5 382 } $self->superclasses()
383 );
384}
385
0882828e 386## Methods
387
388sub add_method {
389 my ($self, $method_name, $method) = @_;
390 (defined $method_name && $method_name)
391 || confess "You must define a method name";
2d711cc8 392
7855ddba 393 my $body;
7855ddba 394 if (blessed($method)) {
92330ee2 395 $body = $method->body;
7855ddba 396 }
92330ee2 397 else {
7855ddba 398 $body = $method;
7855ddba 399 ('CODE' eq (reftype($body) || ''))
400 || confess "Your code block must be a CODE reference";
0f71bc80 401 $method = $self->method_metaclass->wrap($body);
7855ddba 402 }
0f71bc80 403 $self->get_method_map->{$method_name} = $method;
7855ddba 404
405 my $full_method_name = ($self->name . '::' . $method_name);
406 $self->add_package_symbol("&${method_name}" => subname $full_method_name => $body);
0882828e 407}
408
a4258ffd 409{
2d711cc8 410 my $fetch_and_prepare_method = sub {
411 my ($self, $method_name) = @_;
412 # fetch it locally
413 my $method = $self->get_method($method_name);
414 # if we dont have local ...
415 unless ($method) {
195f5bf8 416 # try to find the next method
417 $method = $self->find_next_method_by_name($method_name);
418 # die if it does not exist
419 (defined $method)
b9575695 420 || confess "The method '$method_name' is not found in the inherience hierarchy for class " . $self->name;
195f5bf8 421 # and now make sure to wrap it
422 # even if it is already wrapped
423 # because we need a new sub ref
2d711cc8 424 $method = Class::MOP::Method::Wrapped->wrap($method);
195f5bf8 425 }
426 else {
427 # now make sure we wrap it properly
428 $method = Class::MOP::Method::Wrapped->wrap($method)
429 unless $method->isa('Class::MOP::Method::Wrapped');
430 }
431 $self->add_method($method_name => $method);
2d711cc8 432 return $method;
433 };
434
435 sub add_before_method_modifier {
436 my ($self, $method_name, $method_modifier) = @_;
437 (defined $method_name && $method_name)
438 || confess "You must pass in a method name";
439 my $method = $fetch_and_prepare_method->($self, $method_name);
440 $method->add_before_modifier(subname ':before' => $method_modifier);
441 }
442
443 sub add_after_method_modifier {
444 my ($self, $method_name, $method_modifier) = @_;
445 (defined $method_name && $method_name)
446 || confess "You must pass in a method name";
447 my $method = $fetch_and_prepare_method->($self, $method_name);
448 $method->add_after_modifier(subname ':after' => $method_modifier);
449 }
450
451 sub add_around_method_modifier {
452 my ($self, $method_name, $method_modifier) = @_;
453 (defined $method_name && $method_name)
454 || confess "You must pass in a method name";
455 my $method = $fetch_and_prepare_method->($self, $method_name);
456 $method->add_around_modifier(subname ':around' => $method_modifier);
457 }
a4258ffd 458
8c936afc 459 # NOTE:
460 # the methods above used to be named like this:
461 # ${pkg}::${method}:(before|after|around)
462 # but this proved problematic when using one modifier
463 # to wrap multiple methods (something which is likely
464 # to happen pretty regularly IMO). So instead of naming
465 # it like this, I have chosen to just name them purely
466 # with their modifier names, like so:
467 # :(before|after|around)
468 # The fact is that in a stack trace, it will be fairly
469 # evident from the context what method they are attached
470 # to, and so don't need the fully qualified name.
ee5e71d4 471}
472
663f8198 473sub alias_method {
474 my ($self, $method_name, $method) = @_;
475 (defined $method_name && $method_name)
476 || confess "You must define a method name";
de19f115 477
0f71bc80 478 my $body = (blessed($method) ? $method->body : $method);
479 ('CODE' eq (reftype($body) || ''))
480 || confess "Your code block must be a CODE reference";
7855ddba 481
482 $self->add_package_symbol("&${method_name}" => $body);
16e960bd 483}
484
de19f115 485sub has_method {
486 my ($self, $method_name) = @_;
487 (defined $method_name && $method_name)
488 || confess "You must define a method name";
0882828e 489
0f71bc80 490 return 0 unless exists $self->get_method_map->{$method_name};
de19f115 491 return 1;
0882828e 492}
493
494sub get_method {
c9b8b7f9 495 my ($self, $method_name) = @_;
0882828e 496 (defined $method_name && $method_name)
497 || confess "You must define a method name";
7855ddba 498
0f71bc80 499 # NOTE:
500 # I don't really need this here, because
501 # if the method_map is missing a key it
502 # will just return undef for me now
503 # return unless $self->has_method($method_name);
9d6dce77 504
7855ddba 505 return $self->get_method_map->{$method_name};
c9b8b7f9 506}
507
508sub remove_method {
509 my ($self, $method_name) = @_;
510 (defined $method_name && $method_name)
511 || confess "You must define a method name";
512
513 my $removed_method = $self->get_method($method_name);
514
0f71bc80 515 do {
516 $self->remove_package_symbol("&${method_name}");
517 delete $self->get_method_map->{$method_name};
518 } if defined $removed_method;
7855ddba 519
c9b8b7f9 520 return $removed_method;
521}
522
523sub get_method_list {
524 my $self = shift;
0f71bc80 525 keys %{$self->get_method_map};
7855ddba 526}
527
528sub find_method_by_name {
529 my ($self, $method_name) = @_;
b9575695 530 (defined $method_name && $method_name)
531 || confess "You must define a method name to find";
532 # keep a record of what we have seen
533 # here, this will handle all the
534 # inheritence issues because we are
535 # using the &class_precedence_list
536 my %seen_class;
537 my @cpl = $self->class_precedence_list();
538 foreach my $class (@cpl) {
539 next if $seen_class{$class};
540 $seen_class{$class}++;
541 # fetch the meta-class ...
542 my $meta = $self->initialize($class);
543 return $meta->get_method($method_name)
544 if $meta->has_method($method_name);
545 }
546 return;
a5eca695 547}
548
549sub compute_all_applicable_methods {
550 my $self = shift;
551 my @methods;
552 # keep a record of what we have seen
553 # here, this will handle all the
554 # inheritence issues because we are
555 # using the &class_precedence_list
556 my (%seen_class, %seen_method);
557 foreach my $class ($self->class_precedence_list()) {
558 next if $seen_class{$class};
559 $seen_class{$class}++;
560 # fetch the meta-class ...
561 my $meta = $self->initialize($class);
562 foreach my $method_name ($meta->get_method_list()) {
563 next if exists $seen_method{$method_name};
564 $seen_method{$method_name}++;
565 push @methods => {
566 name => $method_name,
567 class => $class,
568 code => $meta->get_method($method_name)
569 };
570 }
571 }
572 return @methods;
573}
574
a5eca695 575sub find_all_methods_by_name {
576 my ($self, $method_name) = @_;
577 (defined $method_name && $method_name)
578 || confess "You must define a method name to find";
579 my @methods;
580 # keep a record of what we have seen
581 # here, this will handle all the
582 # inheritence issues because we are
583 # using the &class_precedence_list
584 my %seen_class;
585 foreach my $class ($self->class_precedence_list()) {
586 next if $seen_class{$class};
587 $seen_class{$class}++;
588 # fetch the meta-class ...
96ceced8 589 my $meta = $self->initialize($class);
a5eca695 590 push @methods => {
591 name => $method_name,
592 class => $class,
593 code => $meta->get_method($method_name)
594 } if $meta->has_method($method_name);
595 }
596 return @methods;
8b978dd5 597}
598
96ceced8 599sub find_next_method_by_name {
600 my ($self, $method_name) = @_;
601 (defined $method_name && $method_name)
2d711cc8 602 || confess "You must define a method name to find";
96ceced8 603 # keep a record of what we have seen
604 # here, this will handle all the
605 # inheritence issues because we are
606 # using the &class_precedence_list
607 my %seen_class;
2d711cc8 608 my @cpl = $self->class_precedence_list();
609 shift @cpl; # discard ourselves
96ceced8 610 foreach my $class (@cpl) {
611 next if $seen_class{$class};
612 $seen_class{$class}++;
613 # fetch the meta-class ...
614 my $meta = $self->initialize($class);
2d711cc8 615 return $meta->get_method($method_name)
616 if $meta->has_method($method_name);
96ceced8 617 }
2d711cc8 618 return;
96ceced8 619}
620
552e3d24 621## Attributes
622
e16da3e6 623sub add_attribute {
2e41896e 624 my $self = shift;
625 # either we have an attribute object already
626 # or we need to create one from the args provided
627 my $attribute = blessed($_[0]) ? $_[0] : $self->attribute_metaclass->new(@_);
628 # make sure it is derived from the correct type though
629 ($attribute->isa('Class::MOP::Attribute'))
630 || confess "Your attribute must be an instance of Class::MOP::Attribute (or a subclass)";
b1897d4d 631
632 # first we attach our new attribute
633 # because it might need certain information
634 # about the class which it is attached to
9ec169fe 635 $attribute->attach_to_class($self);
b1897d4d 636
637 # then we remove attributes of a conflicting
638 # name here so that we can properly detach
639 # the old attr object, and remove any
640 # accessors it would have generated
641 $self->remove_attribute($attribute->name)
642 if $self->has_attribute($attribute->name);
643
644 # then onto installing the new accessors
2d711cc8 645 $attribute->install_accessors();
291073fc 646 $self->get_attribute_map->{$attribute->name} = $attribute;
e16da3e6 647}
648
649sub has_attribute {
650 my ($self, $attribute_name) = @_;
651 (defined $attribute_name && $attribute_name)
652 || confess "You must define an attribute name";
291073fc 653 exists $self->get_attribute_map->{$attribute_name} ? 1 : 0;
e16da3e6 654}
655
656sub get_attribute {
657 my ($self, $attribute_name) = @_;
658 (defined $attribute_name && $attribute_name)
659 || confess "You must define an attribute name";
f7259199 660 return $self->get_attribute_map->{$attribute_name}
b1897d4d 661 # NOTE:
662 # this will return undef anyway, so no need ...
663 # if $self->has_attribute($attribute_name);
664 #return;
e16da3e6 665}
666
667sub remove_attribute {
668 my ($self, $attribute_name) = @_;
669 (defined $attribute_name && $attribute_name)
670 || confess "You must define an attribute name";
7b31baf4 671 my $removed_attribute = $self->get_attribute_map->{$attribute_name};
22286063 672 return unless defined $removed_attribute;
673 delete $self->get_attribute_map->{$attribute_name};
2d711cc8 674 $removed_attribute->remove_accessors();
2d711cc8 675 $removed_attribute->detach_from_class();
e16da3e6 676 return $removed_attribute;
677}
678
679sub get_attribute_list {
680 my $self = shift;
f7259199 681 keys %{$self->get_attribute_map};
e16da3e6 682}
683
684sub compute_all_applicable_attributes {
685 my $self = shift;
686 my @attrs;
687 # keep a record of what we have seen
688 # here, this will handle all the
689 # inheritence issues because we are
690 # using the &class_precedence_list
691 my (%seen_class, %seen_attr);
692 foreach my $class ($self->class_precedence_list()) {
693 next if $seen_class{$class};
694 $seen_class{$class}++;
695 # fetch the meta-class ...
f7259199 696 my $meta = $self->initialize($class);
e16da3e6 697 foreach my $attr_name ($meta->get_attribute_list()) {
698 next if exists $seen_attr{$attr_name};
699 $seen_attr{$attr_name}++;
c9e77dbb 700 push @attrs => $meta->get_attribute($attr_name);
e16da3e6 701 }
702 }
703 return @attrs;
704}
2eb717d5 705
058c1cf5 706sub find_attribute_by_name {
707 my ($self, $attr_name) = @_;
708 # keep a record of what we have seen
709 # here, this will handle all the
710 # inheritence issues because we are
711 # using the &class_precedence_list
712 my %seen_class;
713 foreach my $class ($self->class_precedence_list()) {
714 next if $seen_class{$class};
715 $seen_class{$class}++;
716 # fetch the meta-class ...
717 my $meta = $self->initialize($class);
718 return $meta->get_attribute($attr_name)
719 if $meta->has_attribute($attr_name);
720 }
721 return;
722}
723
857f87a7 724## Class closing
725
726sub is_mutable { 1 }
727sub is_immutable { 0 }
728
729sub make_immutable {
c0cbf4d9 730 return Class::MOP::Class::Immutable->make_metaclass_immutable(@_);
857f87a7 731}
732
8b978dd5 7331;
734
735__END__
736
737=pod
738
739=head1 NAME
740
741Class::MOP::Class - Class Meta Object
742
743=head1 SYNOPSIS
744
8c936afc 745 # assuming that class Foo
746 # has been defined, you can
747
fe122940 748 # use this for introspection ...
749
fe122940 750 # add a method to Foo ...
751 Foo->meta->add_method('bar' => sub { ... })
752
753 # get a list of all the classes searched
754 # the method dispatcher in the correct order
755 Foo->meta->class_precedence_list()
756
757 # remove a method from Foo
758 Foo->meta->remove_method('bar');
759
760 # or use this to actually create classes ...
761
88dd563c 762 Class::MOP::Class->create('Bar' => (
763 version => '0.01',
fe122940 764 superclasses => [ 'Foo' ],
765 attributes => [
766 Class::MOP:::Attribute->new('$bar'),
767 Class::MOP:::Attribute->new('$baz'),
768 ],
769 methods => {
770 calculate_bar => sub { ... },
771 construct_baz => sub { ... }
772 }
773 ));
774
8b978dd5 775=head1 DESCRIPTION
776
fe122940 777This is the largest and currently most complex part of the Perl 5
778meta-object protocol. It controls the introspection and
779manipulation of Perl 5 classes (and it can create them too). The
780best way to understand what this module can do, is to read the
781documentation for each of it's methods.
782
552e3d24 783=head1 METHODS
784
2eb717d5 785=head2 Self Introspection
786
787=over 4
788
789=item B<meta>
790
fe122940 791This will return a B<Class::MOP::Class> instance which is related
792to this class. Thereby allowing B<Class::MOP::Class> to actually
793introspect itself.
794
795As with B<Class::MOP::Attribute>, B<Class::MOP> will actually
796bootstrap this module by installing a number of attribute meta-objects
797into it's metaclass. This will allow this class to reap all the benifits
798of the MOP when subclassing it.
2eb717d5 799
800=back
801
552e3d24 802=head2 Class construction
803
a2e85e6c 804These methods will handle creating B<Class::MOP::Class> objects,
805which can be used to both create new classes, and analyze
806pre-existing classes.
552e3d24 807
808This module will internally store references to all the instances
809you create with these methods, so that they do not need to be
810created any more than nessecary. Basically, they are singletons.
811
812=over 4
813
88dd563c 814=item B<create ($package_name,
815 version =E<gt> ?$version,
816 authority =E<gt> ?$authority,
a2e85e6c 817 superclasses =E<gt> ?@superclasses,
818 methods =E<gt> ?%methods,
819 attributes =E<gt> ?%attributes)>
552e3d24 820
a2e85e6c 821This returns a B<Class::MOP::Class> object, bringing the specified
88dd563c 822C<$package_name> into existence and adding any of the C<$version>,
823C<$authority>, C<@superclasses>, C<%methods> and C<%attributes> to
824it.
552e3d24 825
587aca23 826=item B<create_anon_class (superclasses =E<gt> ?@superclasses,
827 methods =E<gt> ?%methods,
828 attributes =E<gt> ?%attributes)>
829
830This will create an anonymous class, it works much like C<create> but
831it does not need a C<$package_name>. Instead it will create a suitably
832unique package name for you to stash things into.
833
66b3dded 834=item B<initialize ($package_name, %options)>
552e3d24 835
a2e85e6c 836This initializes and returns returns a B<Class::MOP::Class> object
837for a given a C<$package_name>.
838
66b3dded 839=item B<reinitialize ($package_name, %options)>
840
841This removes the old metaclass, and creates a new one in it's place.
842Do B<not> use this unless you really know what you are doing, it could
843very easily make a very large mess of your program.
844
651955fb 845=item B<construct_class_instance (%options)>
a2e85e6c 846
847This will construct an instance of B<Class::MOP::Class>, it is
848here so that we can actually "tie the knot" for B<Class::MOP::Class>
849to use C<construct_instance> once all the bootstrapping is done. This
850method is used internally by C<initialize> and should never be called
851from outside of that method really.
552e3d24 852
550d56db 853=item B<check_metaclass_compatability>
854
855This method is called as the very last thing in the
856C<construct_class_instance> method. This will check that the
857metaclass you are creating is compatible with the metaclasses of all
858your ancestors. For more inforamtion about metaclass compatibility
859see the C<About Metaclass compatibility> section in L<Class::MOP>.
860
552e3d24 861=back
862
c9e77dbb 863=head2 Object instance construction and cloning
a2e85e6c 864
c9e77dbb 865These methods are B<entirely optional>, it is up to you whether you want
866to use them or not.
552e3d24 867
868=over 4
869
2bab2be6 870=item B<instance_metaclass>
871
2d711cc8 872=item B<get_meta_instance>
873
5f3c057a 874=item B<new_object (%params)>
875
876This is a convience method for creating a new object of the class, and
877blessing it into the appropriate package as well. Ideally your class
878would call a C<new> this method like so:
879
880 sub MyClass::new {
881 my ($class, %param) = @_;
882 $class->meta->new_object(%params);
883 }
884
885Of course the ideal place for this would actually be in C<UNIVERSAL::>
886but that is considered bad style, so we do not do that.
887
cbd9f942 888=item B<construct_instance (%params)>
552e3d24 889
c9e77dbb 890This method is used to construct an instace structure suitable for
891C<bless>-ing into your package of choice. It works in conjunction
892with the Attribute protocol to collect all applicable attributes.
893
cbd9f942 894This will construct and instance using a HASH ref as storage
552e3d24 895(currently only HASH references are supported). This will collect all
a2e85e6c 896the applicable attributes and layout out the fields in the HASH ref,
897it will then initialize them using either use the corresponding key
898in C<%params> or any default value or initializer found in the
899attribute meta-object.
727919c5 900
5f3c057a 901=item B<clone_object ($instance, %params)>
902
903This is a convience method for cloning an object instance, then
19d4b5b8 904blessing it into the appropriate package. This method will call
905C<clone_instance>, which performs a shallow copy of the object,
906see that methods documentation for more details. Ideally your
907class would call a C<clone> this method like so:
5f3c057a 908
909 sub MyClass::clone {
910 my ($self, %param) = @_;
911 $self->meta->clone_object($self, %params);
912 }
913
914Of course the ideal place for this would actually be in C<UNIVERSAL::>
915but that is considered bad style, so we do not do that.
916
c9e77dbb 917=item B<clone_instance($instance, %params)>
918
919This method is a compliment of C<construct_instance> (which means if
19d4b5b8 920you override C<construct_instance>, you need to override this one too),
921and clones the instance shallowly.
a27ae83f 922
923The cloned structure returned is (like with C<construct_instance>) an
924unC<bless>ed HASH reference, it is your responsibility to then bless
925this cloned structure into the right class (which C<clone_object> will
926do for you).
c9e77dbb 927
19d4b5b8 928As of 0.11, this method will clone the C<$instance> structure shallowly,
929as opposed to the deep cloning implemented in prior versions. After much
930thought, research and discussion, I have decided that anything but basic
931shallow cloning is outside the scope of the meta-object protocol. I
932think Yuval "nothingmuch" Kogman put it best when he said that cloning
933is too I<context-specific> to be part of the MOP.
934
552e3d24 935=back
936
937=head2 Informational
938
b9d9fc0b 939These are a few predicate methods for asking information about the class.
552e3d24 940
b9d9fc0b 941=over 4
552e3d24 942
b9d9fc0b 943=item B<is_anon_class>
552e3d24 944
b9d9fc0b 945=item B<is_mutable>
552e3d24 946
b9d9fc0b 947=item B<is_immutable>
552e3d24 948
949=back
950
951=head2 Inheritance Relationships
952
953=over 4
954
955=item B<superclasses (?@superclasses)>
956
957This is a read-write attribute which represents the superclass
a2e85e6c 958relationships of the class the B<Class::MOP::Class> instance is
959associated with. Basically, it can get and set the C<@ISA> for you.
552e3d24 960
343203ee 961B<NOTE:>
962Perl will occasionally perform some C<@ISA> and method caching, if
963you decide to change your superclass relationship at runtime (which
964is quite insane and very much not recommened), then you should be
965aware of this and the fact that this module does not make any
966attempt to address this issue.
967
552e3d24 968=item B<class_precedence_list>
969
a2e85e6c 970This computes the a list of all the class's ancestors in the same order
971in which method dispatch will be done. This is similair to
972what B<Class::ISA::super_path> does, but we don't remove duplicate names.
552e3d24 973
974=back
975
976=head2 Methods
977
978=over 4
979
c4260b45 980=item B<get_method_map>
981
2e41896e 982=item B<method_metaclass>
983
552e3d24 984=item B<add_method ($method_name, $method)>
985
986This will take a C<$method_name> and CODE reference to that
a2e85e6c 987C<$method> and install it into the class's package.
552e3d24 988
a2e85e6c 989B<NOTE>:
990This does absolutely nothing special to C<$method>
552e3d24 991other than use B<Sub::Name> to make sure it is tagged with the
992correct name, and therefore show up correctly in stack traces and
993such.
994
663f8198 995=item B<alias_method ($method_name, $method)>
996
997This will take a C<$method_name> and CODE reference to that
998C<$method> and alias the method into the class's package.
999
1000B<NOTE>:
1001Unlike C<add_method>, this will B<not> try to name the
1002C<$method> using B<Sub::Name>, it only aliases the method in
1003the class's package.
1004
552e3d24 1005=item B<has_method ($method_name)>
1006
a2e85e6c 1007This just provides a simple way to check if the class implements
552e3d24 1008a specific C<$method_name>. It will I<not> however, attempt to check
a2e85e6c 1009if the class inherits the method (use C<UNIVERSAL::can> for that).
552e3d24 1010
1011This will correctly handle functions defined outside of the package
1012that use a fully qualified name (C<sub Package::name { ... }>).
1013
1014This will correctly handle functions renamed with B<Sub::Name> and
1015installed using the symbol tables. However, if you are naming the
1016subroutine outside of the package scope, you must use the fully
1017qualified name, including the package name, for C<has_method> to
1018correctly identify it.
1019
1020This will attempt to correctly ignore functions imported from other
1021packages using B<Exporter>. It breaks down if the function imported
1022is an C<__ANON__> sub (such as with C<use constant>), which very well
1023may be a valid method being applied to the class.
1024
1025In short, this method cannot always be trusted to determine if the
1026C<$method_name> is actually a method. However, it will DWIM about
a2e85e6c 102790% of the time, so it's a small trade off I think.
552e3d24 1028
1029=item B<get_method ($method_name)>
1030
86482605 1031This will return a Class::MOP::Method instance related to the specified
1032C<$method_name>, or return undef if that method does not exist.
1033
1034The Class::MOP::Method is codifiable, so you can use it like a normal
1035CODE reference, see L<Class::MOP::Method> for more information.
552e3d24 1036
16e960bd 1037=item B<find_method_by_name ($method_name>
1038
1039This will return a CODE reference of the specified C<$method_name>,
1040or return undef if that method does not exist.
1041
1042Unlike C<get_method> this will also look in the superclasses.
1043
552e3d24 1044=item B<remove_method ($method_name)>
1045
a2e85e6c 1046This will attempt to remove a given C<$method_name> from the class.
552e3d24 1047It will return the CODE reference that it has removed, and will
1048attempt to use B<Sub::Name> to clear the methods associated name.
1049
1050=item B<get_method_list>
1051
1052This will return a list of method names for all I<locally> defined
1053methods. It does B<not> provide a list of all applicable methods,
1054including any inherited ones. If you want a list of all applicable
1055methods, use the C<compute_all_applicable_methods> method.
1056
1057=item B<compute_all_applicable_methods>
1058
a2e85e6c 1059This will return a list of all the methods names this class will
1060respond to, taking into account inheritance. The list will be a list of
552e3d24 1061HASH references, each one containing the following information; method
1062name, the name of the class in which the method lives and a CODE
1063reference for the actual method.
1064
1065=item B<find_all_methods_by_name ($method_name)>
1066
1067This will traverse the inheritence hierarchy and locate all methods
1068with a given C<$method_name>. Similar to
1069C<compute_all_applicable_methods> it returns a list of HASH references
1070with the following information; method name (which will always be the
1071same as C<$method_name>), the name of the class in which the method
1072lives and a CODE reference for the actual method.
1073
1074The list of methods produced is a distinct list, meaning there are no
1075duplicates in it. This is especially useful for things like object
1076initialization and destruction where you only want the method called
1077once, and in the correct order.
1078
96ceced8 1079=item B<find_next_method_by_name ($method_name)>
1080
1081This will return the first method to match a given C<$method_name> in
1082the superclasses, this is basically equivalent to calling
1083C<SUPER::$method_name>, but it can be dispatched at runtime.
1084
552e3d24 1085=back
1086
a4258ffd 1087=head2 Method Modifiers
1088
96ceced8 1089Method modifiers are a concept borrowed from CLOS, in which a method
1090can be wrapped with I<before>, I<after> and I<around> method modifiers
1091that will be called everytime the method is called.
1092
1093=head3 How method modifiers work?
1094
1095Method modifiers work by wrapping the original method and then replacing
1096it in the classes symbol table. The wrappers will handle calling all the
1097modifiers in the appropariate orders and preserving the calling context
1098for the original method.
1099
1100Each method modifier serves a particular purpose, which may not be
1101obvious to users of other method wrapping modules. To start with, the
1102return values of I<before> and I<after> modifiers are ignored. This is
1103because thier purpose is B<not> to filter the input and output of the
1104primary method (this is done with an I<around> modifier). This may seem
1105like an odd restriction to some, but doing this allows for simple code
1106to be added at the begining or end of a method call without jeapordizing
1107the normal functioning of the primary method or placing any extra
1108responsibility on the code of the modifier. Of course if you have more
1109complex needs, then use the I<around> modifier, which uses a variation
1110of continutation passing style to allow for a high degree of flexibility.
1111
1112Before and around modifiers are called in last-defined-first-called order,
1113while after modifiers are called in first-defined-first-called order. So
1114the call tree might looks something like this:
1115
1116 before 2
1117 before 1
1118 around 2
1119 around 1
1120 primary
1121 after 1
1122 after 2
1123
1124To see examples of using method modifiers, see the following examples
1125included in the distribution; F<InstanceCountingClass>, F<Perl6Attribute>,
1126F<AttributesWithHistory> and F<C3MethodDispatchOrder>. There is also a
1127classic CLOS usage example in the test F<017_add_method_modifier.t>.
1128
1129=head3 What is the performance impact?
1130
1131Of course there is a performance cost associated with method modifiers,
1132but we have made every effort to make that cost be directly proportional
1133to the amount of modifier features you utilize.
1134
1135The wrapping method does it's best to B<only> do as much work as it
1136absolutely needs to. In order to do this we have moved some of the
1137performance costs to set-up time, where they are easier to amortize.
1138
1139All this said, my benchmarks have indicated the following:
1140
1141 simple wrapper with no modifiers 100% slower
1142 simple wrapper with simple before modifier 400% slower
1143 simple wrapper with simple after modifier 450% slower
1144 simple wrapper with simple around modifier 500-550% slower
1145 simple wrapper with all 3 modifiers 1100% slower
1146
1147These numbers may seem daunting, but you must remember, every feature
1148comes with some cost. To put things in perspective, just doing a simple
1149C<AUTOLOAD> which does nothing but extract the name of the method called
1150and return it costs about 400% over a normal method call.
1151
a4258ffd 1152=over 4
1153
1154=item B<add_before_method_modifier ($method_name, $code)>
1155
96ceced8 1156This will wrap the method at C<$method_name> and the supplied C<$code>
1157will be passed the C<@_> arguments, and called before the original
1158method is called. As specified above, the return value of the I<before>
1159method modifiers is ignored, and it's ability to modify C<@_> is
1160fairly limited. If you need to do either of these things, use an
1161C<around> method modifier.
1162
a4258ffd 1163=item B<add_after_method_modifier ($method_name, $code)>
1164
96ceced8 1165This will wrap the method at C<$method_name> so that the original
1166method will be called, it's return values stashed, and then the
1167supplied C<$code> will be passed the C<@_> arguments, and called.
1168As specified above, the return value of the I<after> method
1169modifiers is ignored, and it cannot modify the return values of
1170the original method. If you need to do either of these things, use an
1171C<around> method modifier.
1172
a4258ffd 1173=item B<add_around_method_modifier ($method_name, $code)>
1174
96ceced8 1175This will wrap the method at C<$method_name> so that C<$code>
1176will be called and passed the original method as an extra argument
1177at the begining of the C<@_> argument list. This is a variation of
1178continuation passing style, where the function prepended to C<@_>
1179can be considered a continuation. It is up to C<$code> if it calls
1180the original method or not, there is no restriction on what the
1181C<$code> can or cannot do.
1182
a4258ffd 1183=back
1184
552e3d24 1185=head2 Attributes
1186
1187It should be noted that since there is no one consistent way to define
1188the attributes of a class in Perl 5. These methods can only work with
1189the information given, and can not easily discover information on
a2e85e6c 1190their own. See L<Class::MOP::Attribute> for more details.
552e3d24 1191
1192=over 4
1193
2e41896e 1194=item B<attribute_metaclass>
1195
7b31baf4 1196=item B<get_attribute_map>
1197
552e3d24 1198=item B<add_attribute ($attribute_name, $attribute_meta_object)>
1199
a2e85e6c 1200This stores a C<$attribute_meta_object> in the B<Class::MOP::Class>
1201instance associated with the given class, and associates it with
1202the C<$attribute_name>. Unlike methods, attributes within the MOP
1203are stored as meta-information only. They will be used later to
1204construct instances from (see C<construct_instance> above).
552e3d24 1205More details about the attribute meta-objects can be found in the
a2e85e6c 1206L<Class::MOP::Attribute> or the L<Class::MOP/The Attribute protocol>
1207section.
1208
1209It should be noted that any accessor, reader/writer or predicate
1210methods which the C<$attribute_meta_object> has will be installed
1211into the class at this time.
552e3d24 1212
86482605 1213B<NOTE>
1214If an attribute already exists for C<$attribute_name>, the old one
1215will be removed (as well as removing all it's accessors), and then
1216the new one added.
1217
552e3d24 1218=item B<has_attribute ($attribute_name)>
1219
a2e85e6c 1220Checks to see if this class has an attribute by the name of
552e3d24 1221C<$attribute_name> and returns a boolean.
1222
1223=item B<get_attribute ($attribute_name)>
1224
1225Returns the attribute meta-object associated with C<$attribute_name>,
1226if none is found, it will return undef.
1227
1228=item B<remove_attribute ($attribute_name)>
1229
1230This will remove the attribute meta-object stored at
1231C<$attribute_name>, then return the removed attribute meta-object.
1232
a2e85e6c 1233B<NOTE:>
1234Removing an attribute will only affect future instances of
552e3d24 1235the class, it will not make any attempt to remove the attribute from
1236any existing instances of the class.
1237
a2e85e6c 1238It should be noted that any accessor, reader/writer or predicate
1239methods which the attribute meta-object stored at C<$attribute_name>
1240has will be removed from the class at this time. This B<will> make
1241these attributes somewhat inaccessable in previously created
1242instances. But if you are crazy enough to do this at runtime, then
1243you are crazy enough to deal with something like this :).
1244
552e3d24 1245=item B<get_attribute_list>
1246
1247This returns a list of attribute names which are defined in the local
1248class. If you want a list of all applicable attributes for a class,
1249use the C<compute_all_applicable_attributes> method.
1250
1251=item B<compute_all_applicable_attributes>
1252
c9e77dbb 1253This will traverse the inheritance heirachy and return a list of all
1254the applicable attributes for this class. It does not construct a
1255HASH reference like C<compute_all_applicable_methods> because all
1256that same information is discoverable through the attribute
1257meta-object itself.
552e3d24 1258
058c1cf5 1259=item B<find_attribute_by_name ($attr_name)>
1260
1261This method will traverse the inheritance heirachy and find the
1262first attribute whose name matches C<$attr_name>, then return it.
1263It will return undef if nothing is found.
1264
552e3d24 1265=back
1266
857f87a7 1267=head2 Class closing
1268
1269=over 4
1270
857f87a7 1271=item B<make_immutable>
1272
1273=back
1274
1a09d9cc 1275=head1 AUTHORS
8b978dd5 1276
a2e85e6c 1277Stevan Little E<lt>stevan@iinteractive.comE<gt>
8b978dd5 1278
1a09d9cc 1279Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
1280
8b978dd5 1281=head1 COPYRIGHT AND LICENSE
1282
1283Copyright 2006 by Infinity Interactive, Inc.
1284
1285L<http://www.iinteractive.com>
1286
1287This library is free software; you can redistribute it and/or modify
1288it under the same terms as Perl itself.
1289
798baea5 1290=cut