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