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