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