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