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