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