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