939050c5534024ecd130af94025996240776f14e
[gitmo/Class-MOP.git] / lib / Class / MOP / Class.pm
1
2 package Class::MOP::Class;
3
4 use strict;
5 use warnings;
6
7 use Class::MOP::Instance;
8 use Class::MOP::Method::Wrapped;
9 use Class::MOP::Method::Accessor;
10 use Class::MOP::Method::Constructor;
11
12 use Carp         'confess';
13 use Scalar::Util 'blessed', 'reftype', 'weaken';
14 use Sub::Name    'subname';
15 use Devel::GlobalDestruction 'in_global_destruction';
16 use Try::Tiny;
17 use List::MoreUtils 'all';
18
19 our $VERSION   = '1.01';
20 $VERSION = eval $VERSION;
21 our $AUTHORITY = 'cpan:STEVAN';
22
23 use base 'Class::MOP::Module',
24          'Class::MOP::Mixin::HasAttributes',
25          'Class::MOP::Mixin::HasMethods';
26
27 # Creation
28
29 sub initialize {
30     my $class = shift;
31
32     my $package_name;
33     
34     if ( @_ % 2 ) {
35         $package_name = shift;
36     } else {
37         my %options = @_;
38         $package_name = $options{package};
39     }
40
41     ($package_name && !ref($package_name))
42         || confess "You must pass a package name and it cannot be blessed";
43
44     return Class::MOP::get_metaclass_by_name($package_name)
45         || $class->_construct_class_instance(package => $package_name, @_);
46 }
47
48 # NOTE: (meta-circularity)
49 # this is a special form of _construct_instance
50 # (see below), which is used to construct class
51 # meta-object instances for any Class::MOP::*
52 # class. All other classes will use the more
53 # normal &construct_instance.
54 sub _construct_class_instance {
55     my $class        = shift;
56     my $options      = @_ == 1 ? $_[0] : {@_};
57     my $package_name = $options->{package};
58     (defined $package_name && $package_name)
59         || confess "You must pass a package name";
60     # NOTE:
61     # return the metaclass if we have it cached,
62     # and it is still defined (it has not been
63     # reaped by DESTROY yet, which can happen
64     # annoyingly enough during global destruction)
65
66     if (defined(my $meta = Class::MOP::get_metaclass_by_name($package_name))) {
67         return $meta;
68     }
69
70     # NOTE:
71     # we need to deal with the possibility
72     # of class immutability here, and then
73     # get the name of the class appropriately
74     $class = (ref($class)
75                     ? ($class->is_immutable
76                         ? $class->_get_mutable_metaclass_name()
77                         : ref($class))
78                     : $class);
79
80     # now create the metaclass
81     my $meta;
82     if ($class eq 'Class::MOP::Class') {
83         $meta = $class->_new($options);
84     }
85     else {
86         # NOTE:
87         # it is safe to use meta here because
88         # class will always be a subclass of
89         # Class::MOP::Class, which defines meta
90         $meta = $class->meta->_construct_instance($options)
91     }
92
93     # and check the metaclass compatibility
94     $meta->_check_metaclass_compatibility();  
95
96     Class::MOP::store_metaclass_by_name($package_name, $meta);
97
98     # NOTE:
99     # we need to weaken any anon classes
100     # so that they can call DESTROY properly
101     Class::MOP::weaken_metaclass($package_name) if $meta->is_anon_class;
102
103     $meta;
104 }
105
106 sub _new {
107     my $class = shift;
108
109     return Class::MOP::Class->initialize($class)->new_object(@_)
110         if $class ne __PACKAGE__;
111
112     my $options = @_ == 1 ? $_[0] : {@_};
113
114     return bless {
115         # inherited from Class::MOP::Package
116         'package' => $options->{package},
117
118         # NOTE:
119         # since the following attributes will
120         # actually be loaded from the symbol
121         # table, and actually bypass the instance
122         # entirely, we can just leave these things
123         # listed here for reference, because they
124         # should not actually have a value associated
125         # with the slot.
126         'namespace' => \undef,
127         'methods'   => {},
128
129         # inherited from Class::MOP::Module
130         'version'   => \undef,
131         'authority' => \undef,
132
133         # defined in Class::MOP::Class
134         'superclasses' => \undef,
135
136         'attributes' => {},
137         'attribute_metaclass' =>
138             ( $options->{'attribute_metaclass'} || 'Class::MOP::Attribute' ),
139         'method_metaclass' =>
140             ( $options->{'method_metaclass'} || 'Class::MOP::Method' ),
141         'wrapped_method_metaclass' => (
142             $options->{'wrapped_method_metaclass'}
143                 || 'Class::MOP::Method::Wrapped'
144         ),
145         'instance_metaclass' =>
146             ( $options->{'instance_metaclass'} || 'Class::MOP::Instance' ),
147         'immutable_trait' => (
148             $options->{'immutable_trait'}
149                 || 'Class::MOP::Class::Immutable::Trait'
150         ),
151         'constructor_name' => ( $options->{constructor_name} || 'new' ),
152         'constructor_class' => (
153             $options->{constructor_class} || 'Class::MOP::Method::Constructor'
154         ),
155         'destructor_class' => $options->{destructor_class},
156     }, $class;
157 }
158
159 sub reset_package_cache_flag  { (shift)->{'_package_cache_flag'} = undef } 
160 sub update_package_cache_flag {
161     my $self = shift;
162     # NOTE:
163     # we can manually update the cache number 
164     # since we are actually adding the method
165     # to our cache as well. This avoids us 
166     # having to regenerate the method_map.
167     # - SL    
168     $self->{'_package_cache_flag'} = Class::MOP::check_package_cache_flag($self->name);    
169 }
170
171 ## Metaclass compatibility
172 {
173     my %base_metaclass = (
174         attribute_metaclass      => 'Class::MOP::Attribute',
175         method_metaclass         => 'Class::MOP::Method',
176         wrapped_method_metaclass => 'Class::MOP::Method::Wrapped',
177         instance_metaclass       => 'Class::MOP::Instance',
178         constructor_class        => 'Class::MOP::Method::Constructor',
179         destructor_class         => 'Class::MOP::Method::Destructor',
180     );
181
182     sub _base_metaclasses { %base_metaclass }
183 }
184
185 sub _check_metaclass_compatibility {
186     my $self = shift;
187
188     if (my @superclasses = $self->superclasses) {
189         $self->_fix_metaclass_incompatibility(@superclasses);
190
191         my %base_metaclass = $self->_base_metaclasses;
192
193         # this is always okay ...
194         return if ref($self) eq 'Class::MOP::Class'
195             && all {
196                 my $meta = $self->$_;
197                 !defined($meta) || $meta eq $base_metaclass{$_}
198             } keys %base_metaclass;
199
200         for my $superclass (@superclasses) {
201             $self->_check_class_metaclass_compatibility($superclass);
202         }
203
204         for my $metaclass_type (keys %base_metaclass) {
205             next unless defined $self->$metaclass_type;
206             for my $superclass (@superclasses) {
207                 $self->_check_single_metaclass_compatibility(
208                     $metaclass_type, $superclass
209                 );
210             }
211         }
212     }
213 }
214
215 sub _check_class_metaclass_compatibility {
216     my $self = shift;
217     my ( $superclass_name ) = @_;
218
219     my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
220         || return;
221
222     # NOTE:
223     # we need to deal with the possibility
224     # of class immutability here, and then
225     # get the name of the class appropriately
226     my $super_meta_type
227         = $super_meta->is_immutable
228         ? $super_meta->_get_mutable_metaclass_name()
229         : ref($super_meta);
230
231     ($self->isa($super_meta_type))
232         || confess "The metaclass of " . $self->name . " ("
233                  . (ref($self)) . ")" .  " is not compatible with "
234                  . "the metaclass of its superclass, "
235                  . $superclass_name . " (" . ($super_meta_type) . ")";
236 }
237
238 sub _check_single_metaclass_compatibility {
239     my $self = shift;
240     my ( $metaclass_type, $superclass_name ) = @_;
241
242     my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name)
243         || return;
244
245     # for instance, Moose::Meta::Class has a error_class attribute, but
246     # Class::MOP::Class doesn't - this shouldn't be an error
247     return unless $super_meta->can($metaclass_type);
248     # for instance, Moose::Meta::Class has a destructor_class, but
249     # Class::MOP::Class doesn't - this shouldn't be an error
250     return if defined $self->$metaclass_type
251             && !defined $super_meta->$metaclass_type;
252
253     my $metaclass_type_name = $metaclass_type;
254     $metaclass_type_name =~ s/_(?:meta)?class$//;
255     $metaclass_type_name =~ s/_/ /g;
256     ($self->$metaclass_type->isa($super_meta->$metaclass_type))
257         || confess "The $metaclass_type_name metaclass for "
258                  . $self->name . " (" . ($self->$metaclass_type)
259                  . ")" . " is not compatible with the "
260                  . "$metaclass_type_name metaclass of its "
261                  . "superclass, " . $superclass_name . " ("
262                  . ($super_meta->$metaclass_type) . ")";
263 }
264
265 sub _can_fix_class_metaclass_incompatibility_by_subclassing {
266     my $self = shift;
267     my ($super_meta) = @_;
268
269     # NOTE:
270     # we need to deal with the possibility
271     # of class immutability here, and then
272     # get the name of the class appropriately
273     my $super_meta_type
274         = $super_meta->is_immutable
275         ? $super_meta->_get_mutable_metaclass_name()
276         : ref($super_meta);
277
278     return $super_meta_type ne blessed($self)
279         && $super_meta->isa(blessed($self));
280 }
281
282 sub _can_fix_single_metaclass_incompatibility_by_subclassing {
283     my $self = shift;
284     my ($metaclass_type, $super_meta) = @_;
285
286     my $specific_meta = $self->$metaclass_type;
287     return unless $super_meta->can($metaclass_type);
288     my $super_specific_meta = $super_meta->$metaclass_type;
289
290     # for instance, Moose::Meta::Class has a destructor_class, but
291     # Class::MOP::Class doesn't - this shouldn't be an error
292     return if defined $specific_meta
293            && !defined $super_specific_meta;
294
295     return $specific_meta ne $super_specific_meta
296         && $super_specific_meta->isa($specific_meta);
297 }
298
299 sub _can_fix_metaclass_incompatibility_by_subclassing {
300     my $self = shift;
301     my ($super_meta) = @_;
302
303     return 1 if $self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta);
304
305     my %base_metaclass = $self->_base_metaclasses;
306     for my $metaclass_type (keys %base_metaclass) {
307         next unless defined $self->$metaclass_type;
308         return 1 if $self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta);
309     }
310
311     return;
312 }
313
314 sub _can_fix_metaclass_incompatibility {
315     my $self = shift;
316     return $self->_can_fix_metaclass_incompatibility_by_subclassing(@_);
317 }
318
319 sub _fix_metaclass_incompatibility {
320     my $self = shift;
321     my @supers = @_;
322
323     my $necessary = 0;
324     for my $super (map { Class::MOP::Class->initialize($_) } @supers) {
325         $necessary = 1
326             if $self->_can_fix_metaclass_incompatibility($super);
327     }
328     return unless $necessary;
329
330     ($self->is_pristine)
331         || confess "Can't fix metaclass incompatibility for "
332                  . $self->name
333                  . " because it is not pristine.";
334
335     for my $super (map { Class::MOP::Class->initialize($_) } @supers) {
336         $self->_fix_class_metaclass_incompatibility($super);
337     }
338
339     my %base_metaclass = $self->_base_metaclasses;
340     for my $metaclass_type (keys %base_metaclass) {
341         next unless defined $self->$metaclass_type;
342         for my $super (map { Class::MOP::Class->initialize($_) } @supers) {
343             $self->_fix_single_metaclass_incompatibility(
344                 $metaclass_type, $super
345             );
346         }
347     }
348 }
349
350 sub _fix_class_metaclass_incompatibility {
351     my $self = shift;
352     my ( $super_meta ) = @_;
353
354     if ($self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta)) {
355         $super_meta->meta->rebless_instance($self);
356     }
357 }
358
359 sub _fix_single_metaclass_incompatibility {
360     my $self = shift;
361     my ( $metaclass_type, $super_meta ) = @_;
362
363     if ($self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta)) {
364         $self->{$metaclass_type} = $super_meta->$metaclass_type;
365     }
366 }
367
368 ## ANON classes
369
370 {
371     # NOTE:
372     # this should be sufficient, if you have a
373     # use case where it is not, write a test and
374     # I will change it.
375     my $ANON_CLASS_SERIAL = 0;
376
377     # NOTE:
378     # we need a sufficiently annoying prefix
379     # this should suffice for now, this is
380     # used in a couple of places below, so
381     # need to put it up here for now.
382     my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
383
384     sub is_anon_class {
385         my $self = shift;
386         no warnings 'uninitialized';
387         $self->name =~ /^$ANON_CLASS_PREFIX/o;
388     }
389
390     sub create_anon_class {
391         my ($class, %options) = @_;
392         my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
393         return $class->create($package_name, %options);
394     }
395
396     # NOTE:
397     # this will only get called for
398     # anon-classes, all other calls
399     # are assumed to occur during
400     # global destruction and so don't
401     # really need to be handled explicitly
402     sub DESTROY {
403         my $self = shift;
404
405         return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
406
407         no warnings 'uninitialized';
408         my $name = $self->name;
409         return unless $name =~ /^$ANON_CLASS_PREFIX/o;
410
411         # Moose does a weird thing where it replaces the metaclass for
412         # class when fixing metaclass incompatibility. In that case,
413         # we don't want to clean out the namespace now. We can detect
414         # that because Moose will explicitly update the singleton
415         # cache in Class::MOP.
416         my $current_meta = Class::MOP::get_metaclass_by_name($name);
417         return if $current_meta ne $self;
418
419         my ($serial_id) = ($name =~ /^$ANON_CLASS_PREFIX(\d+)/o);
420         no strict 'refs';
421         @{$name . '::ISA'} = ();
422         %{$name . '::'}    = ();
423         delete ${$ANON_CLASS_PREFIX}{$serial_id . '::'};
424
425         Class::MOP::remove_metaclass_by_name($name);
426     }
427
428 }
429
430 # creating classes with MOP ...
431
432 sub create {
433     my ( $class, @args ) = @_;
434
435     unshift @args, 'package' if @args % 2 == 1;
436
437     my (%options) = @args;
438     my $package_name = $options{package};
439
440     (ref $options{superclasses} eq 'ARRAY')
441         || confess "You must pass an ARRAY ref of superclasses"
442             if exists $options{superclasses};
443             
444     (ref $options{attributes} eq 'ARRAY')
445         || confess "You must pass an ARRAY ref of attributes"
446             if exists $options{attributes};      
447             
448     (ref $options{methods} eq 'HASH')
449         || confess "You must pass a HASH ref of methods"
450             if exists $options{methods};                  
451
452     my (%initialize_options) = @args;
453     delete @initialize_options{qw(
454         package
455         superclasses
456         attributes
457         methods
458         version
459         authority
460     )};
461     my $meta = $class->initialize( $package_name => %initialize_options );
462
463     $meta->_instantiate_module( $options{version}, $options{authority} );
464
465     # FIXME totally lame
466     $meta->add_method('meta' => sub {
467         $class->initialize(ref($_[0]) || $_[0]);
468     });
469
470     $meta->superclasses(@{$options{superclasses}})
471         if exists $options{superclasses};
472     # NOTE:
473     # process attributes first, so that they can
474     # install accessors, but locally defined methods
475     # can then overwrite them. It is maybe a little odd, but
476     # I think this should be the order of things.
477     if (exists $options{attributes}) {
478         foreach my $attr (@{$options{attributes}}) {
479             $meta->add_attribute($attr);
480         }
481     }
482     if (exists $options{methods}) {
483         foreach my $method_name (keys %{$options{methods}}) {
484             $meta->add_method($method_name, $options{methods}->{$method_name});
485         }
486     }
487     return $meta;
488 }
489
490 ## Attribute readers
491
492 # NOTE:
493 # all these attribute readers will be bootstrapped
494 # away in the Class::MOP bootstrap section
495
496 sub instance_metaclass       { $_[0]->{'instance_metaclass'}          }
497 sub immutable_trait          { $_[0]->{'immutable_trait'}             }
498 sub constructor_class        { $_[0]->{'constructor_class'}           }
499 sub constructor_name         { $_[0]->{'constructor_name'}            }
500 sub destructor_class         { $_[0]->{'destructor_class'}            }
501
502 # Instance Construction & Cloning
503
504 sub new_object {
505     my $class = shift;
506
507     # NOTE:
508     # we need to protect the integrity of the
509     # Class::MOP::Class singletons here, so we
510     # delegate this to &construct_class_instance
511     # which will deal with the singletons
512     return $class->_construct_class_instance(@_)
513         if $class->name->isa('Class::MOP::Class');
514     return $class->_construct_instance(@_);
515 }
516
517 sub _construct_instance {
518     my $class = shift;
519     my $params = @_ == 1 ? $_[0] : {@_};
520     my $meta_instance = $class->get_meta_instance();
521     # FIXME:
522     # the code below is almost certainly incorrect
523     # but this is foreign inheritance, so we might
524     # have to kludge it in the end.
525     my $instance;
526     if (my $instance_class = blessed($params->{__INSTANCE__})) {
527         ($instance_class eq $class->name)
528             || confess "Objects passed as the __INSTANCE__ parameter must "
529                      . "already be blessed into the correct class, but "
530                      . "$params->{__INSTANCE__} is not a " . $class->name;
531         $instance = $params->{__INSTANCE__};
532     }
533     elsif (exists $params->{__INSTANCE__}) {
534         confess "The __INSTANCE__ parameter must be a blessed reference, not "
535               . $params->{__INSTANCE__};
536     }
537     else {
538         $instance = $meta_instance->create_instance();
539     }
540     foreach my $attr ($class->get_all_attributes()) {
541         $attr->initialize_instance_slot($meta_instance, $instance, $params);
542     }
543     # NOTE:
544     # this will only work for a HASH instance type
545     if ($class->is_anon_class) {
546         (reftype($instance) eq 'HASH')
547             || confess "Currently only HASH based instances are supported with instance of anon-classes";
548         # NOTE:
549         # At some point we should make this official
550         # as a reserved slot name, but right now I am
551         # going to keep it here.
552         # my $RESERVED_MOP_SLOT = '__MOP__';
553         $instance->{'__MOP__'} = $class;
554     }
555     return $instance;
556 }
557
558
559 sub get_meta_instance {
560     my $self = shift;
561     $self->{'_meta_instance'} ||= $self->_create_meta_instance();
562 }
563
564 sub _create_meta_instance {
565     my $self = shift;
566     
567     my $instance = $self->instance_metaclass->new(
568         associated_metaclass => $self,
569         attributes => [ $self->get_all_attributes() ],
570     );
571
572     $self->add_meta_instance_dependencies()
573         if $instance->is_dependent_on_superclasses();
574
575     return $instance;
576 }
577
578 sub clone_object {
579     my $class    = shift;
580     my $instance = shift;
581     (blessed($instance) && $instance->isa($class->name))
582         || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
583
584     # NOTE:
585     # we need to protect the integrity of the
586     # Class::MOP::Class singletons here, they
587     # should not be cloned.
588     return $instance if $instance->isa('Class::MOP::Class');
589     $class->_clone_instance($instance, @_);
590 }
591
592 sub _clone_instance {
593     my ($class, $instance, %params) = @_;
594     (blessed($instance))
595         || confess "You can only clone instances, ($instance) is not a blessed instance";
596     my $meta_instance = $class->get_meta_instance();
597     my $clone = $meta_instance->clone_instance($instance);
598     foreach my $attr ($class->get_all_attributes()) {
599         if ( defined( my $init_arg = $attr->init_arg ) ) {
600             if (exists $params{$init_arg}) {
601                 $attr->set_value($clone, $params{$init_arg});
602             }
603         }
604     }
605     return $clone;
606 }
607
608 sub rebless_instance {
609     my ($self, $instance, %params) = @_;
610
611     my $old_metaclass = Class::MOP::class_of($instance);
612
613     my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
614     $self->name->isa($old_class)
615         || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
616
617     $old_metaclass->rebless_instance_away($instance, $self, %params)
618         if $old_metaclass;
619
620     my $meta_instance = $self->get_meta_instance();
621
622     # rebless!
623     # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
624     $meta_instance->rebless_instance_structure($_[1], $self);
625
626     foreach my $attr ( $self->get_all_attributes ) {
627         if ( $attr->has_value($instance) ) {
628             if ( defined( my $init_arg = $attr->init_arg ) ) {
629                 $params{$init_arg} = $attr->get_value($instance)
630                     unless exists $params{$init_arg};
631             } 
632             else {
633                 $attr->set_value($instance, $attr->get_value($instance));
634             }
635         }
636     }
637
638     foreach my $attr ($self->get_all_attributes) {
639         $attr->initialize_instance_slot($meta_instance, $instance, \%params);
640     }
641     
642     $instance;
643 }
644
645 sub rebless_instance_back {
646     my ( $self, $instance ) = @_;
647
648     my $old_metaclass = Class::MOP::class_of($instance);
649
650     my $old_class
651         = $old_metaclass ? $old_metaclass->name : blessed($instance);
652     $old_class->isa( $self->name )
653         || confess
654         "You may rebless only into a superclass of ($old_class), of which ("
655         . $self->name
656         . ") isn't.";
657
658     $old_metaclass->rebless_instance_away( $instance, $self )
659         if $old_metaclass;
660
661     my $meta_instance = $self->get_meta_instance;
662
663     # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
664     $meta_instance->rebless_instance_structure( $_[1], $self );
665
666     for my $attr ( $old_metaclass->get_all_attributes ) {
667         next if $self->has_attribute( $attr->name );
668         $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
669     }
670
671     return $instance;
672 }
673
674 sub rebless_instance_away {
675     # this intentionally does nothing, it is just a hook
676 }
677
678 sub _attach_attribute {
679     my ($self, $attribute) = @_;
680     $attribute->attach_to_class($self);
681 }
682
683 sub _post_add_attribute {
684     my ( $self, $attribute ) = @_;
685
686     $self->invalidate_meta_instances;
687
688     # invalidate package flag here
689     try {
690         local $SIG{__DIE__};
691         $attribute->install_accessors;
692     }
693     catch {
694         $self->remove_attribute( $attribute->name );
695         die $_;
696     };
697 }
698
699 sub remove_attribute {
700     my $self = shift;
701
702     my $removed_attribute = $self->SUPER::remove_attribute(@_)
703         or return;
704
705     $self->invalidate_meta_instances;
706
707     $removed_attribute->remove_accessors;
708     $removed_attribute->detach_from_class;
709
710     return$removed_attribute;
711 }
712
713 sub find_attribute_by_name {
714     my ( $self, $attr_name ) = @_;
715
716     foreach my $class ( $self->linearized_isa ) {
717         # fetch the meta-class ...
718         my $meta = $self->initialize($class);
719         return $meta->get_attribute($attr_name)
720             if $meta->has_attribute($attr_name);
721     }
722
723     return;
724 }
725
726 sub get_all_attributes {
727     my $self = shift;
728     my %attrs = map { %{ $self->initialize($_)->_attribute_map } }
729         reverse $self->linearized_isa;
730     return values %attrs;
731 }
732
733 # Inheritance
734
735 sub superclasses {
736     my $self     = shift;
737     my $var_spec = { sigil => '@', type => 'ARRAY', name => 'ISA' };
738     if (@_) {
739         my @supers = @_;
740         @{$self->get_package_symbol($var_spec)} = @supers;
741
742         # NOTE:
743         # on 5.8 and below, we need to call
744         # a method to get Perl to detect
745         # a cycle in the class hierarchy
746         my $class = $self->name;
747         $class->isa($class);
748
749         # NOTE:
750         # we need to check the metaclass
751         # compatibility here so that we can
752         # be sure that the superclass is
753         # not potentially creating an issues
754         # we don't know about
755
756         $self->_check_metaclass_compatibility();
757         $self->_superclasses_updated();
758     }
759     @{$self->get_package_symbol($var_spec)};
760 }
761
762 sub _superclasses_updated {
763     my $self = shift;
764     $self->update_meta_instance_dependencies();
765 }
766
767 sub subclasses {
768     my $self = shift;
769     my $super_class = $self->name;
770
771     return @{ $super_class->mro::get_isarev() };
772 }
773
774 sub direct_subclasses {
775     my $self = shift;
776     my $super_class = $self->name;
777
778     return grep {
779         grep {
780             $_ eq $super_class
781         } Class::MOP::Class->initialize($_)->superclasses
782     } $self->subclasses;
783 }
784
785 sub linearized_isa {
786     return @{ mro::get_linear_isa( (shift)->name ) };
787 }
788
789 sub class_precedence_list {
790     my $self = shift;
791     my $name = $self->name;
792
793     unless (Class::MOP::IS_RUNNING_ON_5_10()) { 
794         # NOTE:
795         # We need to check for circular inheritance here
796         # if we are are not on 5.10, cause 5.8 detects it 
797         # late. This will do nothing if all is well, and 
798         # blow up otherwise. Yes, it's an ugly hack, better
799         # suggestions are welcome.        
800         # - SL
801         ($name || return)->isa('This is a test for circular inheritance') 
802     }
803
804     # if our mro is c3, we can 
805     # just grab the linear_isa
806     if (mro::get_mro($name) eq 'c3') {
807         return @{ mro::get_linear_isa($name) }
808     }
809     else {
810         # NOTE:
811         # we can't grab the linear_isa for dfs
812         # since it has all the duplicates 
813         # already removed.
814         return (
815             $name,
816             map {
817                 $self->initialize($_)->class_precedence_list()
818             } $self->superclasses()
819         );
820     }
821 }
822
823 ## Methods
824
825 {
826     my $fetch_and_prepare_method = sub {
827         my ($self, $method_name) = @_;
828         my $wrapped_metaclass = $self->wrapped_method_metaclass;
829         # fetch it locally
830         my $method = $self->get_method($method_name);
831         # if we dont have local ...
832         unless ($method) {
833             # try to find the next method
834             $method = $self->find_next_method_by_name($method_name);
835             # die if it does not exist
836             (defined $method)
837                 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
838             # and now make sure to wrap it
839             # even if it is already wrapped
840             # because we need a new sub ref
841             $method = $wrapped_metaclass->wrap($method,
842                 package_name => $self->name,
843                 name         => $method_name,
844             );
845         }
846         else {
847             # now make sure we wrap it properly
848             $method = $wrapped_metaclass->wrap($method,
849                 package_name => $self->name,
850                 name         => $method_name,
851             ) unless $method->isa($wrapped_metaclass);
852         }
853         $self->add_method($method_name => $method);
854         return $method;
855     };
856
857     sub add_before_method_modifier {
858         my ($self, $method_name, $method_modifier) = @_;
859         (defined $method_name && length $method_name)
860             || confess "You must pass in a method name";
861         my $method = $fetch_and_prepare_method->($self, $method_name);
862         $method->add_before_modifier(
863             subname(':before' => $method_modifier)
864         );
865     }
866
867     sub add_after_method_modifier {
868         my ($self, $method_name, $method_modifier) = @_;
869         (defined $method_name && length $method_name)
870             || confess "You must pass in a method name";
871         my $method = $fetch_and_prepare_method->($self, $method_name);
872         $method->add_after_modifier(
873             subname(':after' => $method_modifier)
874         );
875     }
876
877     sub add_around_method_modifier {
878         my ($self, $method_name, $method_modifier) = @_;
879         (defined $method_name && length $method_name)
880             || confess "You must pass in a method name";
881         my $method = $fetch_and_prepare_method->($self, $method_name);
882         $method->add_around_modifier(
883             subname(':around' => $method_modifier)
884         );
885     }
886
887     # NOTE:
888     # the methods above used to be named like this:
889     #    ${pkg}::${method}:(before|after|around)
890     # but this proved problematic when using one modifier
891     # to wrap multiple methods (something which is likely
892     # to happen pretty regularly IMO). So instead of naming
893     # it like this, I have chosen to just name them purely
894     # with their modifier names, like so:
895     #    :(before|after|around)
896     # The fact is that in a stack trace, it will be fairly
897     # evident from the context what method they are attached
898     # to, and so don't need the fully qualified name.
899 }
900
901 sub find_method_by_name {
902     my ($self, $method_name) = @_;
903     (defined $method_name && length $method_name)
904         || confess "You must define a method name to find";
905     foreach my $class ($self->linearized_isa) {
906         my $method = $self->initialize($class)->get_method($method_name);
907         return $method if defined $method;
908     }
909     return;
910 }
911
912 sub get_all_methods {
913     my $self = shift;
914
915     my %methods;
916     for my $class ( reverse $self->linearized_isa ) {
917         my $meta = $self->initialize($class);
918
919         $methods{$_} = $meta->get_method($_)
920             for $meta->get_method_list;
921     }
922
923     return values %methods;
924 }
925
926 sub get_all_method_names {
927     my $self = shift;
928     my %uniq;
929     return grep { !$uniq{$_}++ } map { $self->initialize($_)->get_method_list } $self->linearized_isa;
930 }
931
932 sub find_all_methods_by_name {
933     my ($self, $method_name) = @_;
934     (defined $method_name && length $method_name)
935         || confess "You must define a method name to find";
936     my @methods;
937     foreach my $class ($self->linearized_isa) {
938         # fetch the meta-class ...
939         my $meta = $self->initialize($class);
940         push @methods => {
941             name  => $method_name,
942             class => $class,
943             code  => $meta->get_method($method_name)
944         } if $meta->has_method($method_name);
945     }
946     return @methods;
947 }
948
949 sub find_next_method_by_name {
950     my ($self, $method_name) = @_;
951     (defined $method_name && length $method_name)
952         || confess "You must define a method name to find";
953     my @cpl = $self->linearized_isa;
954     shift @cpl; # discard ourselves
955     foreach my $class (@cpl) {
956         my $method = $self->initialize($class)->get_method($method_name);
957         return $method if defined $method;
958     }
959     return;
960 }
961
962 sub update_meta_instance_dependencies {
963     my $self = shift;
964
965     if ( $self->{meta_instance_dependencies} ) {
966         return $self->add_meta_instance_dependencies;
967     }
968 }
969
970 sub add_meta_instance_dependencies {
971     my $self = shift;
972
973     $self->remove_meta_instance_dependencies;
974
975     my @attrs = $self->get_all_attributes();
976
977     my %seen;
978     my @classes = grep { not $seen{ $_->name }++ }
979         map { $_->associated_class } @attrs;
980
981     foreach my $class (@classes) {
982         $class->add_dependent_meta_instance($self);
983     }
984
985     $self->{meta_instance_dependencies} = \@classes;
986 }
987
988 sub remove_meta_instance_dependencies {
989     my $self = shift;
990
991     if ( my $classes = delete $self->{meta_instance_dependencies} ) {
992         foreach my $class (@$classes) {
993             $class->remove_dependent_meta_instance($self);
994         }
995
996         return $classes;
997     }
998
999     return;
1000
1001 }
1002
1003 sub add_dependent_meta_instance {
1004     my ( $self, $metaclass ) = @_;
1005     push @{ $self->{dependent_meta_instances} }, $metaclass;
1006 }
1007
1008 sub remove_dependent_meta_instance {
1009     my ( $self, $metaclass ) = @_;
1010     my $name = $metaclass->name;
1011     @$_ = grep { $_->name ne $name } @$_
1012         for $self->{dependent_meta_instances};
1013 }
1014
1015 sub invalidate_meta_instances {
1016     my $self = shift;
1017     $_->invalidate_meta_instance()
1018         for $self, @{ $self->{dependent_meta_instances} };
1019 }
1020
1021 sub invalidate_meta_instance {
1022     my $self = shift;
1023     undef $self->{_meta_instance};
1024 }
1025
1026 # check if we can reinitialize
1027 sub is_pristine {
1028     my $self = shift;
1029
1030     # if any local attr is defined
1031     return if $self->get_attribute_list;
1032
1033     # or any non-declared methods
1034     for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1035         return if $method->isa("Class::MOP::Method::Generated");
1036         # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1037     }
1038
1039     return 1;
1040 }
1041
1042 ## Class closing
1043
1044 sub is_mutable   { 1 }
1045 sub is_immutable { 0 }
1046
1047 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1048
1049 sub _immutable_options {
1050     my ( $self, @args ) = @_;
1051
1052     return (
1053         inline_accessors   => 1,
1054         inline_constructor => 1,
1055         inline_destructor  => 0,
1056         debug              => 0,
1057         immutable_trait    => $self->immutable_trait,
1058         constructor_name   => $self->constructor_name,
1059         constructor_class  => $self->constructor_class,
1060         destructor_class   => $self->destructor_class,
1061         @args,
1062     );
1063 }
1064
1065 sub make_immutable {
1066     my ( $self, @args ) = @_;
1067
1068     if ( $self->is_mutable ) {
1069         $self->_initialize_immutable( $self->_immutable_options(@args) );
1070         $self->_rebless_as_immutable(@args);
1071         return $self;
1072     }
1073     else {
1074         return;
1075     }
1076 }
1077
1078 sub make_mutable {
1079     my $self = shift;
1080
1081     if ( $self->is_immutable ) {
1082         my @args = $self->immutable_options;
1083         $self->_rebless_as_mutable();
1084         $self->_remove_inlined_code(@args);
1085         delete $self->{__immutable};
1086         return $self;
1087     }
1088     else {
1089         return;
1090     }
1091 }
1092
1093 sub _rebless_as_immutable {
1094     my ( $self, @args ) = @_;
1095
1096     $self->{__immutable}{original_class} = ref $self;
1097
1098     bless $self => $self->_immutable_metaclass(@args);
1099 }
1100
1101 sub _immutable_metaclass {
1102     my ( $self, %args ) = @_;
1103
1104     if ( my $class = $args{immutable_metaclass} ) {
1105         return $class;
1106     }
1107
1108     my $trait = $args{immutable_trait} = $self->immutable_trait
1109         || confess "no immutable trait specified for $self";
1110
1111     my $meta      = $self->meta;
1112     my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1113
1114     my $class_name;
1115
1116     if ( $meta_attr and $trait eq $meta_attr->default ) {
1117         # if the trait is the same as the default we try and pick a
1118         # predictable name for the immutable metaclass
1119         $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1120     }
1121     else {
1122         $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1123             $trait, 'ForMetaClass', ref($self);
1124     }
1125
1126     return $class_name
1127         if Class::MOP::is_class_loaded($class_name);
1128
1129     # If the metaclass is a subclass of CMOP::Class which has had
1130     # metaclass roles applied (via Moose), then we want to make sure
1131     # that we preserve that anonymous class (see Fey::ORM for an
1132     # example of where this matters).
1133     my $meta_name
1134         = $meta->is_immutable
1135         ? $meta->_get_mutable_metaclass_name
1136         : ref $meta;
1137
1138     my $immutable_meta = $meta_name->create(
1139         $class_name,
1140         superclasses => [ ref $self ],
1141     );
1142
1143     Class::MOP::load_class($trait);
1144     for my $meth ( Class::MOP::Class->initialize($trait)->get_all_methods ) {
1145         my $meth_name = $meth->name;
1146
1147         if ( $immutable_meta->find_method_by_name( $meth_name ) ) {
1148             $immutable_meta->add_around_method_modifier( $meth_name, $meth->body );
1149         }
1150         else {
1151             $immutable_meta->add_method( $meth_name, $meth->clone );
1152         }
1153     }
1154
1155     $immutable_meta->make_immutable(
1156         inline_constructor => 0,
1157         inline_accessors   => 0,
1158     );
1159
1160     return $class_name;
1161 }
1162
1163 sub _remove_inlined_code {
1164     my $self = shift;
1165
1166     $self->remove_method( $_->name ) for $self->_inlined_methods;
1167
1168     delete $self->{__immutable}{inlined_methods};
1169 }
1170
1171 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1172
1173 sub _add_inlined_method {
1174     my ( $self, $method ) = @_;
1175
1176     push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1177 }
1178
1179 sub _initialize_immutable {
1180     my ( $self, %args ) = @_;
1181
1182     $self->{__immutable}{options} = \%args;
1183     $self->_install_inlined_code(%args);
1184 }
1185
1186 sub _install_inlined_code {
1187     my ( $self, %args ) = @_;
1188
1189     # FIXME
1190     $self->_inline_accessors(%args)   if $args{inline_accessors};
1191     $self->_inline_constructor(%args) if $args{inline_constructor};
1192     $self->_inline_destructor(%args)  if $args{inline_destructor};
1193 }
1194
1195 sub _rebless_as_mutable {
1196     my $self = shift;
1197
1198     bless $self, $self->_get_mutable_metaclass_name;
1199
1200     return $self;
1201 }
1202
1203 sub _inline_accessors {
1204     my $self = shift;
1205
1206     foreach my $attr_name ( $self->get_attribute_list ) {
1207         $self->get_attribute($attr_name)->install_accessors(1);
1208     }
1209 }
1210
1211 sub _inline_constructor {
1212     my ( $self, %args ) = @_;
1213
1214     my $name = $args{constructor_name};
1215     # A class may not even have a constructor, and that's okay.
1216     return unless defined $name;
1217
1218     if ( $self->has_method($name) && !$args{replace_constructor} ) {
1219         my $class = $self->name;
1220         warn "Not inlining a constructor for $class since it defines"
1221             . " its own constructor.\n"
1222             . "If you are certain you don't need to inline your"
1223             . " constructor, specify inline_constructor => 0 in your"
1224             . " call to $class->meta->make_immutable\n";
1225         return;
1226     }
1227
1228     my $constructor_class = $args{constructor_class};
1229
1230     Class::MOP::load_class($constructor_class);
1231
1232     my $constructor = $constructor_class->new(
1233         options      => \%args,
1234         metaclass    => $self,
1235         is_inline    => 1,
1236         package_name => $self->name,
1237         name         => $name,
1238     );
1239
1240     if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1241         $self->add_method( $name => $constructor );
1242         $self->_add_inlined_method($constructor);
1243     }
1244 }
1245
1246 sub _inline_destructor {
1247     my ( $self, %args ) = @_;
1248
1249     ( exists $args{destructor_class} && defined $args{destructor_class} )
1250         || confess "The 'inline_destructor' option is present, but "
1251         . "no destructor class was specified";
1252
1253     if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1254         my $class = $self->name;
1255         warn "Not inlining a destructor for $class since it defines"
1256             . " its own destructor.\n";
1257         return;
1258     }
1259
1260     my $destructor_class = $args{destructor_class};
1261
1262     Class::MOP::load_class($destructor_class);
1263
1264     return unless $destructor_class->is_needed($self);
1265
1266     my $destructor = $destructor_class->new(
1267         options      => \%args,
1268         metaclass    => $self,
1269         package_name => $self->name,
1270         name         => 'DESTROY'
1271     );
1272
1273     if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1274         $self->add_method( 'DESTROY' => $destructor );
1275         $self->_add_inlined_method($destructor);
1276     }
1277 }
1278
1279 1;
1280
1281 __END__
1282
1283 =pod
1284
1285 =head1 NAME
1286
1287 Class::MOP::Class - Class Meta Object
1288
1289 =head1 SYNOPSIS
1290
1291   # assuming that class Foo
1292   # has been defined, you can
1293
1294   # use this for introspection ...
1295
1296   # add a method to Foo ...
1297   Foo->meta->add_method( 'bar' => sub {...} )
1298
1299   # get a list of all the classes searched
1300   # the method dispatcher in the correct order
1301   Foo->meta->class_precedence_list()
1302
1303   # remove a method from Foo
1304   Foo->meta->remove_method('bar');
1305
1306   # or use this to actually create classes ...
1307
1308   Class::MOP::Class->create(
1309       'Bar' => (
1310           version      => '0.01',
1311           superclasses => ['Foo'],
1312           attributes   => [
1313               Class::MOP::Attribute->new('$bar'),
1314               Class::MOP::Attribute->new('$baz'),
1315           ],
1316           methods => {
1317               calculate_bar => sub {...},
1318               construct_baz => sub {...}
1319           }
1320       )
1321   );
1322
1323 =head1 DESCRIPTION
1324
1325 The Class Protocol is the largest and most complex part of the
1326 Class::MOP meta-object protocol. It controls the introspection and
1327 manipulation of Perl 5 classes, and it can create them as well. The
1328 best way to understand what this module can do is to read the
1329 documentation for each of its methods.
1330
1331 =head1 INHERITANCE
1332
1333 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1334
1335 =head1 METHODS
1336
1337 =head2 Class construction
1338
1339 These methods all create new C<Class::MOP::Class> objects. These
1340 objects can represent existing classes or they can be used to create
1341 new classes from scratch.
1342
1343 The metaclass object for a given class is a singleton. If you attempt
1344 to create a metaclass for the same class twice, you will just get the
1345 existing object.
1346
1347 =over 4
1348
1349 =item B<< Class::MOP::Class->create($package_name, %options) >>
1350
1351 This method creates a new C<Class::MOP::Class> object with the given
1352 package name. It accepts a number of options:
1353
1354 =over 8
1355
1356 =item * version
1357
1358 An optional version number for the newly created package.
1359
1360 =item * authority
1361
1362 An optional authority for the newly created package.
1363
1364 =item * superclasses
1365
1366 An optional array reference of superclass names.
1367
1368 =item * methods
1369
1370 An optional hash reference of methods for the class. The keys of the
1371 hash reference are method names and values are subroutine references.
1372
1373 =item * attributes
1374
1375 An optional array reference of L<Class::MOP::Attribute> objects.
1376
1377 =back
1378
1379 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1380
1381 This method works just like C<< Class::MOP::Class->create >> but it
1382 creates an "anonymous" class. In fact, the class does have a name, but
1383 that name is a unique name generated internally by this module.
1384
1385 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1386 parameters that C<create> accepts.
1387
1388 Anonymous classes are destroyed once the metaclass they are attached
1389 to goes out of scope, and will be removed from Perl's internal symbol
1390 table.
1391
1392 All instances of an anonymous class keep a special reference to the
1393 metaclass object, which prevents the metaclass from going out of scope
1394 while any instances exist.
1395
1396 This only works if the instance is based on a hash reference, however.
1397
1398 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1399
1400 This method will initialize a C<Class::MOP::Class> object for the
1401 named package. Unlike C<create>, this method I<will not> create a new
1402 class.
1403
1404 The purpose of this method is to retrieve a C<Class::MOP::Class>
1405 object for introspecting an existing class.
1406
1407 If an existing C<Class::MOP::Class> object exists for the named
1408 package, it will be returned, and any options provided will be
1409 ignored!
1410
1411 If the object does not yet exist, it will be created.
1412
1413 The valid options that can be passed to this method are
1414 C<attribute_metaclass>, C<method_metaclass>,
1415 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1416 optional, and default to the appropriate class in the C<Class::MOP>
1417 distribution.
1418
1419 =back
1420
1421 =head2 Object instance construction and cloning
1422
1423 These methods are all related to creating and/or cloning object
1424 instances.
1425
1426 =over 4
1427
1428 =item B<< $metaclass->clone_object($instance, %params) >>
1429
1430 This method clones an existing object instance. Any parameters you
1431 provide are will override existing attribute values in the object.
1432
1433 This is a convenience method for cloning an object instance, then
1434 blessing it into the appropriate package.
1435
1436 You could implement a clone method in your class, using this method:
1437
1438   sub clone {
1439       my ($self, %params) = @_;
1440       $self->meta->clone_object($self, %params);
1441   }
1442
1443 =item B<< $metaclass->rebless_instance($instance, %params) >>
1444
1445 This method changes the class of C<$instance> to the metaclass's class.
1446
1447 You can only rebless an instance into a subclass of its current
1448 class. If you pass any additional parameters, these will be treated
1449 like constructor parameters and used to initialize the object's
1450 attributes. Any existing attributes that are already set will be
1451 overwritten.
1452
1453 Before reblessing the instance, this method will call
1454 C<rebless_instance_away> on the instance's current metaclass. This method
1455 will be passed the instance, the new metaclass, and any parameters
1456 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1457 does nothing; it is merely a hook.
1458
1459 =item B<< $metaclass->rebless_instance_back($instance) >>
1460
1461 Does the same thing as C<rebless_instance>, except that you can only
1462 rebless an instance into one of its superclasses. Any attributes that
1463 do not exist in the superclass will be deinitialized.
1464
1465 This is a much more dangerous operation than C<rebless_instance>,
1466 especially when multiple inheritance is involved, so use this carefully!
1467
1468 =item B<< $metaclass->new_object(%params) >>
1469
1470 This method is used to create a new object of the metaclass's
1471 class. Any parameters you provide are used to initialize the
1472 instance's attributes. A special C<__INSTANCE__> key can be passed to
1473 provide an already generated instance, rather than having Class::MOP
1474 generate it for you. This is mostly useful for using Class::MOP with
1475 foreign classes which generate instances using their own constructors.
1476
1477 =item B<< $metaclass->instance_metaclass >>
1478
1479 Returns the class name of the instance metaclass. See
1480 L<Class::MOP::Instance> for more information on the instance
1481 metaclass.
1482
1483 =item B<< $metaclass->get_meta_instance >>
1484
1485 Returns an instance of the C<instance_metaclass> to be used in the
1486 construction of a new instance of the class.
1487
1488 =back
1489
1490 =head2 Informational predicates
1491
1492 These are a few predicate methods for asking information about the
1493 class itself.
1494
1495 =over 4
1496
1497 =item B<< $metaclass->is_anon_class >>
1498
1499 This returns true if the class was created by calling C<<
1500 Class::MOP::Class->create_anon_class >>.
1501
1502 =item B<< $metaclass->is_mutable >>
1503
1504 This returns true if the class is still mutable.
1505
1506 =item B<< $metaclass->is_immutable >>
1507
1508 This returns true if the class has been made immutable.
1509
1510 =item B<< $metaclass->is_pristine >>
1511
1512 A class is I<not> pristine if it has non-inherited attributes or if it
1513 has any generated methods.
1514
1515 =back
1516
1517 =head2 Inheritance Relationships
1518
1519 =over 4
1520
1521 =item B<< $metaclass->superclasses(@superclasses) >>
1522
1523 This is a read-write accessor which represents the superclass
1524 relationships of the metaclass's class.
1525
1526 This is basically sugar around getting and setting C<@ISA>.
1527
1528 =item B<< $metaclass->class_precedence_list >>
1529
1530 This returns a list of all of the class's ancestor classes. The
1531 classes are returned in method dispatch order.
1532
1533 =item B<< $metaclass->linearized_isa >>
1534
1535 This returns a list based on C<class_precedence_list> but with all
1536 duplicates removed.
1537
1538 =item B<< $metaclass->subclasses >>
1539
1540 This returns a list of all subclasses for this class, even indirect
1541 subclasses.
1542
1543 =item B<< $metaclass->direct_subclasses >>
1544
1545 This returns a list of immediate subclasses for this class, which does not
1546 include indirect subclasses.
1547
1548 =back
1549
1550 =head2 Method introspection and creation
1551
1552 These methods allow you to introspect a class's methods, as well as
1553 add, remove, or change methods.
1554
1555 Determining what is truly a method in a Perl 5 class requires some
1556 heuristics (aka guessing).
1557
1558 Methods defined outside the package with a fully qualified name (C<sub
1559 Package::name { ... }>) will be included. Similarly, methods named
1560 with a fully qualified name using L<Sub::Name> are also included.
1561
1562 However, we attempt to ignore imported functions.
1563
1564 Ultimately, we are using heuristics to determine what truly is a
1565 method in a class, and these heuristics may get the wrong answer in
1566 some edge cases. However, for most "normal" cases the heuristics work
1567 correctly.
1568
1569 =over 4
1570
1571 =item B<< $metaclass->get_method($method_name) >>
1572
1573 This will return a L<Class::MOP::Method> for the specified
1574 C<$method_name>. If the class does not have the specified method, it
1575 returns C<undef>
1576
1577 =item B<< $metaclass->has_method($method_name) >>
1578
1579 Returns a boolean indicating whether or not the class defines the
1580 named method. It does not include methods inherited from parent
1581 classes.
1582
1583 =item B<< $metaclass->get_method_list >>
1584
1585 This will return a list of method I<names> for all methods defined in
1586 this class.
1587
1588 =item B<< $metaclass->add_method($method_name, $method) >>
1589
1590 This method takes a method name and a subroutine reference, and adds
1591 the method to the class.
1592
1593 The subroutine reference can be a L<Class::MOP::Method>, and you are
1594 strongly encouraged to pass a meta method object instead of a code
1595 reference. If you do so, that object gets stored as part of the
1596 class's method map directly. If not, the meta information will have to
1597 be recreated later, and may be incorrect.
1598
1599 If you provide a method object, this method will clone that object if
1600 the object's package name does not match the class name. This lets us
1601 track the original source of any methods added from other classes
1602 (notably Moose roles).
1603
1604 =item B<< $metaclass->remove_method($method_name) >>
1605
1606 Remove the named method from the class. This method returns the
1607 L<Class::MOP::Method> object for the method.
1608
1609 =item B<< $metaclass->method_metaclass >>
1610
1611 Returns the class name of the method metaclass, see
1612 L<Class::MOP::Method> for more information on the method metaclass.
1613
1614 =item B<< $metaclass->wrapped_method_metaclass >>
1615
1616 Returns the class name of the wrapped method metaclass, see
1617 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1618 method metaclass.
1619
1620 =item B<< $metaclass->get_all_methods >>
1621
1622 This will traverse the inheritance hierarchy and return a list of all
1623 the L<Class::MOP::Method> objects for this class and its parents.
1624
1625 =item B<< $metaclass->find_method_by_name($method_name) >>
1626
1627 This will return a L<Class::MOP::Method> for the specified
1628 C<$method_name>. If the class does not have the specified method, it
1629 returns C<undef>
1630
1631 Unlike C<get_method>, this method I<will> look for the named method in
1632 superclasses.
1633
1634 =item B<< $metaclass->get_all_method_names >>
1635
1636 This will return a list of method I<names> for all of this class's
1637 methods, including inherited methods.
1638
1639 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1640
1641 This method looks for the named method in the class and all of its
1642 parents. It returns every matching method it finds in the inheritance
1643 tree, so it returns a list of methods.
1644
1645 Each method is returned as a hash reference with three keys. The keys
1646 are C<name>, C<class>, and C<code>. The C<code> key has a
1647 L<Class::MOP::Method> object as its value.
1648
1649 The list of methods is distinct.
1650
1651 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1652
1653 This method returns the first method in any superclass matching the
1654 given name. It is effectively the method that C<SUPER::$method_name>
1655 would dispatch to.
1656
1657 =back
1658
1659 =head2 Attribute introspection and creation
1660
1661 Because Perl 5 does not have a core concept of attributes in classes,
1662 we can only return information about attributes which have been added
1663 via this class's methods. We cannot discover information about
1664 attributes which are defined in terms of "regular" Perl 5 methods.
1665
1666 =over 4
1667
1668 =item B<< $metaclass->get_attribute($attribute_name) >>
1669
1670 This will return a L<Class::MOP::Attribute> for the specified
1671 C<$attribute_name>. If the class does not have the specified
1672 attribute, it returns C<undef>.
1673
1674 NOTE that get_attribute does not search superclasses, for that you
1675 need to use C<find_attribute_by_name>.
1676
1677 =item B<< $metaclass->has_attribute($attribute_name) >>
1678
1679 Returns a boolean indicating whether or not the class defines the
1680 named attribute. It does not include attributes inherited from parent
1681 classes.
1682
1683 =item B<< $metaclass->get_attribute_list >>
1684
1685 This will return a list of attributes I<names> for all attributes
1686 defined in this class.
1687
1688 =item B<< $metaclass->get_all_attributes >>
1689
1690 This will traverse the inheritance hierarchy and return a list of all
1691 the L<Class::MOP::Attribute> objects for this class and its parents.
1692
1693 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1694
1695 This will return a L<Class::MOP::Attribute> for the specified
1696 C<$attribute_name>. If the class does not have the specified
1697 attribute, it returns C<undef>.
1698
1699 Unlike C<get_attribute>, this attribute I<will> look for the named
1700 attribute in superclasses.
1701
1702 =item B<< $metaclass->add_attribute(...) >>
1703
1704 This method accepts either an existing L<Class::MOP::Attribute>
1705 object or parameters suitable for passing to that class's C<new>
1706 method.
1707
1708 The attribute provided will be added to the class.
1709
1710 Any accessor methods defined by the attribute will be added to the
1711 class when the attribute is added.
1712
1713 If an attribute of the same name already exists, the old attribute
1714 will be removed first.
1715
1716 =item B<< $metaclass->remove_attribute($attribute_name) >>
1717
1718 This will remove the named attribute from the class, and
1719 L<Class::MOP::Attribute> object.
1720
1721 Removing an attribute also removes any accessor methods defined by the
1722 attribute.
1723
1724 However, note that removing an attribute will only affect I<future>
1725 object instances created for this class, not existing instances.
1726
1727 =item B<< $metaclass->attribute_metaclass >>
1728
1729 Returns the class name of the attribute metaclass for this class. By
1730 default, this is L<Class::MOP::Attribute>.
1731
1732 =back
1733
1734 =head2 Class Immutability
1735
1736 Making a class immutable "freezes" the class definition. You can no
1737 longer call methods which alter the class, such as adding or removing
1738 methods or attributes.
1739
1740 Making a class immutable lets us optimize the class by inlining some
1741 methods, and also allows us to optimize some methods on the metaclass
1742 object itself.
1743
1744 After immutabilization, the metaclass object will cache most informational
1745 methods that returns information about methods or attributes. Methods which
1746 would alter the class, such as C<add_attribute> and C<add_method>, will
1747 throw an error on an immutable metaclass object.
1748
1749 The immutabilization system in L<Moose> takes much greater advantage
1750 of the inlining features than Class::MOP itself does.
1751
1752 =over 4
1753
1754 =item B<< $metaclass->make_immutable(%options) >>
1755
1756 This method will create an immutable transformer and use it to make
1757 the class and its metaclass object immutable.
1758
1759 This method accepts the following options:
1760
1761 =over 8
1762
1763 =item * inline_accessors
1764
1765 =item * inline_constructor
1766
1767 =item * inline_destructor
1768
1769 These are all booleans indicating whether the specified method(s)
1770 should be inlined.
1771
1772 By default, accessors and the constructor are inlined, but not the
1773 destructor.
1774
1775 =item * immutable_trait
1776
1777 The name of a class which will be used as a parent class for the
1778 metaclass object being made immutable. This "trait" implements the
1779 post-immutability functionality of the metaclass (but not the
1780 transformation itself).
1781
1782 This defaults to L<Class::MOP::Class::Immutable::Trait>.
1783
1784 =item * constructor_name
1785
1786 This is the constructor method name. This defaults to "new".
1787
1788 =item * constructor_class
1789
1790 The name of the method metaclass for constructors. It will be used to
1791 generate the inlined constructor. This defaults to
1792 "Class::MOP::Method::Constructor".
1793
1794 =item * replace_constructor
1795
1796 This is a boolean indicating whether an existing constructor should be
1797 replaced when inlining a constructor. This defaults to false.
1798
1799 =item * destructor_class
1800
1801 The name of the method metaclass for destructors. It will be used to
1802 generate the inlined destructor. This defaults to
1803 "Class::MOP::Method::Denstructor".
1804
1805 =item * replace_destructor
1806
1807 This is a boolean indicating whether an existing destructor should be
1808 replaced when inlining a destructor. This defaults to false.
1809
1810 =back
1811
1812 =item B<< $metaclass->immutable_options >>
1813
1814 Returns a hash of the options used when making the class immutable, including
1815 both defaults and anything supplied by the user in the call to C<<
1816 $metaclass->make_immutable >>. This is useful if you need to temporarily make
1817 a class mutable and then restore immutability as it was before.
1818
1819 =item B<< $metaclass->make_mutable >>
1820
1821 Calling this method reverse the immutabilization transformation.
1822
1823 =back
1824
1825 =head2 Method Modifiers
1826
1827 Method modifiers are hooks which allow a method to be wrapped with
1828 I<before>, I<after> and I<around> method modifiers. Every time a
1829 method is called, its modifiers are also called.
1830
1831 A class can modify its own methods, as well as methods defined in
1832 parent classes.
1833
1834 =head3 How method modifiers work?
1835
1836 Method modifiers work by wrapping the original method and then
1837 replacing it in the class's symbol table. The wrappers will handle
1838 calling all the modifiers in the appropriate order and preserving the
1839 calling context for the original method.
1840
1841 The return values of C<before> and C<after> modifiers are
1842 ignored. This is because their purpose is B<not> to filter the input
1843 and output of the primary method (this is done with an I<around>
1844 modifier).
1845
1846 This may seem like an odd restriction to some, but doing this allows
1847 for simple code to be added at the beginning or end of a method call
1848 without altering the function of the wrapped method or placing any
1849 extra responsibility on the code of the modifier.
1850
1851 Of course if you have more complex needs, you can use the C<around>
1852 modifier which allows you to change both the parameters passed to the
1853 wrapped method, as well as its return value.
1854
1855 Before and around modifiers are called in last-defined-first-called
1856 order, while after modifiers are called in first-defined-first-called
1857 order. So the call tree might looks something like this:
1858
1859   before 2
1860    before 1
1861     around 2
1862      around 1
1863       primary
1864      around 1
1865     around 2
1866    after 1
1867   after 2
1868
1869 =head3 What is the performance impact?
1870
1871 Of course there is a performance cost associated with method
1872 modifiers, but we have made every effort to make that cost directly
1873 proportional to the number of modifier features you use.
1874
1875 The wrapping method does its best to B<only> do as much work as it
1876 absolutely needs to. In order to do this we have moved some of the
1877 performance costs to set-up time, where they are easier to amortize.
1878
1879 All this said, our benchmarks have indicated the following:
1880
1881   simple wrapper with no modifiers             100% slower
1882   simple wrapper with simple before modifier   400% slower
1883   simple wrapper with simple after modifier    450% slower
1884   simple wrapper with simple around modifier   500-550% slower
1885   simple wrapper with all 3 modifiers          1100% slower
1886
1887 These numbers may seem daunting, but you must remember, every feature
1888 comes with some cost. To put things in perspective, just doing a
1889 simple C<AUTOLOAD> which does nothing but extract the name of the
1890 method called and return it costs about 400% over a normal method
1891 call.
1892
1893 =over 4
1894
1895 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
1896
1897 This wraps the specified method with the supplied subroutine
1898 reference. The modifier will be called as a method itself, and will
1899 receive the same arguments as are passed to the method.
1900
1901 When the modifier exits, the wrapped method will be called.
1902
1903 The return value of the modifier will be ignored.
1904
1905 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
1906
1907 This wraps the specified method with the supplied subroutine
1908 reference. The modifier will be called as a method itself, and will
1909 receive the same arguments as are passed to the method.
1910
1911 When the wrapped methods exits, the modifier will be called.
1912
1913 The return value of the modifier will be ignored.
1914
1915 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
1916
1917 This wraps the specified method with the supplied subroutine
1918 reference.
1919
1920 The first argument passed to the modifier will be a subroutine
1921 reference to the wrapped method. The second argument is the object,
1922 and after that come any arguments passed when the method is called.
1923
1924 The around modifier can choose to call the original method, as well as
1925 what arguments to pass if it does so.
1926
1927 The return value of the modifier is what will be seen by the caller.
1928
1929 =back
1930
1931 =head2 Introspection
1932
1933 =over 4
1934
1935 =item B<< Class::MOP::Class->meta >>
1936
1937 This will return a L<Class::MOP::Class> instance for this class.
1938
1939 It should also be noted that L<Class::MOP> will actually bootstrap
1940 this module by installing a number of attribute meta-objects into its
1941 metaclass.
1942
1943 =back
1944
1945 =head1 AUTHORS
1946
1947 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1948
1949 =head1 COPYRIGHT AND LICENSE
1950
1951 Copyright 2006-2010 by Infinity Interactive, Inc.
1952
1953 L<http://www.iinteractive.com>
1954
1955 This library is free software; you can redistribute it and/or modify
1956 it under the same terms as Perl itself.
1957
1958 =cut