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