Version 1.02
[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.02';
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 unless defined $super_meta->$metaclass_type;
261     # if metaclass is defined in superclass but not here, it's not compatible
262     # this is a really odd case
263     return 0 unless defined $self->$metaclass_type;
264
265     return $self->$metaclass_type->isa($super_meta->$metaclass_type);
266 }
267
268 sub _check_single_metaclass_compatibility {
269     my $self = shift;
270     my ( $metaclass_type, $superclass_name ) = @_;
271
272     if (!$self->_single_metaclass_is_compatible($metaclass_type, $superclass_name)) {
273         my $super_meta = Class::MOP::get_metaclass_by_name($superclass_name);
274         my $metaclass_type_name = $metaclass_type;
275         $metaclass_type_name =~ s/_(?:meta)?class$//;
276         $metaclass_type_name =~ s/_/ /g;
277         confess "The $metaclass_type_name metaclass for "
278               . $self->name . " (" . ($self->$metaclass_type)
279               . ")" . " is not compatible with the "
280               . "$metaclass_type_name metaclass of its "
281               . "superclass, " . $superclass_name . " ("
282               . ($super_meta->$metaclass_type) . ")";
283     }
284 }
285
286 sub _can_fix_class_metaclass_incompatibility_by_subclassing {
287     my $self = shift;
288     my ($super_meta) = @_;
289
290     my $super_meta_type = $super_meta->_real_ref_name;
291
292     return $super_meta_type ne blessed($self)
293         && $super_meta->isa(blessed($self));
294 }
295
296 sub _can_fix_single_metaclass_incompatibility_by_subclassing {
297     my $self = shift;
298     my ($metaclass_type, $super_meta) = @_;
299
300     my $specific_meta = $self->$metaclass_type;
301     return unless $super_meta->can($metaclass_type);
302     my $super_specific_meta = $super_meta->$metaclass_type;
303
304     # for instance, Moose::Meta::Class has a destructor_class, but
305     # Class::MOP::Class doesn't - this shouldn't be an error
306     return unless defined $super_specific_meta;
307
308     # if metaclass is defined in superclass but not here, it's fixable
309     # this is a really odd case
310     return 1 unless defined $specific_meta;
311
312     return $specific_meta ne $super_specific_meta
313         && $super_specific_meta->isa($specific_meta);
314 }
315
316 sub _can_fix_metaclass_incompatibility_by_subclassing {
317     my $self = shift;
318     my ($super_meta) = @_;
319
320     return 1 if $self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta);
321
322     my %base_metaclass = $self->_base_metaclasses;
323     for my $metaclass_type (keys %base_metaclass) {
324         return 1 if $self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta);
325     }
326
327     return;
328 }
329
330 sub _can_fix_metaclass_incompatibility {
331     my $self = shift;
332     return $self->_can_fix_metaclass_incompatibility_by_subclassing(@_);
333 }
334
335 sub _fix_metaclass_incompatibility {
336     my $self = shift;
337     my @supers = map { Class::MOP::Class->initialize($_) } @_;
338
339     my $necessary = 0;
340     for my $super (@supers) {
341         $necessary = 1
342             if $self->_can_fix_metaclass_incompatibility($super);
343     }
344     return unless $necessary;
345
346     for my $super (@supers) {
347         if (!$self->_class_metaclass_is_compatible($super->name)) {
348             $self->_fix_class_metaclass_incompatibility($super);
349         }
350     }
351
352     my %base_metaclass = $self->_base_metaclasses;
353     for my $metaclass_type (keys %base_metaclass) {
354         for my $super (@supers) {
355             if (!$self->_single_metaclass_is_compatible($metaclass_type, $super->name)) {
356                 $self->_fix_single_metaclass_incompatibility(
357                     $metaclass_type, $super
358                 );
359             }
360         }
361     }
362 }
363
364 sub _fix_class_metaclass_incompatibility {
365     my $self = shift;
366     my ( $super_meta ) = @_;
367
368     if ($self->_can_fix_class_metaclass_incompatibility_by_subclassing($super_meta)) {
369         ($self->is_pristine)
370             || confess "Can't fix metaclass incompatibility for "
371                      . $self->name
372                      . " because it is not pristine.";
373
374         my $super_meta_name = $super_meta->_real_ref_name;
375
376         $super_meta_name->meta->rebless_instance($self);
377     }
378 }
379
380 sub _fix_single_metaclass_incompatibility {
381     my $self = shift;
382     my ( $metaclass_type, $super_meta ) = @_;
383
384     if ($self->_can_fix_single_metaclass_incompatibility_by_subclassing($metaclass_type, $super_meta)) {
385         ($self->is_pristine)
386             || confess "Can't fix metaclass incompatibility for "
387                      . $self->name
388                      . " because it is not pristine.";
389
390         $self->{$metaclass_type} = $super_meta->$metaclass_type;
391     }
392 }
393
394 ## ANON classes
395
396 {
397     # NOTE:
398     # this should be sufficient, if you have a
399     # use case where it is not, write a test and
400     # I will change it.
401     my $ANON_CLASS_SERIAL = 0;
402
403     # NOTE:
404     # we need a sufficiently annoying prefix
405     # this should suffice for now, this is
406     # used in a couple of places below, so
407     # need to put it up here for now.
408     my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';
409
410     sub is_anon_class {
411         my $self = shift;
412         no warnings 'uninitialized';
413         $self->name =~ /^$ANON_CLASS_PREFIX/o;
414     }
415
416     sub create_anon_class {
417         my ($class, %options) = @_;
418         my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
419         return $class->create($package_name, %options);
420     }
421
422     # NOTE:
423     # this will only get called for
424     # anon-classes, all other calls
425     # are assumed to occur during
426     # global destruction and so don't
427     # really need to be handled explicitly
428     sub DESTROY {
429         my $self = shift;
430
431         return if in_global_destruction(); # it'll happen soon anyway and this just makes things more complicated
432
433         no warnings 'uninitialized';
434         my $name = $self->name;
435         return unless $name =~ /^$ANON_CLASS_PREFIX/o;
436
437         # Moose does a weird thing where it replaces the metaclass for
438         # class when fixing metaclass incompatibility. In that case,
439         # we don't want to clean out the namespace now. We can detect
440         # that because Moose will explicitly update the singleton
441         # cache in Class::MOP.
442         my $current_meta = Class::MOP::get_metaclass_by_name($name);
443         return if $current_meta ne $self;
444
445         my ($serial_id) = ($name =~ /^$ANON_CLASS_PREFIX(\d+)/o);
446         no strict 'refs';
447         @{$name . '::ISA'} = ();
448         %{$name . '::'}    = ();
449         delete ${$ANON_CLASS_PREFIX}{$serial_id . '::'};
450
451         Class::MOP::remove_metaclass_by_name($name);
452     }
453
454 }
455
456 # creating classes with MOP ...
457
458 sub create {
459     my ( $class, @args ) = @_;
460
461     unshift @args, 'package' if @args % 2 == 1;
462
463     my (%options) = @args;
464     my $package_name = $options{package};
465
466     (ref $options{superclasses} eq 'ARRAY')
467         || confess "You must pass an ARRAY ref of superclasses"
468             if exists $options{superclasses};
469             
470     (ref $options{attributes} eq 'ARRAY')
471         || confess "You must pass an ARRAY ref of attributes"
472             if exists $options{attributes};      
473             
474     (ref $options{methods} eq 'HASH')
475         || confess "You must pass a HASH ref of methods"
476             if exists $options{methods};                  
477
478     my (%initialize_options) = @args;
479     delete @initialize_options{qw(
480         package
481         superclasses
482         attributes
483         methods
484         version
485         authority
486     )};
487     my $meta = $class->initialize( $package_name => %initialize_options );
488
489     $meta->_instantiate_module( $options{version}, $options{authority} );
490
491     # FIXME totally lame
492     $meta->add_method('meta' => sub {
493         $class->initialize(ref($_[0]) || $_[0]);
494     });
495
496     $meta->superclasses(@{$options{superclasses}})
497         if exists $options{superclasses};
498     # NOTE:
499     # process attributes first, so that they can
500     # install accessors, but locally defined methods
501     # can then overwrite them. It is maybe a little odd, but
502     # I think this should be the order of things.
503     if (exists $options{attributes}) {
504         foreach my $attr (@{$options{attributes}}) {
505             $meta->add_attribute($attr);
506         }
507     }
508     if (exists $options{methods}) {
509         foreach my $method_name (keys %{$options{methods}}) {
510             $meta->add_method($method_name, $options{methods}->{$method_name});
511         }
512     }
513     return $meta;
514 }
515
516 ## Attribute readers
517
518 # NOTE:
519 # all these attribute readers will be bootstrapped
520 # away in the Class::MOP bootstrap section
521
522 sub instance_metaclass       { $_[0]->{'instance_metaclass'}          }
523 sub immutable_trait          { $_[0]->{'immutable_trait'}             }
524 sub constructor_class        { $_[0]->{'constructor_class'}           }
525 sub constructor_name         { $_[0]->{'constructor_name'}            }
526 sub destructor_class         { $_[0]->{'destructor_class'}            }
527
528 # Instance Construction & Cloning
529
530 sub new_object {
531     my $class = shift;
532
533     # NOTE:
534     # we need to protect the integrity of the
535     # Class::MOP::Class singletons here, so we
536     # delegate this to &construct_class_instance
537     # which will deal with the singletons
538     return $class->_construct_class_instance(@_)
539         if $class->name->isa('Class::MOP::Class');
540     return $class->_construct_instance(@_);
541 }
542
543 sub _construct_instance {
544     my $class = shift;
545     my $params = @_ == 1 ? $_[0] : {@_};
546     my $meta_instance = $class->get_meta_instance();
547     # FIXME:
548     # the code below is almost certainly incorrect
549     # but this is foreign inheritance, so we might
550     # have to kludge it in the end.
551     my $instance;
552     if (my $instance_class = blessed($params->{__INSTANCE__})) {
553         ($instance_class eq $class->name)
554             || confess "Objects passed as the __INSTANCE__ parameter must "
555                      . "already be blessed into the correct class, but "
556                      . "$params->{__INSTANCE__} is not a " . $class->name;
557         $instance = $params->{__INSTANCE__};
558     }
559     elsif (exists $params->{__INSTANCE__}) {
560         confess "The __INSTANCE__ parameter must be a blessed reference, not "
561               . $params->{__INSTANCE__};
562     }
563     else {
564         $instance = $meta_instance->create_instance();
565     }
566     foreach my $attr ($class->get_all_attributes()) {
567         $attr->initialize_instance_slot($meta_instance, $instance, $params);
568     }
569     # NOTE:
570     # this will only work for a HASH instance type
571     if ($class->is_anon_class) {
572         (reftype($instance) eq 'HASH')
573             || confess "Currently only HASH based instances are supported with instance of anon-classes";
574         # NOTE:
575         # At some point we should make this official
576         # as a reserved slot name, but right now I am
577         # going to keep it here.
578         # my $RESERVED_MOP_SLOT = '__MOP__';
579         $instance->{'__MOP__'} = $class;
580     }
581     return $instance;
582 }
583
584
585 sub get_meta_instance {
586     my $self = shift;
587     $self->{'_meta_instance'} ||= $self->_create_meta_instance();
588 }
589
590 sub _create_meta_instance {
591     my $self = shift;
592     
593     my $instance = $self->instance_metaclass->new(
594         associated_metaclass => $self,
595         attributes => [ $self->get_all_attributes() ],
596     );
597
598     $self->add_meta_instance_dependencies()
599         if $instance->is_dependent_on_superclasses();
600
601     return $instance;
602 }
603
604 sub clone_object {
605     my $class    = shift;
606     my $instance = shift;
607     (blessed($instance) && $instance->isa($class->name))
608         || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
609
610     # NOTE:
611     # we need to protect the integrity of the
612     # Class::MOP::Class singletons here, they
613     # should not be cloned.
614     return $instance if $instance->isa('Class::MOP::Class');
615     $class->_clone_instance($instance, @_);
616 }
617
618 sub _clone_instance {
619     my ($class, $instance, %params) = @_;
620     (blessed($instance))
621         || confess "You can only clone instances, ($instance) is not a blessed instance";
622     my $meta_instance = $class->get_meta_instance();
623     my $clone = $meta_instance->clone_instance($instance);
624     foreach my $attr ($class->get_all_attributes()) {
625         if ( defined( my $init_arg = $attr->init_arg ) ) {
626             if (exists $params{$init_arg}) {
627                 $attr->set_value($clone, $params{$init_arg});
628             }
629         }
630     }
631     return $clone;
632 }
633
634 sub rebless_instance {
635     my ($self, $instance, %params) = @_;
636
637     my $old_metaclass = Class::MOP::class_of($instance);
638
639     my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
640     $self->name->isa($old_class)
641         || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
642
643     $old_metaclass->rebless_instance_away($instance, $self, %params)
644         if $old_metaclass;
645
646     my $meta_instance = $self->get_meta_instance();
647
648     # rebless!
649     # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
650     $meta_instance->rebless_instance_structure($_[1], $self);
651
652     foreach my $attr ( $self->get_all_attributes ) {
653         if ( $attr->has_value($instance) ) {
654             if ( defined( my $init_arg = $attr->init_arg ) ) {
655                 $params{$init_arg} = $attr->get_value($instance)
656                     unless exists $params{$init_arg};
657             } 
658             else {
659                 $attr->set_value($instance, $attr->get_value($instance));
660             }
661         }
662     }
663
664     foreach my $attr ($self->get_all_attributes) {
665         $attr->initialize_instance_slot($meta_instance, $instance, \%params);
666     }
667     
668     $instance;
669 }
670
671 sub rebless_instance_back {
672     my ( $self, $instance ) = @_;
673
674     my $old_metaclass = Class::MOP::class_of($instance);
675
676     my $old_class
677         = $old_metaclass ? $old_metaclass->name : blessed($instance);
678     $old_class->isa( $self->name )
679         || confess
680         "You may rebless only into a superclass of ($old_class), of which ("
681         . $self->name
682         . ") isn't.";
683
684     $old_metaclass->rebless_instance_away( $instance, $self )
685         if $old_metaclass;
686
687     my $meta_instance = $self->get_meta_instance;
688
689     # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
690     $meta_instance->rebless_instance_structure( $_[1], $self );
691
692     for my $attr ( $old_metaclass->get_all_attributes ) {
693         next if $self->has_attribute( $attr->name );
694         $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
695     }
696
697     return $instance;
698 }
699
700 sub rebless_instance_away {
701     # this intentionally does nothing, it is just a hook
702 }
703
704 sub _attach_attribute {
705     my ($self, $attribute) = @_;
706     $attribute->attach_to_class($self);
707 }
708
709 sub _post_add_attribute {
710     my ( $self, $attribute ) = @_;
711
712     $self->invalidate_meta_instances;
713
714     # invalidate package flag here
715     try {
716         local $SIG{__DIE__};
717         $attribute->install_accessors;
718     }
719     catch {
720         $self->remove_attribute( $attribute->name );
721         die $_;
722     };
723 }
724
725 sub remove_attribute {
726     my $self = shift;
727
728     my $removed_attribute = $self->SUPER::remove_attribute(@_)
729         or return;
730
731     $self->invalidate_meta_instances;
732
733     $removed_attribute->remove_accessors;
734     $removed_attribute->detach_from_class;
735
736     return$removed_attribute;
737 }
738
739 sub find_attribute_by_name {
740     my ( $self, $attr_name ) = @_;
741
742     foreach my $class ( $self->linearized_isa ) {
743         # fetch the meta-class ...
744         my $meta = Class::MOP::Class->initialize($class);
745         return $meta->get_attribute($attr_name)
746             if $meta->has_attribute($attr_name);
747     }
748
749     return;
750 }
751
752 sub get_all_attributes {
753     my $self = shift;
754     my %attrs = map { %{ Class::MOP::Class->initialize($_)->_attribute_map } }
755         reverse $self->linearized_isa;
756     return values %attrs;
757 }
758
759 # Inheritance
760
761 sub superclasses {
762     my $self     = shift;
763     my $var_spec = { sigil => '@', type => 'ARRAY', name => 'ISA' };
764     if (@_) {
765         my @supers = @_;
766         @{$self->get_package_symbol($var_spec)} = @supers;
767
768         # NOTE:
769         # on 5.8 and below, we need to call
770         # a method to get Perl to detect
771         # a cycle in the class hierarchy
772         my $class = $self->name;
773         $class->isa($class);
774
775         # NOTE:
776         # we need to check the metaclass
777         # compatibility here so that we can
778         # be sure that the superclass is
779         # not potentially creating an issues
780         # we don't know about
781
782         $self->_check_metaclass_compatibility();
783         $self->_superclasses_updated();
784     }
785     @{$self->get_package_symbol($var_spec)};
786 }
787
788 sub _superclasses_updated {
789     my $self = shift;
790     $self->update_meta_instance_dependencies();
791 }
792
793 sub subclasses {
794     my $self = shift;
795     my $super_class = $self->name;
796
797     return @{ $super_class->mro::get_isarev() };
798 }
799
800 sub direct_subclasses {
801     my $self = shift;
802     my $super_class = $self->name;
803
804     return grep {
805         grep {
806             $_ eq $super_class
807         } Class::MOP::Class->initialize($_)->superclasses
808     } $self->subclasses;
809 }
810
811 sub linearized_isa {
812     return @{ mro::get_linear_isa( (shift)->name ) };
813 }
814
815 sub class_precedence_list {
816     my $self = shift;
817     my $name = $self->name;
818
819     unless (Class::MOP::IS_RUNNING_ON_5_10()) { 
820         # NOTE:
821         # We need to check for circular inheritance here
822         # if we are are not on 5.10, cause 5.8 detects it 
823         # late. This will do nothing if all is well, and 
824         # blow up otherwise. Yes, it's an ugly hack, better
825         # suggestions are welcome.        
826         # - SL
827         ($name || return)->isa('This is a test for circular inheritance') 
828     }
829
830     # if our mro is c3, we can 
831     # just grab the linear_isa
832     if (mro::get_mro($name) eq 'c3') {
833         return @{ mro::get_linear_isa($name) }
834     }
835     else {
836         # NOTE:
837         # we can't grab the linear_isa for dfs
838         # since it has all the duplicates 
839         # already removed.
840         return (
841             $name,
842             map {
843                 Class::MOP::Class->initialize($_)->class_precedence_list()
844             } $self->superclasses()
845         );
846     }
847 }
848
849 ## Methods
850
851 {
852     my $fetch_and_prepare_method = sub {
853         my ($self, $method_name) = @_;
854         my $wrapped_metaclass = $self->wrapped_method_metaclass;
855         # fetch it locally
856         my $method = $self->get_method($method_name);
857         # if we dont have local ...
858         unless ($method) {
859             # try to find the next method
860             $method = $self->find_next_method_by_name($method_name);
861             # die if it does not exist
862             (defined $method)
863                 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
864             # and now make sure to wrap it
865             # even if it is already wrapped
866             # because we need a new sub ref
867             $method = $wrapped_metaclass->wrap($method,
868                 package_name => $self->name,
869                 name         => $method_name,
870             );
871         }
872         else {
873             # now make sure we wrap it properly
874             $method = $wrapped_metaclass->wrap($method,
875                 package_name => $self->name,
876                 name         => $method_name,
877             ) unless $method->isa($wrapped_metaclass);
878         }
879         $self->add_method($method_name => $method);
880         return $method;
881     };
882
883     sub add_before_method_modifier {
884         my ($self, $method_name, $method_modifier) = @_;
885         (defined $method_name && length $method_name)
886             || confess "You must pass in a method name";
887         my $method = $fetch_and_prepare_method->($self, $method_name);
888         $method->add_before_modifier(
889             subname(':before' => $method_modifier)
890         );
891     }
892
893     sub add_after_method_modifier {
894         my ($self, $method_name, $method_modifier) = @_;
895         (defined $method_name && length $method_name)
896             || confess "You must pass in a method name";
897         my $method = $fetch_and_prepare_method->($self, $method_name);
898         $method->add_after_modifier(
899             subname(':after' => $method_modifier)
900         );
901     }
902
903     sub add_around_method_modifier {
904         my ($self, $method_name, $method_modifier) = @_;
905         (defined $method_name && length $method_name)
906             || confess "You must pass in a method name";
907         my $method = $fetch_and_prepare_method->($self, $method_name);
908         $method->add_around_modifier(
909             subname(':around' => $method_modifier)
910         );
911     }
912
913     # NOTE:
914     # the methods above used to be named like this:
915     #    ${pkg}::${method}:(before|after|around)
916     # but this proved problematic when using one modifier
917     # to wrap multiple methods (something which is likely
918     # to happen pretty regularly IMO). So instead of naming
919     # it like this, I have chosen to just name them purely
920     # with their modifier names, like so:
921     #    :(before|after|around)
922     # The fact is that in a stack trace, it will be fairly
923     # evident from the context what method they are attached
924     # to, and so don't need the fully qualified name.
925 }
926
927 sub find_method_by_name {
928     my ($self, $method_name) = @_;
929     (defined $method_name && length $method_name)
930         || confess "You must define a method name to find";
931     foreach my $class ($self->linearized_isa) {
932         my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
933         return $method if defined $method;
934     }
935     return;
936 }
937
938 sub get_all_methods {
939     my $self = shift;
940
941     my %methods;
942     for my $class ( reverse $self->linearized_isa ) {
943         my $meta = Class::MOP::Class->initialize($class);
944
945         $methods{$_} = $meta->get_method($_)
946             for $meta->get_method_list;
947     }
948
949     return values %methods;
950 }
951
952 sub get_all_method_names {
953     my $self = shift;
954     my %uniq;
955     return grep { !$uniq{$_}++ } map { Class::MOP::Class->initialize($_)->get_method_list } $self->linearized_isa;
956 }
957
958 sub find_all_methods_by_name {
959     my ($self, $method_name) = @_;
960     (defined $method_name && length $method_name)
961         || confess "You must define a method name to find";
962     my @methods;
963     foreach my $class ($self->linearized_isa) {
964         # fetch the meta-class ...
965         my $meta = Class::MOP::Class->initialize($class);
966         push @methods => {
967             name  => $method_name,
968             class => $class,
969             code  => $meta->get_method($method_name)
970         } if $meta->has_method($method_name);
971     }
972     return @methods;
973 }
974
975 sub find_next_method_by_name {
976     my ($self, $method_name) = @_;
977     (defined $method_name && length $method_name)
978         || confess "You must define a method name to find";
979     my @cpl = $self->linearized_isa;
980     shift @cpl; # discard ourselves
981     foreach my $class (@cpl) {
982         my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
983         return $method if defined $method;
984     }
985     return;
986 }
987
988 sub update_meta_instance_dependencies {
989     my $self = shift;
990
991     if ( $self->{meta_instance_dependencies} ) {
992         return $self->add_meta_instance_dependencies;
993     }
994 }
995
996 sub add_meta_instance_dependencies {
997     my $self = shift;
998
999     $self->remove_meta_instance_dependencies;
1000
1001     my @attrs = $self->get_all_attributes();
1002
1003     my %seen;
1004     my @classes = grep { not $seen{ $_->name }++ }
1005         map { $_->associated_class } @attrs;
1006
1007     foreach my $class (@classes) {
1008         $class->add_dependent_meta_instance($self);
1009     }
1010
1011     $self->{meta_instance_dependencies} = \@classes;
1012 }
1013
1014 sub remove_meta_instance_dependencies {
1015     my $self = shift;
1016
1017     if ( my $classes = delete $self->{meta_instance_dependencies} ) {
1018         foreach my $class (@$classes) {
1019             $class->remove_dependent_meta_instance($self);
1020         }
1021
1022         return $classes;
1023     }
1024
1025     return;
1026
1027 }
1028
1029 sub add_dependent_meta_instance {
1030     my ( $self, $metaclass ) = @_;
1031     push @{ $self->{dependent_meta_instances} }, $metaclass;
1032 }
1033
1034 sub remove_dependent_meta_instance {
1035     my ( $self, $metaclass ) = @_;
1036     my $name = $metaclass->name;
1037     @$_ = grep { $_->name ne $name } @$_
1038         for $self->{dependent_meta_instances};
1039 }
1040
1041 sub invalidate_meta_instances {
1042     my $self = shift;
1043     $_->invalidate_meta_instance()
1044         for $self, @{ $self->{dependent_meta_instances} };
1045 }
1046
1047 sub invalidate_meta_instance {
1048     my $self = shift;
1049     undef $self->{_meta_instance};
1050 }
1051
1052 # check if we can reinitialize
1053 sub is_pristine {
1054     my $self = shift;
1055
1056     # if any local attr is defined
1057     return if $self->get_attribute_list;
1058
1059     # or any non-declared methods
1060     for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1061         return if $method->isa("Class::MOP::Method::Generated");
1062         # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1063     }
1064
1065     return 1;
1066 }
1067
1068 ## Class closing
1069
1070 sub is_mutable   { 1 }
1071 sub is_immutable { 0 }
1072
1073 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1074
1075 sub _immutable_options {
1076     my ( $self, @args ) = @_;
1077
1078     return (
1079         inline_accessors   => 1,
1080         inline_constructor => 1,
1081         inline_destructor  => 0,
1082         debug              => 0,
1083         immutable_trait    => $self->immutable_trait,
1084         constructor_name   => $self->constructor_name,
1085         constructor_class  => $self->constructor_class,
1086         destructor_class   => $self->destructor_class,
1087         @args,
1088     );
1089 }
1090
1091 sub make_immutable {
1092     my ( $self, @args ) = @_;
1093
1094     if ( $self->is_mutable ) {
1095         $self->_initialize_immutable( $self->_immutable_options(@args) );
1096         $self->_rebless_as_immutable(@args);
1097         return $self;
1098     }
1099     else {
1100         return;
1101     }
1102 }
1103
1104 sub make_mutable {
1105     my $self = shift;
1106
1107     if ( $self->is_immutable ) {
1108         my @args = $self->immutable_options;
1109         $self->_rebless_as_mutable();
1110         $self->_remove_inlined_code(@args);
1111         delete $self->{__immutable};
1112         return $self;
1113     }
1114     else {
1115         return;
1116     }
1117 }
1118
1119 sub _rebless_as_immutable {
1120     my ( $self, @args ) = @_;
1121
1122     $self->{__immutable}{original_class} = ref $self;
1123
1124     bless $self => $self->_immutable_metaclass(@args);
1125 }
1126
1127 sub _immutable_metaclass {
1128     my ( $self, %args ) = @_;
1129
1130     if ( my $class = $args{immutable_metaclass} ) {
1131         return $class;
1132     }
1133
1134     my $trait = $args{immutable_trait} = $self->immutable_trait
1135         || confess "no immutable trait specified for $self";
1136
1137     my $meta      = $self->meta;
1138     my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1139
1140     my $class_name;
1141
1142     if ( $meta_attr and $trait eq $meta_attr->default ) {
1143         # if the trait is the same as the default we try and pick a
1144         # predictable name for the immutable metaclass
1145         $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1146     }
1147     else {
1148         $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1149             $trait, 'ForMetaClass', ref($self);
1150     }
1151
1152     return $class_name
1153         if Class::MOP::is_class_loaded($class_name);
1154
1155     # If the metaclass is a subclass of CMOP::Class which has had
1156     # metaclass roles applied (via Moose), then we want to make sure
1157     # that we preserve that anonymous class (see Fey::ORM for an
1158     # example of where this matters).
1159     my $meta_name = $meta->_real_ref_name;
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