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