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