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