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