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