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