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