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