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