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