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