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