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