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