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