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