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