merging in the accessor 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
10 use Carp         'confess';
11 use Scalar::Util 'blessed', 'reftype', 'weaken';
12 use Sub::Name    'subname';
13 use B            'svref_2object';
14
15 our $VERSION   = '0.21';
16 our $AUTHORITY = 'cpan:STEVAN';
17
18 use base 'Class::MOP::Module';
19
20 # Self-introspection 
21
22 sub meta { Class::MOP::Class->initialize(blessed($_[0]) || $_[0]) }
23
24 # Creation
25     
26 sub initialize {
27     my $class        = shift;
28     my $package_name = shift;
29     (defined $package_name && $package_name && !blessed($package_name))
30         || confess "You must pass a package name and it cannot be blessed";    
31     $class->construct_class_instance(':package' => $package_name, @_);
32 }
33
34 sub reinitialize {
35     my $class        = shift;
36     my $package_name = shift;
37     (defined $package_name && $package_name && !blessed($package_name))
38         || confess "You must pass a package name and it cannot be blessed";    
39     Class::MOP::remove_metaclass_by_name($package_name);
40     $class->construct_class_instance(':package' => $package_name, @_);
41 }       
42     
43 # NOTE: (meta-circularity) 
44 # this is a special form of &construct_instance 
45 # (see below), which is used to construct class
46 # meta-object instances for any Class::MOP::* 
47 # class. All other classes will use the more 
48 # normal &construct_instance.
49 sub construct_class_instance {
50     my $class        = shift;
51     my %options      = @_;
52     my $package_name = $options{':package'};
53     (defined $package_name && $package_name)
54         || confess "You must pass a package name";  
55     # NOTE:
56     # return the metaclass if we have it cached, 
57     # and it is still defined (it has not been 
58     # reaped by DESTROY yet, which can happen 
59     # annoyingly enough during global destruction)
60     return Class::MOP::get_metaclass_by_name($package_name)
61         if Class::MOP::does_metaclass_exist($package_name);  
62
63     # NOTE:
64     # we need to deal with the possibility 
65     # of class immutability here, and then 
66     # get the name of the class appropriately
67     $class = (blessed($class)
68                     ? ($class->is_immutable
69                         ? $class->get_mutable_metaclass_name()
70                         : blessed($class))
71                     : $class);
72
73     # now create the metaclass
74     my $meta;
75     if ($class =~ /^Class::MOP::Class$/) {
76         no strict 'refs';                
77         $meta = bless { 
78             # inherited from Class::MOP::Package
79             '$:package'             => $package_name, 
80             
81             # NOTE:
82             # since the following attributes will 
83             # actually be loaded from the symbol 
84             # table, and actually bypass the instance
85             # entirely, we can just leave these things
86             # listed here for reference, because they
87             # should not actually have a value associated 
88             # with the slot.
89             '%:namespace'           => \undef,                
90             # inherited from Class::MOP::Module
91             '$:version'             => \undef,
92             '$:authority'           => \undef,
93             # defined in Class::MOP::Class
94             
95             '%:methods'             => {},
96             '%:attributes'          => {},            
97             '$:attribute_metaclass' => $options{':attribute_metaclass'} || 'Class::MOP::Attribute',
98             '$:method_metaclass'    => $options{':method_metaclass'}    || 'Class::MOP::Method',
99             '$:instance_metaclass'  => $options{':instance_metaclass'}  || 'Class::MOP::Instance',
100         } => $class;
101     }
102     else {
103         # NOTE:
104         # it is safe to use meta here because
105         # class will always be a subclass of 
106         # Class::MOP::Class, which defines meta
107         $meta = $class->meta->construct_instance(%options)
108     }
109     
110     # and check the metaclass compatibility
111     $meta->check_metaclass_compatability();
112     
113     Class::MOP::store_metaclass_by_name($package_name, $meta);
114     
115     # NOTE:
116     # we need to weaken any anon classes
117     # so that they can call DESTROY properly
118     Class::MOP::weaken_metaclass($package_name) if $meta->is_anon_class;
119     
120     $meta;        
121
122     
123 sub check_metaclass_compatability {
124     my $self = shift;
125
126     # this is always okay ...
127     return if blessed($self)            eq 'Class::MOP::Class'   && 
128               $self->instance_metaclass eq 'Class::MOP::Instance';
129
130     my @class_list = $self->class_precedence_list;
131     shift @class_list; # shift off $self->name
132
133     foreach my $class_name (@class_list) { 
134         my $meta = Class::MOP::get_metaclass_by_name($class_name) || next;
135         
136         # NOTE:
137         # we need to deal with the possibility 
138         # of class immutability here, and then 
139         # get the name of the class appropriately            
140         my $meta_type = ($meta->is_immutable
141                             ? $meta->get_mutable_metaclass_name()
142                             : blessed($meta));                
143                             
144         ($self->isa($meta_type))
145             || confess $self->name . "->meta => (" . (blessed($self)) . ")" . 
146                        " is not compatible with the " . 
147                        $class_name . "->meta => (" . ($meta_type)     . ")";
148         # NOTE:
149         # we also need to check that instance metaclasses
150         # are compatabile in the same the class.
151         ($self->instance_metaclass->isa($meta->instance_metaclass))
152             || confess $self->name . "->meta => (" . ($self->instance_metaclass) . ")" . 
153                        " is not compatible with the " . 
154                        $class_name . "->meta => (" . ($meta->instance_metaclass) . ")";                           
155     }        
156
157
158 ## ANON classes
159
160 {
161     # NOTE:
162     # this should be sufficient, if you have a 
163     # use case where it is not, write a test and 
164     # I will change it.
165     my $ANON_CLASS_SERIAL = 0;
166     
167     # NOTE:
168     # we need a sufficiently annoying prefix
169     # this should suffice for now, this is 
170     # used in a couple of places below, so 
171     # need to put it up here for now.
172     my $ANON_CLASS_PREFIX = 'Class::MOP::Class::__ANON__::SERIAL::';    
173
174     sub is_anon_class {
175         my $self = shift;
176         no warnings 'uninitialized';
177         $self->name =~ /^$ANON_CLASS_PREFIX/ ? 1 : 0;        
178     }
179
180     sub create_anon_class {
181         my ($class, %options) = @_;   
182         my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
183         return $class->create($package_name, %options);
184     } 
185
186     # NOTE:
187     # this will only get called for 
188     # anon-classes, all other calls 
189     # are assumed to occur during 
190     # global destruction and so don't
191     # really need to be handled explicitly
192     sub DESTROY {
193         my $self = shift;
194         no warnings 'uninitialized';        
195         return unless $self->name =~ /^$ANON_CLASS_PREFIX/;
196         my ($serial_id) = ($self->name =~ /^$ANON_CLASS_PREFIX(\d+)/);
197         no strict 'refs';     
198         foreach my $key (keys %{$ANON_CLASS_PREFIX . $serial_id}) {
199             delete ${$ANON_CLASS_PREFIX . $serial_id}{$key};
200         }
201         delete ${'main::' . $ANON_CLASS_PREFIX}{$serial_id . '::'};        
202     }
203
204 }
205
206 # creating classes with MOP ...
207
208 sub create {
209     my $class        = shift;
210     my $package_name = shift;
211     
212     (defined $package_name && $package_name)
213         || confess "You must pass a package name";
214
215     (scalar @_ % 2 == 0)
216         || confess "You much pass all parameters as name => value pairs " . 
217                    "(I found an uneven number of params in \@_)";
218
219     my (%options) = @_;
220     
221     my $code = "package $package_name;";
222     $code .= "\$$package_name\:\:VERSION = '" . $options{version} . "';" 
223         if exists $options{version};
224     $code .= "\$$package_name\:\:AUTHORITY = '" . $options{authority} . "';" 
225         if exists $options{authority};  
226               
227     eval $code;
228     confess "creation of $package_name failed : $@" if $@;    
229     
230     my $meta = $class->initialize($package_name);
231     
232     $meta->add_method('meta' => sub { 
233         $class->initialize(blessed($_[0]) || $_[0]);
234     });
235     
236     $meta->superclasses(@{$options{superclasses}})
237         if exists $options{superclasses};
238     # NOTE:
239     # process attributes first, so that they can 
240     # install accessors, but locally defined methods
241     # can then overwrite them. It is maybe a little odd, but
242     # I think this should be the order of things.
243     if (exists $options{attributes}) {
244         foreach my $attr (@{$options{attributes}}) {
245             $meta->add_attribute($attr);
246         }
247     }        
248     if (exists $options{methods}) {
249         foreach my $method_name (keys %{$options{methods}}) {
250             $meta->add_method($method_name, $options{methods}->{$method_name});
251         }
252     }  
253     return $meta;
254 }
255
256 ## Attribute readers
257
258 # NOTE:
259 # all these attribute readers will be bootstrapped 
260 # away in the Class::MOP bootstrap section
261
262 sub get_attribute_map   { $_[0]->{'%:attributes'}          }
263 sub attribute_metaclass { $_[0]->{'$:attribute_metaclass'} }
264 sub method_metaclass    { $_[0]->{'$:method_metaclass'}    }
265 sub instance_metaclass  { $_[0]->{'$:instance_metaclass'}  }
266
267 # FIXME:
268 # this is a prime canidate for conversion to XS
269 sub get_method_map {    
270     my $self = shift;
271     my $map  = $self->{'%:methods'}; 
272     
273     my $class_name       = $self->name;
274     my $method_metaclass = $self->method_metaclass;
275     
276     foreach my $symbol ($self->list_all_package_symbols('CODE')) {
277         my $code = $self->get_package_symbol('&' . $symbol);
278         
279         next if exists  $map->{$symbol} && 
280                 defined $map->{$symbol} && 
281                         $map->{$symbol}->body == $code;        
282         
283         my $gv = svref_2object($code)->GV;
284         next if ($gv->STASH->NAME || '') ne $class_name &&
285                 ($gv->NAME        || '') ne '__ANON__';        
286         
287         $map->{$symbol} = $method_metaclass->wrap($code);
288     }
289     
290     return $map;
291 }
292
293 # Instance Construction & Cloning
294
295 sub new_object {
296     my $class = shift;
297     # NOTE:
298     # we need to protect the integrity of the 
299     # Class::MOP::Class singletons here, so we
300     # delegate this to &construct_class_instance
301     # which will deal with the singletons
302     return $class->construct_class_instance(@_)
303         if $class->name->isa('Class::MOP::Class');
304     return $class->construct_instance(@_);
305 }
306
307 sub construct_instance {
308     my ($class, %params) = @_;
309     my $meta_instance = $class->get_meta_instance();
310     my $instance = $meta_instance->create_instance();
311     foreach my $attr ($class->compute_all_applicable_attributes()) {
312         $attr->initialize_instance_slot($meta_instance, $instance, \%params);
313     }
314     return $instance;
315 }
316
317 sub get_meta_instance {
318     my $class = shift;
319     return $class->instance_metaclass->new(
320         $class, 
321         $class->compute_all_applicable_attributes()
322     );
323 }
324
325 sub clone_object {
326     my $class    = shift;
327     my $instance = shift; 
328     (blessed($instance) && $instance->isa($class->name))
329         || confess "You must pass an instance ($instance) of the metaclass (" . $class->name . ")";
330     # NOTE:
331     # we need to protect the integrity of the 
332     # Class::MOP::Class singletons here, they 
333     # should not be cloned.
334     return $instance if $instance->isa('Class::MOP::Class');   
335     $class->clone_instance($instance, @_);
336 }
337
338 sub clone_instance {
339     my ($class, $instance, %params) = @_;
340     (blessed($instance))
341         || confess "You can only clone instances, \$self is not a blessed instance";
342     my $meta_instance = $class->get_meta_instance();
343     my $clone = $meta_instance->clone_instance($instance);        
344     foreach my $key (keys %params) {
345         next unless $meta_instance->is_valid_slot($key);
346         $meta_instance->set_slot_value($clone, $key, $params{$key});
347     }
348     return $clone;    
349 }
350
351 # Inheritance
352
353 sub superclasses {
354     my $self = shift;
355     if (@_) {
356         my @supers = @_;
357         @{$self->get_package_symbol('@ISA')} = @supers;
358         # NOTE:
359         # we need to check the metaclass 
360         # compatability here so that we can 
361         # be sure that the superclass is 
362         # not potentially creating an issues 
363         # we don't know about
364         $self->check_metaclass_compatability();
365     }
366     @{$self->get_package_symbol('@ISA')};
367 }
368
369 sub class_precedence_list {
370     my $self = shift;
371     # NOTE:
372     # We need to check for ciruclar inheirtance here.
373     # This will do nothing if all is well, and blow
374     # up otherwise. Yes, it's an ugly hack, better 
375     # suggestions are welcome.
376     { ($self->name || return)->isa('This is a test for circular inheritance') }
377     # ... and now back to our regularly scheduled program
378     (
379         $self->name, 
380         map { 
381             $self->initialize($_)->class_precedence_list()
382         } $self->superclasses()
383     );   
384 }
385
386 ## Methods
387
388 sub add_method {
389     my ($self, $method_name, $method) = @_;
390     (defined $method_name && $method_name)
391         || confess "You must define a method name";
392     
393     my $body;
394     if (blessed($method)) {
395         $body = $method->body;           
396     }
397     else {        
398         $body = $method;
399         ('CODE' eq (reftype($body) || ''))
400             || confess "Your code block must be a CODE reference";        
401         $method = $self->method_metaclass->wrap($body);        
402     }
403     $self->get_method_map->{$method_name} = $method;
404     
405     my $full_method_name = ($self->name . '::' . $method_name);        
406     $self->add_package_symbol("&${method_name}" => subname $full_method_name => $body);
407 }
408
409 {
410     my $fetch_and_prepare_method = sub {
411         my ($self, $method_name) = @_;
412         # fetch it locally
413         my $method = $self->get_method($method_name);
414         # if we dont have local ...
415         unless ($method) {
416             # try to find the next method
417             $method = $self->find_next_method_by_name($method_name);
418             # die if it does not exist
419             (defined $method)
420                 || confess "The method '$method_name' is not found in the inherience hierarchy for class " . $self->name;
421             # and now make sure to wrap it 
422             # even if it is already wrapped
423             # because we need a new sub ref
424             $method = Class::MOP::Method::Wrapped->wrap($method);
425         }
426         else {
427             # now make sure we wrap it properly 
428             $method = Class::MOP::Method::Wrapped->wrap($method)
429                 unless $method->isa('Class::MOP::Method::Wrapped');  
430         }    
431         $self->add_method($method_name => $method);        
432         return $method;
433     };
434
435     sub add_before_method_modifier {
436         my ($self, $method_name, $method_modifier) = @_;
437         (defined $method_name && $method_name)
438             || confess "You must pass in a method name";    
439         my $method = $fetch_and_prepare_method->($self, $method_name);
440         $method->add_before_modifier(subname ':before' => $method_modifier);
441     }
442
443     sub add_after_method_modifier {
444         my ($self, $method_name, $method_modifier) = @_;
445         (defined $method_name && $method_name)
446             || confess "You must pass in a method name";    
447         my $method = $fetch_and_prepare_method->($self, $method_name);
448         $method->add_after_modifier(subname ':after' => $method_modifier);
449     }
450     
451     sub add_around_method_modifier {
452         my ($self, $method_name, $method_modifier) = @_;
453         (defined $method_name && $method_name)
454             || confess "You must pass in a method name";
455         my $method = $fetch_and_prepare_method->($self, $method_name);
456         $method->add_around_modifier(subname ':around' => $method_modifier);
457     }   
458
459     # NOTE: 
460     # the methods above used to be named like this:
461     #    ${pkg}::${method}:(before|after|around)
462     # but this proved problematic when using one modifier
463     # to wrap multiple methods (something which is likely
464     # to happen pretty regularly IMO). So instead of naming
465     # it like this, I have chosen to just name them purely 
466     # with their modifier names, like so:
467     #    :(before|after|around)
468     # The fact is that in a stack trace, it will be fairly 
469     # evident from the context what method they are attached
470     # to, and so don't need the fully qualified name.
471 }
472
473 sub alias_method {
474     my ($self, $method_name, $method) = @_;
475     (defined $method_name && $method_name)
476         || confess "You must define a method name";
477
478     my $body = (blessed($method) ? $method->body : $method);
479     ('CODE' eq (reftype($body) || ''))
480         || confess "Your code block must be a CODE reference";        
481         
482     $self->add_package_symbol("&${method_name}" => $body);
483 }
484
485 sub has_method {
486     my ($self, $method_name) = @_;
487     (defined $method_name && $method_name)
488         || confess "You must define a method name";    
489     
490     return 0 unless exists $self->get_method_map->{$method_name};    
491     return 1;
492 }
493
494 sub get_method {
495     my ($self, $method_name) = @_;
496     (defined $method_name && $method_name)
497         || confess "You must define a method name";
498      
499     # NOTE:
500     # I don't really need this here, because
501     # if the method_map is missing a key it 
502     # will just return undef for me now
503     # return unless $self->has_method($method_name);
504  
505     return $self->get_method_map->{$method_name};
506 }
507
508 sub remove_method {
509     my ($self, $method_name) = @_;
510     (defined $method_name && $method_name)
511         || confess "You must define a method name";
512     
513     my $removed_method = $self->get_method($method_name);    
514     
515     do { 
516         $self->remove_package_symbol("&${method_name}");
517         delete $self->get_method_map->{$method_name};
518     } if defined $removed_method;
519         
520     return $removed_method;
521 }
522
523 sub get_method_list {
524     my $self = shift;
525     keys %{$self->get_method_map};
526 }
527
528 sub find_method_by_name {
529     my ($self, $method_name) = @_;
530     (defined $method_name && $method_name)
531         || confess "You must define a method name to find"; 
532     # keep a record of what we have seen
533     # here, this will handle all the 
534     # inheritence issues because we are 
535     # using the &class_precedence_list
536     my %seen_class;
537     my @cpl = $self->class_precedence_list();
538     foreach my $class (@cpl) {
539         next if $seen_class{$class};
540         $seen_class{$class}++;
541         # fetch the meta-class ...
542         my $meta = $self->initialize($class);
543         return $meta->get_method($method_name) 
544             if $meta->has_method($method_name);
545     }
546     return;
547 }
548
549 sub compute_all_applicable_methods {
550     my $self = shift;
551     my @methods;
552     # keep a record of what we have seen
553     # here, this will handle all the 
554     # inheritence issues because we are 
555     # using the &class_precedence_list
556     my (%seen_class, %seen_method);
557     foreach my $class ($self->class_precedence_list()) {
558         next if $seen_class{$class};
559         $seen_class{$class}++;
560         # fetch the meta-class ...
561         my $meta = $self->initialize($class);
562         foreach my $method_name ($meta->get_method_list()) { 
563             next if exists $seen_method{$method_name};
564             $seen_method{$method_name}++;
565             push @methods => {
566                 name  => $method_name, 
567                 class => $class,
568                 code  => $meta->get_method($method_name)
569             };
570         }
571     }
572     return @methods;
573 }
574
575 sub find_all_methods_by_name {
576     my ($self, $method_name) = @_;
577     (defined $method_name && $method_name)
578         || confess "You must define a method name to find";    
579     my @methods;
580     # keep a record of what we have seen
581     # here, this will handle all the 
582     # inheritence issues because we are 
583     # using the &class_precedence_list
584     my %seen_class;
585     foreach my $class ($self->class_precedence_list()) {
586         next if $seen_class{$class};
587         $seen_class{$class}++;
588         # fetch the meta-class ...
589         my $meta = $self->initialize($class);
590         push @methods => {
591             name  => $method_name, 
592             class => $class,
593             code  => $meta->get_method($method_name)
594         } if $meta->has_method($method_name);
595     }
596     return @methods;
597 }
598
599 sub find_next_method_by_name {
600     my ($self, $method_name) = @_;
601     (defined $method_name && $method_name)
602         || confess "You must define a method name to find"; 
603     # keep a record of what we have seen
604     # here, this will handle all the 
605     # inheritence issues because we are 
606     # using the &class_precedence_list
607     my %seen_class;
608     my @cpl = $self->class_precedence_list();
609     shift @cpl; # discard ourselves
610     foreach my $class (@cpl) {
611         next if $seen_class{$class};
612         $seen_class{$class}++;
613         # fetch the meta-class ...
614         my $meta = $self->initialize($class);
615         return $meta->get_method($method_name) 
616             if $meta->has_method($method_name);
617     }
618     return;
619 }
620
621 ## Attributes
622
623 sub add_attribute {
624     my $self      = shift;
625     # either we have an attribute object already
626     # or we need to create one from the args provided
627     my $attribute = blessed($_[0]) ? $_[0] : $self->attribute_metaclass->new(@_);
628     # make sure it is derived from the correct type though
629     ($attribute->isa('Class::MOP::Attribute'))
630         || confess "Your attribute must be an instance of Class::MOP::Attribute (or a subclass)";    
631
632     # first we attach our new attribute
633     # because it might need certain information 
634     # about the class which it is attached to
635     $attribute->attach_to_class($self);
636     
637     # then we remove attributes of a conflicting 
638     # name here so that we can properly detach 
639     # the old attr object, and remove any 
640     # accessors it would have generated
641     $self->remove_attribute($attribute->name)
642         if $self->has_attribute($attribute->name);
643         
644     # then onto installing the new accessors
645     $attribute->install_accessors();
646     $self->get_attribute_map->{$attribute->name} = $attribute;
647 }
648
649 sub has_attribute {
650     my ($self, $attribute_name) = @_;
651     (defined $attribute_name && $attribute_name)
652         || confess "You must define an attribute name";
653     exists $self->get_attribute_map->{$attribute_name} ? 1 : 0;    
654
655
656 sub get_attribute {
657     my ($self, $attribute_name) = @_;
658     (defined $attribute_name && $attribute_name)
659         || confess "You must define an attribute name";
660     return $self->get_attribute_map->{$attribute_name} 
661     # NOTE:
662     # this will return undef anyway, so no need ...
663     #    if $self->has_attribute($attribute_name);   
664     #return; 
665
666
667 sub remove_attribute {
668     my ($self, $attribute_name) = @_;
669     (defined $attribute_name && $attribute_name)
670         || confess "You must define an attribute name";
671     my $removed_attribute = $self->get_attribute_map->{$attribute_name};    
672     return unless defined $removed_attribute;
673     delete $self->get_attribute_map->{$attribute_name};        
674     $removed_attribute->remove_accessors(); 
675     $removed_attribute->detach_from_class();
676     return $removed_attribute;
677
678
679 sub get_attribute_list {
680     my $self = shift;
681     keys %{$self->get_attribute_map};
682
683
684 sub compute_all_applicable_attributes {
685     my $self = shift;
686     my @attrs;
687     # keep a record of what we have seen
688     # here, this will handle all the 
689     # inheritence issues because we are 
690     # using the &class_precedence_list
691     my (%seen_class, %seen_attr);
692     foreach my $class ($self->class_precedence_list()) {
693         next if $seen_class{$class};
694         $seen_class{$class}++;
695         # fetch the meta-class ...
696         my $meta = $self->initialize($class);
697         foreach my $attr_name ($meta->get_attribute_list()) { 
698             next if exists $seen_attr{$attr_name};
699             $seen_attr{$attr_name}++;
700             push @attrs => $meta->get_attribute($attr_name);
701         }
702     }
703     return @attrs;    
704 }
705
706 sub find_attribute_by_name {
707     my ($self, $attr_name) = @_;
708     # keep a record of what we have seen
709     # here, this will handle all the 
710     # inheritence issues because we are 
711     # using the &class_precedence_list
712     my %seen_class;
713     foreach my $class ($self->class_precedence_list()) {
714         next if $seen_class{$class};
715         $seen_class{$class}++;
716         # fetch the meta-class ...
717         my $meta = $self->initialize($class);
718         return $meta->get_attribute($attr_name)
719             if $meta->has_attribute($attr_name);
720     }
721     return;
722 }
723
724 ## Class closing
725
726 sub is_mutable   { 1 }
727 sub is_immutable { 0 }
728
729 sub make_immutable {
730     return Class::MOP::Class::Immutable->make_metaclass_immutable(@_);
731 }
732
733 1;
734
735 __END__
736
737 =pod
738
739 =head1 NAME 
740
741 Class::MOP::Class - Class Meta Object
742
743 =head1 SYNOPSIS
744
745   # assuming that class Foo 
746   # has been defined, you can
747   
748   # use this for introspection ...
749   
750   # add a method to Foo ...
751   Foo->meta->add_method('bar' => sub { ... })
752   
753   # get a list of all the classes searched 
754   # the method dispatcher in the correct order 
755   Foo->meta->class_precedence_list()
756   
757   # remove a method from Foo
758   Foo->meta->remove_method('bar');
759   
760   # or use this to actually create classes ...
761   
762   Class::MOP::Class->create('Bar' => (
763       version      => '0.01',
764       superclasses => [ 'Foo' ],
765       attributes => [
766           Class::MOP:::Attribute->new('$bar'),
767           Class::MOP:::Attribute->new('$baz'),          
768       ],
769       methods => {
770           calculate_bar => sub { ... },
771           construct_baz => sub { ... }          
772       }
773   ));
774
775 =head1 DESCRIPTION
776
777 This is the largest and currently most complex part of the Perl 5 
778 meta-object protocol. It controls the introspection and 
779 manipulation of Perl 5 classes (and it can create them too). The 
780 best way to understand what this module can do, is to read the 
781 documentation for each of it's methods.
782
783 =head1 METHODS
784
785 =head2 Self Introspection
786
787 =over 4
788
789 =item B<meta>
790
791 This will return a B<Class::MOP::Class> instance which is related 
792 to this class. Thereby allowing B<Class::MOP::Class> to actually 
793 introspect itself.
794
795 As with B<Class::MOP::Attribute>, B<Class::MOP> will actually 
796 bootstrap this module by installing a number of attribute meta-objects 
797 into it's metaclass. This will allow this class to reap all the benifits 
798 of the MOP when subclassing it. 
799
800 =back
801
802 =head2 Class construction
803
804 These methods will handle creating B<Class::MOP::Class> objects, 
805 which can be used to both create new classes, and analyze 
806 pre-existing classes. 
807
808 This module will internally store references to all the instances 
809 you create with these methods, so that they do not need to be 
810 created any more than nessecary. Basically, they are singletons.
811
812 =over 4
813
814 =item B<create ($package_name, 
815                 version      =E<gt> ?$version,                 
816                 authority    =E<gt> ?$authority,                                 
817                 superclasses =E<gt> ?@superclasses, 
818                 methods      =E<gt> ?%methods, 
819                 attributes   =E<gt> ?%attributes)>
820
821 This returns a B<Class::MOP::Class> object, bringing the specified 
822 C<$package_name> into existence and adding any of the C<$version>, 
823 C<$authority>, C<@superclasses>, C<%methods> and C<%attributes> to 
824 it.
825
826 =item B<create_anon_class (superclasses =E<gt> ?@superclasses, 
827                            methods      =E<gt> ?%methods, 
828                            attributes   =E<gt> ?%attributes)>
829
830 This will create an anonymous class, it works much like C<create> but 
831 it does not need a C<$package_name>. Instead it will create a suitably 
832 unique package name for you to stash things into.
833
834 =item B<initialize ($package_name, %options)>
835
836 This initializes and returns returns a B<Class::MOP::Class> object 
837 for a given a C<$package_name>.
838
839 =item B<reinitialize ($package_name, %options)>
840
841 This removes the old metaclass, and creates a new one in it's place.
842 Do B<not> use this unless you really know what you are doing, it could 
843 very easily make a very large mess of your program. 
844
845 =item B<construct_class_instance (%options)>
846
847 This will construct an instance of B<Class::MOP::Class>, it is 
848 here so that we can actually "tie the knot" for B<Class::MOP::Class> 
849 to use C<construct_instance> once all the bootstrapping is done. This 
850 method is used internally by C<initialize> and should never be called
851 from outside of that method really.
852
853 =item B<check_metaclass_compatability>
854
855 This method is called as the very last thing in the 
856 C<construct_class_instance> method. This will check that the 
857 metaclass you are creating is compatible with the metaclasses of all 
858 your ancestors. For more inforamtion about metaclass compatibility 
859 see the C<About Metaclass compatibility> section in L<Class::MOP>.
860
861 =back
862
863 =head2 Object instance construction and cloning
864
865 These methods are B<entirely optional>, it is up to you whether you want 
866 to use them or not.
867
868 =over 4
869
870 =item B<instance_metaclass>
871
872 =item B<get_meta_instance>
873
874 =item B<new_object (%params)>
875
876 This is a convience method for creating a new object of the class, and 
877 blessing it into the appropriate package as well. Ideally your class 
878 would call a C<new> this method like so:
879
880   sub MyClass::new { 
881       my ($class, %param) = @_;
882       $class->meta->new_object(%params);
883   }
884
885 Of course the ideal place for this would actually be in C<UNIVERSAL::> 
886 but that is considered bad style, so we do not do that.
887
888 =item B<construct_instance (%params)>
889
890 This method is used to construct an instace structure suitable for 
891 C<bless>-ing into your package of choice. It works in conjunction 
892 with the Attribute protocol to collect all applicable attributes.
893
894 This will construct and instance using a HASH ref as storage 
895 (currently only HASH references are supported). This will collect all 
896 the applicable attributes and layout out the fields in the HASH ref, 
897 it will then initialize them using either use the corresponding key 
898 in C<%params> or any default value or initializer found in the 
899 attribute meta-object.
900
901 =item B<clone_object ($instance, %params)>
902
903 This is a convience method for cloning an object instance, then  
904 blessing it into the appropriate package. This method will call 
905 C<clone_instance>, which performs a shallow copy of the object, 
906 see that methods documentation for more details. Ideally your 
907 class would call a C<clone> this method like so:
908
909   sub MyClass::clone {
910       my ($self, %param) = @_;
911       $self->meta->clone_object($self, %params);
912   }
913
914 Of course the ideal place for this would actually be in C<UNIVERSAL::> 
915 but that is considered bad style, so we do not do that.
916
917 =item B<clone_instance($instance, %params)>
918
919 This method is a compliment of C<construct_instance> (which means if 
920 you override C<construct_instance>, you need to override this one too), 
921 and clones the instance shallowly.
922
923 The cloned structure returned is (like with C<construct_instance>) an 
924 unC<bless>ed HASH reference, it is your responsibility to then bless 
925 this cloned structure into the right class (which C<clone_object> will
926 do for you).
927
928 As of 0.11, this method will clone the C<$instance> structure shallowly, 
929 as opposed to the deep cloning implemented in prior versions. After much 
930 thought, research and discussion, I have decided that anything but basic 
931 shallow cloning is outside the scope of the meta-object protocol. I 
932 think Yuval "nothingmuch" Kogman put it best when he said that cloning 
933 is too I<context-specific> to be part of the MOP.
934
935 =back
936
937 =head2 Informational 
938
939 These are a few predicate methods for asking information about the class.
940
941 =over 4
942
943 =item B<is_anon_class>
944
945 =item B<is_mutable>
946
947 =item B<is_immutable>
948
949 =back
950
951 =head2 Inheritance Relationships
952
953 =over 4
954
955 =item B<superclasses (?@superclasses)>
956
957 This is a read-write attribute which represents the superclass 
958 relationships of the class the B<Class::MOP::Class> instance is
959 associated with. Basically, it can get and set the C<@ISA> for you.
960
961 B<NOTE:>
962 Perl will occasionally perform some C<@ISA> and method caching, if 
963 you decide to change your superclass relationship at runtime (which 
964 is quite insane and very much not recommened), then you should be 
965 aware of this and the fact that this module does not make any 
966 attempt to address this issue.
967
968 =item B<class_precedence_list>
969
970 This computes the a list of all the class's ancestors in the same order 
971 in which method dispatch will be done. This is similair to 
972 what B<Class::ISA::super_path> does, but we don't remove duplicate names.
973
974 =back
975
976 =head2 Methods
977
978 =over 4
979
980 =item B<get_method_map>
981
982 =item B<method_metaclass>
983
984 =item B<add_method ($method_name, $method)>
985
986 This will take a C<$method_name> and CODE reference to that 
987 C<$method> and install it into the class's package. 
988
989 B<NOTE>: 
990 This does absolutely nothing special to C<$method> 
991 other than use B<Sub::Name> to make sure it is tagged with the 
992 correct name, and therefore show up correctly in stack traces and 
993 such.
994
995 =item B<alias_method ($method_name, $method)>
996
997 This will take a C<$method_name> and CODE reference to that 
998 C<$method> and alias the method into the class's package. 
999
1000 B<NOTE>: 
1001 Unlike C<add_method>, this will B<not> try to name the 
1002 C<$method> using B<Sub::Name>, it only aliases the method in 
1003 the class's package. 
1004
1005 =item B<has_method ($method_name)>
1006
1007 This just provides a simple way to check if the class implements 
1008 a specific C<$method_name>. It will I<not> however, attempt to check 
1009 if the class inherits the method (use C<UNIVERSAL::can> for that).
1010
1011 This will correctly handle functions defined outside of the package 
1012 that use a fully qualified name (C<sub Package::name { ... }>).
1013
1014 This will correctly handle functions renamed with B<Sub::Name> and 
1015 installed using the symbol tables. However, if you are naming the 
1016 subroutine outside of the package scope, you must use the fully 
1017 qualified name, including the package name, for C<has_method> to 
1018 correctly identify it. 
1019
1020 This will attempt to correctly ignore functions imported from other 
1021 packages using B<Exporter>. It breaks down if the function imported 
1022 is an C<__ANON__> sub (such as with C<use constant>), which very well 
1023 may be a valid method being applied to the class. 
1024
1025 In short, this method cannot always be trusted to determine if the 
1026 C<$method_name> is actually a method. However, it will DWIM about 
1027 90% of the time, so it's a small trade off I think.
1028
1029 =item B<get_method ($method_name)>
1030
1031 This will return a Class::MOP::Method instance related to the specified 
1032 C<$method_name>, or return undef if that method does not exist.
1033
1034 The Class::MOP::Method is codifiable, so you can use it like a normal 
1035 CODE reference, see L<Class::MOP::Method> for more information.
1036
1037 =item B<find_method_by_name ($method_name>
1038
1039 This will return a CODE reference of the specified C<$method_name>,
1040 or return undef if that method does not exist.
1041
1042 Unlike C<get_method> this will also look in the superclasses.
1043
1044 =item B<remove_method ($method_name)>
1045
1046 This will attempt to remove a given C<$method_name> from the class. 
1047 It will return the CODE reference that it has removed, and will 
1048 attempt to use B<Sub::Name> to clear the methods associated name.
1049
1050 =item B<get_method_list>
1051
1052 This will return a list of method names for all I<locally> defined 
1053 methods. It does B<not> provide a list of all applicable methods, 
1054 including any inherited ones. If you want a list of all applicable 
1055 methods, use the C<compute_all_applicable_methods> method.
1056
1057 =item B<compute_all_applicable_methods>
1058
1059 This will return a list of all the methods names this class will 
1060 respond to, taking into account inheritance. The list will be a list of 
1061 HASH references, each one containing the following information; method 
1062 name, the name of the class in which the method lives and a CODE 
1063 reference for the actual method.
1064
1065 =item B<find_all_methods_by_name ($method_name)>
1066
1067 This will traverse the inheritence hierarchy and locate all methods 
1068 with a given C<$method_name>. Similar to 
1069 C<compute_all_applicable_methods> it returns a list of HASH references 
1070 with the following information; method name (which will always be the 
1071 same as C<$method_name>), the name of the class in which the method 
1072 lives and a CODE reference for the actual method.
1073
1074 The list of methods produced is a distinct list, meaning there are no 
1075 duplicates in it. This is especially useful for things like object 
1076 initialization and destruction where you only want the method called 
1077 once, and in the correct order.
1078
1079 =item B<find_next_method_by_name ($method_name)>
1080
1081 This will return the first method to match a given C<$method_name> in 
1082 the superclasses, this is basically equivalent to calling 
1083 C<SUPER::$method_name>, but it can be dispatched at runtime.
1084
1085 =back
1086
1087 =head2 Method Modifiers
1088
1089 Method modifiers are a concept borrowed from CLOS, in which a method 
1090 can be wrapped with I<before>, I<after> and I<around> method modifiers 
1091 that will be called everytime the method is called. 
1092
1093 =head3 How method modifiers work?
1094
1095 Method modifiers work by wrapping the original method and then replacing 
1096 it in the classes symbol table. The wrappers will handle calling all the 
1097 modifiers in the appropariate orders and preserving the calling context 
1098 for the original method. 
1099
1100 Each method modifier serves a particular purpose, which may not be 
1101 obvious to users of other method wrapping modules. To start with, the 
1102 return values of I<before> and I<after> modifiers are ignored. This is 
1103 because thier purpose is B<not> to filter the input and output of the 
1104 primary method (this is done with an I<around> modifier). This may seem 
1105 like an odd restriction to some, but doing this allows for simple code 
1106 to be added at the begining or end of a method call without jeapordizing 
1107 the normal functioning of the primary method or placing any extra 
1108 responsibility on the code of the modifier. Of course if you have more 
1109 complex needs, then use the I<around> modifier, which uses a variation 
1110 of continutation passing style to allow for a high degree of flexibility. 
1111
1112 Before and around modifiers are called in last-defined-first-called order, 
1113 while after modifiers are called in first-defined-first-called order. So 
1114 the call tree might looks something like this:
1115   
1116   before 2
1117    before 1
1118     around 2
1119      around 1
1120       primary
1121      after 1
1122     after 2
1123
1124 To see examples of using method modifiers, see the following examples 
1125 included in the distribution; F<InstanceCountingClass>, F<Perl6Attribute>, 
1126 F<AttributesWithHistory> and F<C3MethodDispatchOrder>. There is also a 
1127 classic CLOS usage example in the test F<017_add_method_modifier.t>.
1128
1129 =head3 What is the performance impact?
1130
1131 Of course there is a performance cost associated with method modifiers, 
1132 but we have made every effort to make that cost be directly proportional 
1133 to the amount of modifier features you utilize.
1134
1135 The wrapping method does it's best to B<only> do as much work as it 
1136 absolutely needs to. In order to do this we have moved some of the 
1137 performance costs to set-up time, where they are easier to amortize.
1138
1139 All this said, my benchmarks have indicated the following:
1140
1141   simple wrapper with no modifiers             100% slower
1142   simple wrapper with simple before modifier   400% slower
1143   simple wrapper with simple after modifier    450% slower
1144   simple wrapper with simple around modifier   500-550% slower
1145   simple wrapper with all 3 modifiers          1100% slower
1146
1147 These numbers may seem daunting, but you must remember, every feature 
1148 comes with some cost. To put things in perspective, just doing a simple 
1149 C<AUTOLOAD> which does nothing but extract the name of the method called
1150 and return it costs about 400% over a normal method call. 
1151
1152 =over 4
1153
1154 =item B<add_before_method_modifier ($method_name, $code)>
1155
1156 This will wrap the method at C<$method_name> and the supplied C<$code> 
1157 will be passed the C<@_> arguments, and called before the original 
1158 method is called. As specified above, the return value of the I<before> 
1159 method modifiers is ignored, and it's ability to modify C<@_> is 
1160 fairly limited. If you need to do either of these things, use an 
1161 C<around> method modifier.
1162
1163 =item B<add_after_method_modifier ($method_name, $code)>
1164
1165 This will wrap the method at C<$method_name> so that the original 
1166 method will be called, it's return values stashed, and then the 
1167 supplied C<$code> will be passed the C<@_> arguments, and called.
1168 As specified above, the return value of the I<after> method 
1169 modifiers is ignored, and it cannot modify the return values of 
1170 the original method. If you need to do either of these things, use an 
1171 C<around> method modifier.
1172
1173 =item B<add_around_method_modifier ($method_name, $code)>
1174
1175 This will wrap the method at C<$method_name> so that C<$code> 
1176 will be called and passed the original method as an extra argument 
1177 at the begining of the C<@_> argument list. This is a variation of 
1178 continuation passing style, where the function prepended to C<@_> 
1179 can be considered a continuation. It is up to C<$code> if it calls 
1180 the original method or not, there is no restriction on what the 
1181 C<$code> can or cannot do.
1182
1183 =back
1184
1185 =head2 Attributes
1186
1187 It should be noted that since there is no one consistent way to define 
1188 the attributes of a class in Perl 5. These methods can only work with 
1189 the information given, and can not easily discover information on 
1190 their own. See L<Class::MOP::Attribute> for more details.
1191
1192 =over 4
1193
1194 =item B<attribute_metaclass>
1195
1196 =item B<get_attribute_map>
1197
1198 =item B<add_attribute ($attribute_name, $attribute_meta_object)>
1199
1200 This stores a C<$attribute_meta_object> in the B<Class::MOP::Class> 
1201 instance associated with the given class, and associates it with 
1202 the C<$attribute_name>. Unlike methods, attributes within the MOP 
1203 are stored as meta-information only. They will be used later to 
1204 construct instances from (see C<construct_instance> above).
1205 More details about the attribute meta-objects can be found in the 
1206 L<Class::MOP::Attribute> or the L<Class::MOP/The Attribute protocol>
1207 section.
1208
1209 It should be noted that any accessor, reader/writer or predicate 
1210 methods which the C<$attribute_meta_object> has will be installed 
1211 into the class at this time.
1212
1213 B<NOTE>
1214 If an attribute already exists for C<$attribute_name>, the old one 
1215 will be removed (as well as removing all it's accessors), and then 
1216 the new one added.
1217
1218 =item B<has_attribute ($attribute_name)>
1219
1220 Checks to see if this class has an attribute by the name of 
1221 C<$attribute_name> and returns a boolean.
1222
1223 =item B<get_attribute ($attribute_name)>
1224
1225 Returns the attribute meta-object associated with C<$attribute_name>, 
1226 if none is found, it will return undef. 
1227
1228 =item B<remove_attribute ($attribute_name)>
1229
1230 This will remove the attribute meta-object stored at 
1231 C<$attribute_name>, then return the removed attribute meta-object. 
1232
1233 B<NOTE:> 
1234 Removing an attribute will only affect future instances of 
1235 the class, it will not make any attempt to remove the attribute from 
1236 any existing instances of the class.
1237
1238 It should be noted that any accessor, reader/writer or predicate 
1239 methods which the attribute meta-object stored at C<$attribute_name> 
1240 has will be removed from the class at this time. This B<will> make 
1241 these attributes somewhat inaccessable in previously created 
1242 instances. But if you are crazy enough to do this at runtime, then 
1243 you are crazy enough to deal with something like this :).
1244
1245 =item B<get_attribute_list>
1246
1247 This returns a list of attribute names which are defined in the local 
1248 class. If you want a list of all applicable attributes for a class, 
1249 use the C<compute_all_applicable_attributes> method.
1250
1251 =item B<compute_all_applicable_attributes>
1252
1253 This will traverse the inheritance heirachy and return a list of all 
1254 the applicable attributes for this class. It does not construct a 
1255 HASH reference like C<compute_all_applicable_methods> because all 
1256 that same information is discoverable through the attribute 
1257 meta-object itself.
1258
1259 =item B<find_attribute_by_name ($attr_name)>
1260
1261 This method will traverse the inheritance heirachy and find the 
1262 first attribute whose name matches C<$attr_name>, then return it. 
1263 It will return undef if nothing is found.
1264
1265 =back
1266
1267 =head2 Class closing
1268
1269 =over 4
1270
1271 =item B<make_immutable>
1272
1273 =back
1274
1275 =head1 AUTHORS
1276
1277 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1278
1279 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
1280
1281 =head1 COPYRIGHT AND LICENSE
1282
1283 Copyright 2006 by Infinity Interactive, Inc.
1284
1285 L<http://www.iinteractive.com>
1286
1287 This library is free software; you can redistribute it and/or modify
1288 it under the same terms as Perl itself. 
1289
1290 =cut