Add inline_rebless_instance to metaclass
[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 inline_create_instance {
617     my $self = shift;
618
619     return $self->get_meta_instance->inline_create_instance(@_);
620 }
621
622 sub inline_rebless_instance {
623     my $self = shift;
624
625     return $self->get_meta_instance->inline_rebless_instance_structure(@_);
626 }
627
628 sub clone_object {
629     my $class    = shift;
630     my $instance = shift;
631     (blessed($instance) && $instance->isa($class->name))
632         || confess "You must pass an instance of the metaclass (" . (ref $class ? $class->name : $class) . "), not ($instance)";
633
634     # NOTE:
635     # we need to protect the integrity of the
636     # Class::MOP::Class singletons here, they
637     # should not be cloned.
638     return $instance if $instance->isa('Class::MOP::Class');
639     $class->_clone_instance($instance, @_);
640 }
641
642 sub _clone_instance {
643     my ($class, $instance, %params) = @_;
644     (blessed($instance))
645         || confess "You can only clone instances, ($instance) is not a blessed instance";
646     my $meta_instance = $class->get_meta_instance();
647     my $clone = $meta_instance->clone_instance($instance);
648     foreach my $attr ($class->get_all_attributes()) {
649         if ( defined( my $init_arg = $attr->init_arg ) ) {
650             if (exists $params{$init_arg}) {
651                 $attr->set_value($clone, $params{$init_arg});
652             }
653         }
654     }
655     return $clone;
656 }
657
658 sub rebless_instance {
659     my ($self, $instance, %params) = @_;
660
661     my $old_metaclass = Class::MOP::class_of($instance);
662
663     my $old_class = $old_metaclass ? $old_metaclass->name : blessed($instance);
664     $self->name->isa($old_class)
665         || confess "You may rebless only into a subclass of ($old_class), of which (". $self->name .") isn't.";
666
667     $old_metaclass->rebless_instance_away($instance, $self, %params)
668         if $old_metaclass;
669
670     my $meta_instance = $self->get_meta_instance();
671
672     # rebless!
673     # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
674     $meta_instance->rebless_instance_structure($_[1], $self);
675
676     foreach my $attr ( $self->get_all_attributes ) {
677         if ( $attr->has_value($instance) ) {
678             if ( defined( my $init_arg = $attr->init_arg ) ) {
679                 $params{$init_arg} = $attr->get_value($instance)
680                     unless exists $params{$init_arg};
681             } 
682             else {
683                 $attr->set_value($instance, $attr->get_value($instance));
684             }
685         }
686     }
687
688     foreach my $attr ($self->get_all_attributes) {
689         $attr->initialize_instance_slot($meta_instance, $instance, \%params);
690     }
691     
692     $instance;
693 }
694
695 sub rebless_instance_back {
696     my ( $self, $instance ) = @_;
697
698     my $old_metaclass = Class::MOP::class_of($instance);
699
700     my $old_class
701         = $old_metaclass ? $old_metaclass->name : blessed($instance);
702     $old_class->isa( $self->name )
703         || confess
704         "You may rebless only into a superclass of ($old_class), of which ("
705         . $self->name
706         . ") isn't.";
707
708     $old_metaclass->rebless_instance_away( $instance, $self )
709         if $old_metaclass;
710
711     my $meta_instance = $self->get_meta_instance;
712
713     # we use $_[1] here because of t/306_rebless_overload.t regressions on 5.8.8
714     $meta_instance->rebless_instance_structure( $_[1], $self );
715
716     for my $attr ( $old_metaclass->get_all_attributes ) {
717         next if $self->has_attribute( $attr->name );
718         $meta_instance->deinitialize_slot( $instance, $_ ) for $attr->slots;
719     }
720
721     return $instance;
722 }
723
724 sub rebless_instance_away {
725     # this intentionally does nothing, it is just a hook
726 }
727
728 sub _attach_attribute {
729     my ($self, $attribute) = @_;
730     $attribute->attach_to_class($self);
731 }
732
733 sub _post_add_attribute {
734     my ( $self, $attribute ) = @_;
735
736     $self->invalidate_meta_instances;
737
738     # invalidate package flag here
739     try {
740         local $SIG{__DIE__};
741         $attribute->install_accessors;
742     }
743     catch {
744         $self->remove_attribute( $attribute->name );
745         die $_;
746     };
747 }
748
749 sub remove_attribute {
750     my $self = shift;
751
752     my $removed_attribute = $self->SUPER::remove_attribute(@_)
753         or return;
754
755     $self->invalidate_meta_instances;
756
757     $removed_attribute->remove_accessors;
758     $removed_attribute->detach_from_class;
759
760     return$removed_attribute;
761 }
762
763 sub find_attribute_by_name {
764     my ( $self, $attr_name ) = @_;
765
766     foreach my $class ( $self->linearized_isa ) {
767         # fetch the meta-class ...
768         my $meta = Class::MOP::Class->initialize($class);
769         return $meta->get_attribute($attr_name)
770             if $meta->has_attribute($attr_name);
771     }
772
773     return;
774 }
775
776 sub get_all_attributes {
777     my $self = shift;
778     my %attrs = map { %{ Class::MOP::Class->initialize($_)->_attribute_map } }
779         reverse $self->linearized_isa;
780     return values %attrs;
781 }
782
783 # Inheritance
784
785 sub superclasses {
786     my $self     = shift;
787
788     my $isa = $self->get_or_add_package_symbol(
789         { sigil => '@', type => 'ARRAY', name => 'ISA' } );
790
791     if (@_) {
792         my @supers = @_;
793         @{$isa} = @supers;
794
795         # NOTE:
796         # on 5.8 and below, we need to call
797         # a method to get Perl to detect
798         # a cycle in the class hierarchy
799         my $class = $self->name;
800         $class->isa($class);
801
802         # NOTE:
803         # we need to check the metaclass
804         # compatibility here so that we can
805         # be sure that the superclass is
806         # not potentially creating an issues
807         # we don't know about
808
809         $self->_check_metaclass_compatibility();
810         $self->_superclasses_updated();
811     }
812
813     return @{$isa};
814 }
815
816 sub _superclasses_updated {
817     my $self = shift;
818     $self->update_meta_instance_dependencies();
819 }
820
821 sub subclasses {
822     my $self = shift;
823     my $super_class = $self->name;
824
825     return @{ $super_class->mro::get_isarev() };
826 }
827
828 sub direct_subclasses {
829     my $self = shift;
830     my $super_class = $self->name;
831
832     return grep {
833         grep {
834             $_ eq $super_class
835         } Class::MOP::Class->initialize($_)->superclasses
836     } $self->subclasses;
837 }
838
839 sub linearized_isa {
840     return @{ mro::get_linear_isa( (shift)->name ) };
841 }
842
843 sub class_precedence_list {
844     my $self = shift;
845     my $name = $self->name;
846
847     unless (Class::MOP::IS_RUNNING_ON_5_10()) { 
848         # NOTE:
849         # We need to check for circular inheritance here
850         # if we are are not on 5.10, cause 5.8 detects it 
851         # late. This will do nothing if all is well, and 
852         # blow up otherwise. Yes, it's an ugly hack, better
853         # suggestions are welcome.        
854         # - SL
855         ($name || return)->isa('This is a test for circular inheritance') 
856     }
857
858     # if our mro is c3, we can 
859     # just grab the linear_isa
860     if (mro::get_mro($name) eq 'c3') {
861         return @{ mro::get_linear_isa($name) }
862     }
863     else {
864         # NOTE:
865         # we can't grab the linear_isa for dfs
866         # since it has all the duplicates 
867         # already removed.
868         return (
869             $name,
870             map {
871                 Class::MOP::Class->initialize($_)->class_precedence_list()
872             } $self->superclasses()
873         );
874     }
875 }
876
877 ## Methods
878
879 {
880     my $fetch_and_prepare_method = sub {
881         my ($self, $method_name) = @_;
882         my $wrapped_metaclass = $self->wrapped_method_metaclass;
883         # fetch it locally
884         my $method = $self->get_method($method_name);
885         # if we dont have local ...
886         unless ($method) {
887             # try to find the next method
888             $method = $self->find_next_method_by_name($method_name);
889             # die if it does not exist
890             (defined $method)
891                 || confess "The method '$method_name' was not found in the inheritance hierarchy for " . $self->name;
892             # and now make sure to wrap it
893             # even if it is already wrapped
894             # because we need a new sub ref
895             $method = $wrapped_metaclass->wrap($method,
896                 package_name => $self->name,
897                 name         => $method_name,
898             );
899         }
900         else {
901             # now make sure we wrap it properly
902             $method = $wrapped_metaclass->wrap($method,
903                 package_name => $self->name,
904                 name         => $method_name,
905             ) unless $method->isa($wrapped_metaclass);
906         }
907         $self->add_method($method_name => $method);
908         return $method;
909     };
910
911     sub add_before_method_modifier {
912         my ($self, $method_name, $method_modifier) = @_;
913         (defined $method_name && length $method_name)
914             || confess "You must pass in a method name";
915         my $method = $fetch_and_prepare_method->($self, $method_name);
916         $method->add_before_modifier(
917             subname(':before' => $method_modifier)
918         );
919     }
920
921     sub add_after_method_modifier {
922         my ($self, $method_name, $method_modifier) = @_;
923         (defined $method_name && length $method_name)
924             || confess "You must pass in a method name";
925         my $method = $fetch_and_prepare_method->($self, $method_name);
926         $method->add_after_modifier(
927             subname(':after' => $method_modifier)
928         );
929     }
930
931     sub add_around_method_modifier {
932         my ($self, $method_name, $method_modifier) = @_;
933         (defined $method_name && length $method_name)
934             || confess "You must pass in a method name";
935         my $method = $fetch_and_prepare_method->($self, $method_name);
936         $method->add_around_modifier(
937             subname(':around' => $method_modifier)
938         );
939     }
940
941     # NOTE:
942     # the methods above used to be named like this:
943     #    ${pkg}::${method}:(before|after|around)
944     # but this proved problematic when using one modifier
945     # to wrap multiple methods (something which is likely
946     # to happen pretty regularly IMO). So instead of naming
947     # it like this, I have chosen to just name them purely
948     # with their modifier names, like so:
949     #    :(before|after|around)
950     # The fact is that in a stack trace, it will be fairly
951     # evident from the context what method they are attached
952     # to, and so don't need the fully qualified name.
953 }
954
955 sub find_method_by_name {
956     my ($self, $method_name) = @_;
957     (defined $method_name && length $method_name)
958         || confess "You must define a method name to find";
959     foreach my $class ($self->linearized_isa) {
960         my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
961         return $method if defined $method;
962     }
963     return;
964 }
965
966 sub get_all_methods {
967     my $self = shift;
968
969     my %methods;
970     for my $class ( reverse $self->linearized_isa ) {
971         my $meta = Class::MOP::Class->initialize($class);
972
973         $methods{ $_->name } = $_ for $meta->_get_local_methods;
974     }
975
976     return values %methods;
977 }
978
979 sub get_all_method_names {
980     my $self = shift;
981     my %uniq;
982     return grep { !$uniq{$_}++ } map { Class::MOP::Class->initialize($_)->get_method_list } $self->linearized_isa;
983 }
984
985 sub find_all_methods_by_name {
986     my ($self, $method_name) = @_;
987     (defined $method_name && length $method_name)
988         || confess "You must define a method name to find";
989     my @methods;
990     foreach my $class ($self->linearized_isa) {
991         # fetch the meta-class ...
992         my $meta = Class::MOP::Class->initialize($class);
993         push @methods => {
994             name  => $method_name,
995             class => $class,
996             code  => $meta->get_method($method_name)
997         } if $meta->has_method($method_name);
998     }
999     return @methods;
1000 }
1001
1002 sub find_next_method_by_name {
1003     my ($self, $method_name) = @_;
1004     (defined $method_name && length $method_name)
1005         || confess "You must define a method name to find";
1006     my @cpl = $self->linearized_isa;
1007     shift @cpl; # discard ourselves
1008     foreach my $class (@cpl) {
1009         my $method = Class::MOP::Class->initialize($class)->get_method($method_name);
1010         return $method if defined $method;
1011     }
1012     return;
1013 }
1014
1015 sub update_meta_instance_dependencies {
1016     my $self = shift;
1017
1018     if ( $self->{meta_instance_dependencies} ) {
1019         return $self->add_meta_instance_dependencies;
1020     }
1021 }
1022
1023 sub add_meta_instance_dependencies {
1024     my $self = shift;
1025
1026     $self->remove_meta_instance_dependencies;
1027
1028     my @attrs = $self->get_all_attributes();
1029
1030     my %seen;
1031     my @classes = grep { not $seen{ $_->name }++ }
1032         map { $_->associated_class } @attrs;
1033
1034     foreach my $class (@classes) {
1035         $class->add_dependent_meta_instance($self);
1036     }
1037
1038     $self->{meta_instance_dependencies} = \@classes;
1039 }
1040
1041 sub remove_meta_instance_dependencies {
1042     my $self = shift;
1043
1044     if ( my $classes = delete $self->{meta_instance_dependencies} ) {
1045         foreach my $class (@$classes) {
1046             $class->remove_dependent_meta_instance($self);
1047         }
1048
1049         return $classes;
1050     }
1051
1052     return;
1053
1054 }
1055
1056 sub add_dependent_meta_instance {
1057     my ( $self, $metaclass ) = @_;
1058     push @{ $self->{dependent_meta_instances} }, $metaclass;
1059 }
1060
1061 sub remove_dependent_meta_instance {
1062     my ( $self, $metaclass ) = @_;
1063     my $name = $metaclass->name;
1064     @$_ = grep { $_->name ne $name } @$_
1065         for $self->{dependent_meta_instances};
1066 }
1067
1068 sub invalidate_meta_instances {
1069     my $self = shift;
1070     $_->invalidate_meta_instance()
1071         for $self, @{ $self->{dependent_meta_instances} };
1072 }
1073
1074 sub invalidate_meta_instance {
1075     my $self = shift;
1076     undef $self->{_meta_instance};
1077 }
1078
1079 # check if we can reinitialize
1080 sub is_pristine {
1081     my $self = shift;
1082
1083     # if any local attr is defined
1084     return if $self->get_attribute_list;
1085
1086     # or any non-declared methods
1087     for my $method ( map { $self->get_method($_) } $self->get_method_list ) {
1088         return if $method->isa("Class::MOP::Method::Generated");
1089         # FIXME do we need to enforce this too? return unless $method->isa( $self->method_metaclass );
1090     }
1091
1092     return 1;
1093 }
1094
1095 ## Class closing
1096
1097 sub is_mutable   { 1 }
1098 sub is_immutable { 0 }
1099
1100 sub immutable_options { %{ $_[0]{__immutable}{options} || {} } }
1101
1102 sub _immutable_options {
1103     my ( $self, @args ) = @_;
1104
1105     return (
1106         inline_accessors   => 1,
1107         inline_constructor => 1,
1108         inline_destructor  => 0,
1109         debug              => 0,
1110         immutable_trait    => $self->immutable_trait,
1111         constructor_name   => $self->constructor_name,
1112         constructor_class  => $self->constructor_class,
1113         destructor_class   => $self->destructor_class,
1114         @args,
1115     );
1116 }
1117
1118 sub make_immutable {
1119     my ( $self, @args ) = @_;
1120
1121     if ( $self->is_mutable ) {
1122         $self->_initialize_immutable( $self->_immutable_options(@args) );
1123         $self->_rebless_as_immutable(@args);
1124         return $self;
1125     }
1126     else {
1127         return;
1128     }
1129 }
1130
1131 sub make_mutable {
1132     my $self = shift;
1133
1134     if ( $self->is_immutable ) {
1135         my @args = $self->immutable_options;
1136         $self->_rebless_as_mutable();
1137         $self->_remove_inlined_code(@args);
1138         delete $self->{__immutable};
1139         return $self;
1140     }
1141     else {
1142         return;
1143     }
1144 }
1145
1146 sub _rebless_as_immutable {
1147     my ( $self, @args ) = @_;
1148
1149     $self->{__immutable}{original_class} = ref $self;
1150
1151     bless $self => $self->_immutable_metaclass(@args);
1152 }
1153
1154 sub _immutable_metaclass {
1155     my ( $self, %args ) = @_;
1156
1157     if ( my $class = $args{immutable_metaclass} ) {
1158         return $class;
1159     }
1160
1161     my $trait = $args{immutable_trait} = $self->immutable_trait
1162         || confess "no immutable trait specified for $self";
1163
1164     my $meta      = $self->meta;
1165     my $meta_attr = $meta->find_attribute_by_name("immutable_trait");
1166
1167     my $class_name;
1168
1169     if ( $meta_attr and $trait eq $meta_attr->default ) {
1170         # if the trait is the same as the default we try and pick a
1171         # predictable name for the immutable metaclass
1172         $class_name = 'Class::MOP::Class::Immutable::' . ref($self);
1173     }
1174     else {
1175         $class_name = join '::', 'Class::MOP::Class::Immutable::CustomTrait',
1176             $trait, 'ForMetaClass', ref($self);
1177     }
1178
1179     return $class_name
1180         if Class::MOP::is_class_loaded($class_name);
1181
1182     # If the metaclass is a subclass of CMOP::Class which has had
1183     # metaclass roles applied (via Moose), then we want to make sure
1184     # that we preserve that anonymous class (see Fey::ORM for an
1185     # example of where this matters).
1186     my $meta_name = $meta->_real_ref_name;
1187
1188     my $immutable_meta = $meta_name->create(
1189         $class_name,
1190         superclasses => [ ref $self ],
1191     );
1192
1193     Class::MOP::MiniTrait::apply( $immutable_meta, $trait );
1194
1195     $immutable_meta->make_immutable(
1196         inline_constructor => 0,
1197         inline_accessors   => 0,
1198     );
1199
1200     return $class_name;
1201 }
1202
1203 sub _remove_inlined_code {
1204     my $self = shift;
1205
1206     $self->remove_method( $_->name ) for $self->_inlined_methods;
1207
1208     delete $self->{__immutable}{inlined_methods};
1209 }
1210
1211 sub _inlined_methods { @{ $_[0]{__immutable}{inlined_methods} || [] } }
1212
1213 sub _add_inlined_method {
1214     my ( $self, $method ) = @_;
1215
1216     push @{ $self->{__immutable}{inlined_methods} ||= [] }, $method;
1217 }
1218
1219 sub _initialize_immutable {
1220     my ( $self, %args ) = @_;
1221
1222     $self->{__immutable}{options} = \%args;
1223     $self->_install_inlined_code(%args);
1224 }
1225
1226 sub _install_inlined_code {
1227     my ( $self, %args ) = @_;
1228
1229     # FIXME
1230     $self->_inline_accessors(%args)   if $args{inline_accessors};
1231     $self->_inline_constructor(%args) if $args{inline_constructor};
1232     $self->_inline_destructor(%args)  if $args{inline_destructor};
1233 }
1234
1235 sub _rebless_as_mutable {
1236     my $self = shift;
1237
1238     bless $self, $self->_get_mutable_metaclass_name;
1239
1240     return $self;
1241 }
1242
1243 sub _inline_accessors {
1244     my $self = shift;
1245
1246     foreach my $attr_name ( $self->get_attribute_list ) {
1247         $self->get_attribute($attr_name)->install_accessors(1);
1248     }
1249 }
1250
1251 sub _inline_constructor {
1252     my ( $self, %args ) = @_;
1253
1254     my $name = $args{constructor_name};
1255     # A class may not even have a constructor, and that's okay.
1256     return unless defined $name;
1257
1258     if ( $self->has_method($name) && !$args{replace_constructor} ) {
1259         my $class = $self->name;
1260         warn "Not inlining a constructor for $class since it defines"
1261             . " its own constructor.\n"
1262             . "If you are certain you don't need to inline your"
1263             . " constructor, specify inline_constructor => 0 in your"
1264             . " call to $class->meta->make_immutable\n";
1265         return;
1266     }
1267
1268     my $constructor_class = $args{constructor_class};
1269
1270     Class::MOP::load_class($constructor_class);
1271
1272     my $constructor = $constructor_class->new(
1273         options      => \%args,
1274         metaclass    => $self,
1275         is_inline    => 1,
1276         package_name => $self->name,
1277         name         => $name,
1278     );
1279
1280     if ( $args{replace_constructor} or $constructor->can_be_inlined ) {
1281         $self->add_method( $name => $constructor );
1282         $self->_add_inlined_method($constructor);
1283     }
1284 }
1285
1286 sub _inline_destructor {
1287     my ( $self, %args ) = @_;
1288
1289     ( exists $args{destructor_class} && defined $args{destructor_class} )
1290         || confess "The 'inline_destructor' option is present, but "
1291         . "no destructor class was specified";
1292
1293     if ( $self->has_method('DESTROY') && ! $args{replace_destructor} ) {
1294         my $class = $self->name;
1295         warn "Not inlining a destructor for $class since it defines"
1296             . " its own destructor.\n";
1297         return;
1298     }
1299
1300     my $destructor_class = $args{destructor_class};
1301
1302     Class::MOP::load_class($destructor_class);
1303
1304     return unless $destructor_class->is_needed($self);
1305
1306     my $destructor = $destructor_class->new(
1307         options      => \%args,
1308         metaclass    => $self,
1309         package_name => $self->name,
1310         name         => 'DESTROY'
1311     );
1312
1313     if ( $args{replace_destructor} or $destructor->can_be_inlined ) {
1314         $self->add_method( 'DESTROY' => $destructor );
1315         $self->_add_inlined_method($destructor);
1316     }
1317 }
1318
1319 1;
1320
1321 __END__
1322
1323 =pod
1324
1325 =head1 NAME
1326
1327 Class::MOP::Class - Class Meta Object
1328
1329 =head1 SYNOPSIS
1330
1331   # assuming that class Foo
1332   # has been defined, you can
1333
1334   # use this for introspection ...
1335
1336   # add a method to Foo ...
1337   Foo->meta->add_method( 'bar' => sub {...} )
1338
1339   # get a list of all the classes searched
1340   # the method dispatcher in the correct order
1341   Foo->meta->class_precedence_list()
1342
1343   # remove a method from Foo
1344   Foo->meta->remove_method('bar');
1345
1346   # or use this to actually create classes ...
1347
1348   Class::MOP::Class->create(
1349       'Bar' => (
1350           version      => '0.01',
1351           superclasses => ['Foo'],
1352           attributes   => [
1353               Class::MOP::Attribute->new('$bar'),
1354               Class::MOP::Attribute->new('$baz'),
1355           ],
1356           methods => {
1357               calculate_bar => sub {...},
1358               construct_baz => sub {...}
1359           }
1360       )
1361   );
1362
1363 =head1 DESCRIPTION
1364
1365 The Class Protocol is the largest and most complex part of the
1366 Class::MOP meta-object protocol. It controls the introspection and
1367 manipulation of Perl 5 classes, and it can create them as well. The
1368 best way to understand what this module can do is to read the
1369 documentation for each of its methods.
1370
1371 =head1 INHERITANCE
1372
1373 C<Class::MOP::Class> is a subclass of L<Class::MOP::Module>.
1374
1375 =head1 METHODS
1376
1377 =head2 Class construction
1378
1379 These methods all create new C<Class::MOP::Class> objects. These
1380 objects can represent existing classes or they can be used to create
1381 new classes from scratch.
1382
1383 The metaclass object for a given class is a singleton. If you attempt
1384 to create a metaclass for the same class twice, you will just get the
1385 existing object.
1386
1387 =over 4
1388
1389 =item B<< Class::MOP::Class->create($package_name, %options) >>
1390
1391 This method creates a new C<Class::MOP::Class> object with the given
1392 package name. It accepts a number of options:
1393
1394 =over 8
1395
1396 =item * version
1397
1398 An optional version number for the newly created package.
1399
1400 =item * authority
1401
1402 An optional authority for the newly created package.
1403
1404 =item * superclasses
1405
1406 An optional array reference of superclass names.
1407
1408 =item * methods
1409
1410 An optional hash reference of methods for the class. The keys of the
1411 hash reference are method names and values are subroutine references.
1412
1413 =item * attributes
1414
1415 An optional array reference of L<Class::MOP::Attribute> objects.
1416
1417 =item * no_meta
1418
1419 If true, a C<meta> method will not be installed into the class.
1420
1421 =back
1422
1423 =item B<< Class::MOP::Class->create_anon_class(%options) >>
1424
1425 This method works just like C<< Class::MOP::Class->create >> but it
1426 creates an "anonymous" class. In fact, the class does have a name, but
1427 that name is a unique name generated internally by this module.
1428
1429 It accepts the same C<superclasses>, C<methods>, and C<attributes>
1430 parameters that C<create> accepts.
1431
1432 Anonymous classes are destroyed once the metaclass they are attached
1433 to goes out of scope, and will be removed from Perl's internal symbol
1434 table.
1435
1436 All instances of an anonymous class keep a special reference to the
1437 metaclass object, which prevents the metaclass from going out of scope
1438 while any instances exist.
1439
1440 This only works if the instance is based on a hash reference, however.
1441
1442 =item B<< Class::MOP::Class->initialize($package_name, %options) >>
1443
1444 This method will initialize a C<Class::MOP::Class> object for the
1445 named package. Unlike C<create>, this method I<will not> create a new
1446 class.
1447
1448 The purpose of this method is to retrieve a C<Class::MOP::Class>
1449 object for introspecting an existing class.
1450
1451 If an existing C<Class::MOP::Class> object exists for the named
1452 package, it will be returned, and any options provided will be
1453 ignored!
1454
1455 If the object does not yet exist, it will be created.
1456
1457 The valid options that can be passed to this method are
1458 C<attribute_metaclass>, C<method_metaclass>,
1459 C<wrapped_method_metaclass>, and C<instance_metaclass>. These are all
1460 optional, and default to the appropriate class in the C<Class::MOP>
1461 distribution.
1462
1463 =back
1464
1465 =head2 Object instance construction and cloning
1466
1467 These methods are all related to creating and/or cloning object
1468 instances.
1469
1470 =over 4
1471
1472 =item B<< $metaclass->clone_object($instance, %params) >>
1473
1474 This method clones an existing object instance. Any parameters you
1475 provide are will override existing attribute values in the object.
1476
1477 This is a convenience method for cloning an object instance, then
1478 blessing it into the appropriate package.
1479
1480 You could implement a clone method in your class, using this method:
1481
1482   sub clone {
1483       my ($self, %params) = @_;
1484       $self->meta->clone_object($self, %params);
1485   }
1486
1487 =item B<< $metaclass->rebless_instance($instance, %params) >>
1488
1489 This method changes the class of C<$instance> to the metaclass's class.
1490
1491 You can only rebless an instance into a subclass of its current
1492 class. If you pass any additional parameters, these will be treated
1493 like constructor parameters and used to initialize the object's
1494 attributes. Any existing attributes that are already set will be
1495 overwritten.
1496
1497 Before reblessing the instance, this method will call
1498 C<rebless_instance_away> on the instance's current metaclass. This method
1499 will be passed the instance, the new metaclass, and any parameters
1500 specified to C<rebless_instance>. By default, C<rebless_instance_away>
1501 does nothing; it is merely a hook.
1502
1503 =item B<< $metaclass->rebless_instance_back($instance) >>
1504
1505 Does the same thing as C<rebless_instance>, except that you can only
1506 rebless an instance into one of its superclasses. Any attributes that
1507 do not exist in the superclass will be deinitialized.
1508
1509 This is a much more dangerous operation than C<rebless_instance>,
1510 especially when multiple inheritance is involved, so use this carefully!
1511
1512 =item B<< $metaclass->new_object(%params) >>
1513
1514 This method is used to create a new object of the metaclass's
1515 class. Any parameters you provide are used to initialize the
1516 instance's attributes. A special C<__INSTANCE__> key can be passed to
1517 provide an already generated instance, rather than having Class::MOP
1518 generate it for you. This is mostly useful for using Class::MOP with
1519 foreign classes which generate instances using their own constructors.
1520
1521 =item B<< $metaclass->instance_metaclass >>
1522
1523 Returns the class name of the instance metaclass. See
1524 L<Class::MOP::Instance> for more information on the instance
1525 metaclass.
1526
1527 =item B<< $metaclass->get_meta_instance >>
1528
1529 Returns an instance of the C<instance_metaclass> to be used in the
1530 construction of a new instance of the class.
1531
1532 =item B<< $metaclass->inline_create_instance($class_var) >>
1533
1534 =item B<< $metaclass->inline_rebless_instance($instance_var, $class_var) >>
1535
1536 These methods takes variable names, and use them to create an inline snippet
1537 of code that will create a new instance of the class.
1538
1539 =back
1540
1541 =head2 Informational predicates
1542
1543 These are a few predicate methods for asking information about the
1544 class itself.
1545
1546 =over 4
1547
1548 =item B<< $metaclass->is_anon_class >>
1549
1550 This returns true if the class was created by calling C<<
1551 Class::MOP::Class->create_anon_class >>.
1552
1553 =item B<< $metaclass->is_mutable >>
1554
1555 This returns true if the class is still mutable.
1556
1557 =item B<< $metaclass->is_immutable >>
1558
1559 This returns true if the class has been made immutable.
1560
1561 =item B<< $metaclass->is_pristine >>
1562
1563 A class is I<not> pristine if it has non-inherited attributes or if it
1564 has any generated methods.
1565
1566 =back
1567
1568 =head2 Inheritance Relationships
1569
1570 =over 4
1571
1572 =item B<< $metaclass->superclasses(@superclasses) >>
1573
1574 This is a read-write accessor which represents the superclass
1575 relationships of the metaclass's class.
1576
1577 This is basically sugar around getting and setting C<@ISA>.
1578
1579 =item B<< $metaclass->class_precedence_list >>
1580
1581 This returns a list of all of the class's ancestor classes. The
1582 classes are returned in method dispatch order.
1583
1584 =item B<< $metaclass->linearized_isa >>
1585
1586 This returns a list based on C<class_precedence_list> but with all
1587 duplicates removed.
1588
1589 =item B<< $metaclass->subclasses >>
1590
1591 This returns a list of all subclasses for this class, even indirect
1592 subclasses.
1593
1594 =item B<< $metaclass->direct_subclasses >>
1595
1596 This returns a list of immediate subclasses for this class, which does not
1597 include indirect subclasses.
1598
1599 =back
1600
1601 =head2 Method introspection and creation
1602
1603 These methods allow you to introspect a class's methods, as well as
1604 add, remove, or change methods.
1605
1606 Determining what is truly a method in a Perl 5 class requires some
1607 heuristics (aka guessing).
1608
1609 Methods defined outside the package with a fully qualified name (C<sub
1610 Package::name { ... }>) will be included. Similarly, methods named
1611 with a fully qualified name using L<Sub::Name> are also included.
1612
1613 However, we attempt to ignore imported functions.
1614
1615 Ultimately, we are using heuristics to determine what truly is a
1616 method in a class, and these heuristics may get the wrong answer in
1617 some edge cases. However, for most "normal" cases the heuristics work
1618 correctly.
1619
1620 =over 4
1621
1622 =item B<< $metaclass->get_method($method_name) >>
1623
1624 This will return a L<Class::MOP::Method> for the specified
1625 C<$method_name>. If the class does not have the specified method, it
1626 returns C<undef>
1627
1628 =item B<< $metaclass->has_method($method_name) >>
1629
1630 Returns a boolean indicating whether or not the class defines the
1631 named method. It does not include methods inherited from parent
1632 classes.
1633
1634 =item B<< $metaclass->get_method_list >>
1635
1636 This will return a list of method I<names> for all methods defined in
1637 this class.
1638
1639 =item B<< $metaclass->add_method($method_name, $method) >>
1640
1641 This method takes a method name and a subroutine reference, and adds
1642 the method to the class.
1643
1644 The subroutine reference can be a L<Class::MOP::Method>, and you are
1645 strongly encouraged to pass a meta method object instead of a code
1646 reference. If you do so, that object gets stored as part of the
1647 class's method map directly. If not, the meta information will have to
1648 be recreated later, and may be incorrect.
1649
1650 If you provide a method object, this method will clone that object if
1651 the object's package name does not match the class name. This lets us
1652 track the original source of any methods added from other classes
1653 (notably Moose roles).
1654
1655 =item B<< $metaclass->remove_method($method_name) >>
1656
1657 Remove the named method from the class. This method returns the
1658 L<Class::MOP::Method> object for the method.
1659
1660 =item B<< $metaclass->method_metaclass >>
1661
1662 Returns the class name of the method metaclass, see
1663 L<Class::MOP::Method> for more information on the method metaclass.
1664
1665 =item B<< $metaclass->wrapped_method_metaclass >>
1666
1667 Returns the class name of the wrapped method metaclass, see
1668 L<Class::MOP::Method::Wrapped> for more information on the wrapped
1669 method metaclass.
1670
1671 =item B<< $metaclass->get_all_methods >>
1672
1673 This will traverse the inheritance hierarchy and return a list of all
1674 the L<Class::MOP::Method> objects for this class and its parents.
1675
1676 =item B<< $metaclass->find_method_by_name($method_name) >>
1677
1678 This will return a L<Class::MOP::Method> for the specified
1679 C<$method_name>. If the class does not have the specified method, it
1680 returns C<undef>
1681
1682 Unlike C<get_method>, this method I<will> look for the named method in
1683 superclasses.
1684
1685 =item B<< $metaclass->get_all_method_names >>
1686
1687 This will return a list of method I<names> for all of this class's
1688 methods, including inherited methods.
1689
1690 =item B<< $metaclass->find_all_methods_by_name($method_name) >>
1691
1692 This method looks for the named method in the class and all of its
1693 parents. It returns every matching method it finds in the inheritance
1694 tree, so it returns a list of methods.
1695
1696 Each method is returned as a hash reference with three keys. The keys
1697 are C<name>, C<class>, and C<code>. The C<code> key has a
1698 L<Class::MOP::Method> object as its value.
1699
1700 The list of methods is distinct.
1701
1702 =item B<< $metaclass->find_next_method_by_name($method_name) >>
1703
1704 This method returns the first method in any superclass matching the
1705 given name. It is effectively the method that C<SUPER::$method_name>
1706 would dispatch to.
1707
1708 =back
1709
1710 =head2 Attribute introspection and creation
1711
1712 Because Perl 5 does not have a core concept of attributes in classes,
1713 we can only return information about attributes which have been added
1714 via this class's methods. We cannot discover information about
1715 attributes which are defined in terms of "regular" Perl 5 methods.
1716
1717 =over 4
1718
1719 =item B<< $metaclass->get_attribute($attribute_name) >>
1720
1721 This will return a L<Class::MOP::Attribute> for the specified
1722 C<$attribute_name>. If the class does not have the specified
1723 attribute, it returns C<undef>.
1724
1725 NOTE that get_attribute does not search superclasses, for that you
1726 need to use C<find_attribute_by_name>.
1727
1728 =item B<< $metaclass->has_attribute($attribute_name) >>
1729
1730 Returns a boolean indicating whether or not the class defines the
1731 named attribute. It does not include attributes inherited from parent
1732 classes.
1733
1734 =item B<< $metaclass->get_attribute_list >>
1735
1736 This will return a list of attributes I<names> for all attributes
1737 defined in this class.  Note that this operates on the current class
1738 only, it does not traverse the inheritance hierarchy.
1739
1740 =item B<< $metaclass->get_all_attributes >>
1741
1742 This will traverse the inheritance hierarchy and return a list of all
1743 the L<Class::MOP::Attribute> objects for this class and its parents.
1744
1745 =item B<< $metaclass->find_attribute_by_name($attribute_name) >>
1746
1747 This will return a L<Class::MOP::Attribute> for the specified
1748 C<$attribute_name>. If the class does not have the specified
1749 attribute, it returns C<undef>.
1750
1751 Unlike C<get_attribute>, this attribute I<will> look for the named
1752 attribute in superclasses.
1753
1754 =item B<< $metaclass->add_attribute(...) >>
1755
1756 This method accepts either an existing L<Class::MOP::Attribute>
1757 object or parameters suitable for passing to that class's C<new>
1758 method.
1759
1760 The attribute provided will be added to the class.
1761
1762 Any accessor methods defined by the attribute will be added to the
1763 class when the attribute is added.
1764
1765 If an attribute of the same name already exists, the old attribute
1766 will be removed first.
1767
1768 =item B<< $metaclass->remove_attribute($attribute_name) >>
1769
1770 This will remove the named attribute from the class, and
1771 L<Class::MOP::Attribute> object.
1772
1773 Removing an attribute also removes any accessor methods defined by the
1774 attribute.
1775
1776 However, note that removing an attribute will only affect I<future>
1777 object instances created for this class, not existing instances.
1778
1779 =item B<< $metaclass->attribute_metaclass >>
1780
1781 Returns the class name of the attribute metaclass for this class. By
1782 default, this is L<Class::MOP::Attribute>.
1783
1784 =back
1785
1786 =head2 Class Immutability
1787
1788 Making a class immutable "freezes" the class definition. You can no
1789 longer call methods which alter the class, such as adding or removing
1790 methods or attributes.
1791
1792 Making a class immutable lets us optimize the class by inlining some
1793 methods, and also allows us to optimize some methods on the metaclass
1794 object itself.
1795
1796 After immutabilization, the metaclass object will cache most informational
1797 methods that returns information about methods or attributes. Methods which
1798 would alter the class, such as C<add_attribute> and C<add_method>, will
1799 throw an error on an immutable metaclass object.
1800
1801 The immutabilization system in L<Moose> takes much greater advantage
1802 of the inlining features than Class::MOP itself does.
1803
1804 =over 4
1805
1806 =item B<< $metaclass->make_immutable(%options) >>
1807
1808 This method will create an immutable transformer and use it to make
1809 the class and its metaclass object immutable.
1810
1811 This method accepts the following options:
1812
1813 =over 8
1814
1815 =item * inline_accessors
1816
1817 =item * inline_constructor
1818
1819 =item * inline_destructor
1820
1821 These are all booleans indicating whether the specified method(s)
1822 should be inlined.
1823
1824 By default, accessors and the constructor are inlined, but not the
1825 destructor.
1826
1827 =item * immutable_trait
1828
1829 The name of a class which will be used as a parent class for the
1830 metaclass object being made immutable. This "trait" implements the
1831 post-immutability functionality of the metaclass (but not the
1832 transformation itself).
1833
1834 This defaults to L<Class::MOP::Class::Immutable::Trait>.
1835
1836 =item * constructor_name
1837
1838 This is the constructor method name. This defaults to "new".
1839
1840 =item * constructor_class
1841
1842 The name of the method metaclass for constructors. It will be used to
1843 generate the inlined constructor. This defaults to
1844 "Class::MOP::Method::Constructor".
1845
1846 =item * replace_constructor
1847
1848 This is a boolean indicating whether an existing constructor should be
1849 replaced when inlining a constructor. This defaults to false.
1850
1851 =item * destructor_class
1852
1853 The name of the method metaclass for destructors. It will be used to
1854 generate the inlined destructor. This defaults to
1855 "Class::MOP::Method::Denstructor".
1856
1857 =item * replace_destructor
1858
1859 This is a boolean indicating whether an existing destructor should be
1860 replaced when inlining a destructor. This defaults to false.
1861
1862 =back
1863
1864 =item B<< $metaclass->immutable_options >>
1865
1866 Returns a hash of the options used when making the class immutable, including
1867 both defaults and anything supplied by the user in the call to C<<
1868 $metaclass->make_immutable >>. This is useful if you need to temporarily make
1869 a class mutable and then restore immutability as it was before.
1870
1871 =item B<< $metaclass->make_mutable >>
1872
1873 Calling this method reverse the immutabilization transformation.
1874
1875 =back
1876
1877 =head2 Method Modifiers
1878
1879 Method modifiers are hooks which allow a method to be wrapped with
1880 I<before>, I<after> and I<around> method modifiers. Every time a
1881 method is called, its modifiers are also called.
1882
1883 A class can modify its own methods, as well as methods defined in
1884 parent classes.
1885
1886 =head3 How method modifiers work?
1887
1888 Method modifiers work by wrapping the original method and then
1889 replacing it in the class's symbol table. The wrappers will handle
1890 calling all the modifiers in the appropriate order and preserving the
1891 calling context for the original method.
1892
1893 The return values of C<before> and C<after> modifiers are
1894 ignored. This is because their purpose is B<not> to filter the input
1895 and output of the primary method (this is done with an I<around>
1896 modifier).
1897
1898 This may seem like an odd restriction to some, but doing this allows
1899 for simple code to be added at the beginning or end of a method call
1900 without altering the function of the wrapped method or placing any
1901 extra responsibility on the code of the modifier.
1902
1903 Of course if you have more complex needs, you can use the C<around>
1904 modifier which allows you to change both the parameters passed to the
1905 wrapped method, as well as its return value.
1906
1907 Before and around modifiers are called in last-defined-first-called
1908 order, while after modifiers are called in first-defined-first-called
1909 order. So the call tree might looks something like this:
1910
1911   before 2
1912    before 1
1913     around 2
1914      around 1
1915       primary
1916      around 1
1917     around 2
1918    after 1
1919   after 2
1920
1921 =head3 What is the performance impact?
1922
1923 Of course there is a performance cost associated with method
1924 modifiers, but we have made every effort to make that cost directly
1925 proportional to the number of modifier features you use.
1926
1927 The wrapping method does its best to B<only> do as much work as it
1928 absolutely needs to. In order to do this we have moved some of the
1929 performance costs to set-up time, where they are easier to amortize.
1930
1931 All this said, our benchmarks have indicated the following:
1932
1933   simple wrapper with no modifiers             100% slower
1934   simple wrapper with simple before modifier   400% slower
1935   simple wrapper with simple after modifier    450% slower
1936   simple wrapper with simple around modifier   500-550% slower
1937   simple wrapper with all 3 modifiers          1100% slower
1938
1939 These numbers may seem daunting, but you must remember, every feature
1940 comes with some cost. To put things in perspective, just doing a
1941 simple C<AUTOLOAD> which does nothing but extract the name of the
1942 method called and return it costs about 400% over a normal method
1943 call.
1944
1945 =over 4
1946
1947 =item B<< $metaclass->add_before_method_modifier($method_name, $code) >>
1948
1949 This wraps the specified method with the supplied subroutine
1950 reference. The modifier will be called as a method itself, and will
1951 receive the same arguments as are passed to the method.
1952
1953 When the modifier exits, the wrapped method will be called.
1954
1955 The return value of the modifier will be ignored.
1956
1957 =item B<< $metaclass->add_after_method_modifier($method_name, $code) >>
1958
1959 This wraps the specified method with the supplied subroutine
1960 reference. The modifier will be called as a method itself, and will
1961 receive the same arguments as are passed to the method.
1962
1963 When the wrapped methods exits, the modifier will be called.
1964
1965 The return value of the modifier will be ignored.
1966
1967 =item B<< $metaclass->add_around_method_modifier($method_name, $code) >>
1968
1969 This wraps the specified method with the supplied subroutine
1970 reference.
1971
1972 The first argument passed to the modifier will be a subroutine
1973 reference to the wrapped method. The second argument is the object,
1974 and after that come any arguments passed when the method is called.
1975
1976 The around modifier can choose to call the original method, as well as
1977 what arguments to pass if it does so.
1978
1979 The return value of the modifier is what will be seen by the caller.
1980
1981 =back
1982
1983 =head2 Introspection
1984
1985 =over 4
1986
1987 =item B<< Class::MOP::Class->meta >>
1988
1989 This will return a L<Class::MOP::Class> instance for this class.
1990
1991 It should also be noted that L<Class::MOP> will actually bootstrap
1992 this module by installing a number of attribute meta-objects into its
1993 metaclass.
1994
1995 =back
1996
1997 =head1 AUTHORS
1998
1999 Stevan Little E<lt>stevan@iinteractive.comE<gt>
2000
2001 =head1 COPYRIGHT AND LICENSE
2002
2003 Copyright 2006-2010 by Infinity Interactive, Inc.
2004
2005 L<http://www.iinteractive.com>
2006
2007 This library is free software; you can redistribute it and/or modify
2008 it under the same terms as Perl itself.
2009
2010 =cut