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