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