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