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