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