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