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