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