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