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