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