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