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