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