add associated_metaclass to Method
[gitmo/Class-MOP.git] / lib / Class / MOP.pm
1
2 package Class::MOP;
3
4 use strict;
5 use warnings;
6
7 use MRO::Compat;
8
9 use Carp          'confess';
10 use Scalar::Util  'weaken';
11
12 use Class::MOP::Class;
13 use Class::MOP::Attribute;
14 use Class::MOP::Method;
15
16 use Class::MOP::Immutable;
17
18 BEGIN {
19     
20     our $VERSION   = '0.65';
21     our $AUTHORITY = 'cpan:STEVAN';    
22     
23     *IS_RUNNING_ON_5_10 = ($] < 5.009_005) 
24         ? sub () { 0 }
25         : sub () { 1 };    
26
27     *HAVE_ISAREV = defined(&mro::get_isarev)
28         ? sub () { 1 }
29         : sub () { 1 };
30
31     # NOTE:
32     # we may not use this yet, but once 
33     # the get_code_info XS gets merged 
34     # upstream to it, we will always use 
35     # it. But for now it is just kinda 
36     # extra overhead.
37     # - SL
38     require Sub::Identify;
39         
40     # stash these for a sec, and see how things go
41     my $_PP_subname       = sub { $_[1] };
42     my $_PP_get_code_info = \&Sub::Identify::get_code_info;    
43     
44     if ($ENV{CLASS_MOP_NO_XS}) {
45         # NOTE:
46         # this is if you really want things
47         # to be slow, then you can force the
48         # no-XS rule this way, otherwise we 
49         # make an effort to load as much of 
50         # the XS as possible.
51         # - SL
52         no warnings 'prototype', 'redefine';
53         
54         # this is either part of core or set up appropriately by MRO::Compat
55         *check_package_cache_flag = \&mro::get_pkg_gen; 
56
57         # our own version of Sub::Name
58         *subname       = $_PP_subname;
59         # and the Sub::Identify version of the get_code_info
60         *get_code_info = $_PP_get_code_info;        
61     }
62     else {
63         # now try our best to get as much 
64         # of the XS loaded as possible
65         {
66             local $@;
67             eval {
68                 require XSLoader;
69                 XSLoader::load( 'Class::MOP', $VERSION );            
70             };
71             die $@ if $@ && $@ !~ /object version|loadable object/;
72             
73             # okay, so the XS failed to load, so 
74             # use the pure perl one instead.
75             *get_code_info = $_PP_get_code_info if $@; 
76         }        
77         
78         # get it from MRO::Compat
79         *check_package_cache_flag = \&mro::get_pkg_gen;        
80         
81         # now try and load the Sub::Name 
82         # module and use that as a means
83         # for naming our CVs, if not, we 
84         # use the workaround instead.
85         if ( eval { require Sub::Name } ) {
86             *subname = \&Sub::Name::subname;
87         } 
88         else {
89             *subname = $_PP_subname;
90         }     
91     }
92 }
93
94 {
95     # Metaclasses are singletons, so we cache them here.
96     # there is no need to worry about destruction though
97     # because they should die only when the program dies.
98     # After all, do package definitions even get reaped?
99     my %METAS;
100
101     # means of accessing all the metaclasses that have
102     # been initialized thus far (for mugwumps obj browser)
103     sub get_all_metaclasses         {        %METAS         }
104     sub get_all_metaclass_instances { values %METAS         }
105     sub get_all_metaclass_names     { keys   %METAS         }
106     sub get_metaclass_by_name       { $METAS{$_[0]}         }
107     sub store_metaclass_by_name     { $METAS{$_[0]} = $_[1] }
108     sub weaken_metaclass            { weaken($METAS{$_[0]}) }
109     sub does_metaclass_exist        { exists $METAS{$_[0]} && defined $METAS{$_[0]} }
110     sub remove_metaclass_by_name    { $METAS{$_[0]} = undef }
111
112     # NOTE:
113     # We only cache metaclasses, meaning instances of
114     # Class::MOP::Class. We do not cache instance of
115     # Class::MOP::Package or Class::MOP::Module. Mostly
116     # because I don't yet see a good reason to do so.
117 }
118
119 sub load_class {
120     my $class = shift;
121
122     if (ref($class) || !defined($class) || !length($class)) {
123         my $display = defined($class) ? $class : 'undef';
124         confess "Invalid class name ($display)";
125     }
126
127     # if the class is not already loaded in the symbol table..
128     unless (is_class_loaded($class)) {
129         # require it
130         my $file = $class . '.pm';
131         $file =~ s{::}{/}g;
132         eval { CORE::require($file) };
133         confess "Could not load class ($class) because : $@" if $@;
134     }
135
136     # initialize a metaclass if necessary
137     unless (does_metaclass_exist($class)) {
138         eval { Class::MOP::Class->initialize($class) };
139         confess "Could not initialize class ($class) because : $@" if $@;
140     }
141
142     return get_metaclass_by_name($class);
143 }
144
145 sub is_class_loaded {
146     my $class = shift;
147
148     return 0 if ref($class) || !defined($class) || !length($class);
149
150     # walk the symbol table tree to avoid autovififying
151     # \*{${main::}{"Foo::"}} == \*main::Foo::
152
153     my $pack = \*::;
154     foreach my $part (split('::', $class)) {
155         return 0 unless exists ${$$pack}{"${part}::"};
156         $pack = \*{${$$pack}{"${part}::"}};
157     }
158
159     # check for $VERSION or @ISA
160     return 1 if exists ${$$pack}{VERSION}
161              && defined *{${$$pack}{VERSION}}{SCALAR};
162     return 1 if exists ${$$pack}{ISA}
163              && defined *{${$$pack}{ISA}}{ARRAY};
164
165     # check for any method
166     foreach ( keys %{$$pack} ) {
167         next if substr($_, -2, 2) eq '::';
168
169         my $glob = ${$$pack}{$_} || next;
170
171         # constant subs
172         if ( IS_RUNNING_ON_5_10 ) {
173             return 1 if ref $glob eq 'SCALAR';
174         }
175
176         return 1 if defined *{$glob}{CODE};
177     }
178
179     # fail
180     return 0;
181 }
182
183
184 ## ----------------------------------------------------------------------------
185 ## Setting up our environment ...
186 ## ----------------------------------------------------------------------------
187 ## Class::MOP needs to have a few things in the global perl environment so
188 ## that it can operate effectively. Those things are done here.
189 ## ----------------------------------------------------------------------------
190
191 # ... nothing yet actually ;)
192
193 ## ----------------------------------------------------------------------------
194 ## Bootstrapping
195 ## ----------------------------------------------------------------------------
196 ## The code below here is to bootstrap our MOP with itself. This is also
197 ## sometimes called "tying the knot". By doing this, we make it much easier
198 ## to extend the MOP through subclassing and such since now you can use the
199 ## MOP itself to extend itself.
200 ##
201 ## Yes, I know, thats weird and insane, but it's a good thing, trust me :)
202 ## ----------------------------------------------------------------------------
203
204 # We need to add in the meta-attributes here so that
205 # any subclass of Class::MOP::* will be able to
206 # inherit them using &construct_instance
207
208 ## --------------------------------------------------------
209 ## Class::MOP::Package
210
211 Class::MOP::Package->meta->add_attribute(
212     Class::MOP::Attribute->new('package' => (
213         reader   => {
214             # NOTE: we need to do this in order
215             # for the instance meta-object to
216             # not fall into meta-circular death
217             #
218             # we just alias the original method
219             # rather than re-produce it here
220             'name' => \&Class::MOP::Package::name
221         },
222         init_arg => 'package',
223     ))
224 );
225
226 Class::MOP::Package->meta->add_attribute(
227     Class::MOP::Attribute->new('namespace' => (
228         reader => {
229             # NOTE:
230             # we just alias the original method
231             # rather than re-produce it here
232             'namespace' => \&Class::MOP::Package::namespace
233         },
234         init_arg => undef,
235         default  => sub { \undef }
236     ))
237 );
238
239 # NOTE:
240 # use the metaclass to construct the meta-package
241 # which is a superclass of the metaclass itself :P
242 Class::MOP::Package->meta->add_method('initialize' => sub {
243     my $class        = shift;
244     my $package_name = shift;
245     $class->meta->new_object('package' => $package_name, @_);
246 });
247
248 ## --------------------------------------------------------
249 ## Class::MOP::Module
250
251 # NOTE:
252 # yeah this is kind of stretching things a bit,
253 # but truthfully the version should be an attribute
254 # of the Module, the weirdness comes from having to
255 # stick to Perl 5 convention and store it in the
256 # $VERSION package variable. Basically if you just
257 # squint at it, it will look how you want it to look.
258 # Either as a package variable, or as a attribute of
259 # the metaclass, isn't abstraction great :)
260
261 Class::MOP::Module->meta->add_attribute(
262     Class::MOP::Attribute->new('version' => (
263         reader => {
264             # NOTE:
265             # we just alias the original method
266             # rather than re-produce it here
267             'version' => \&Class::MOP::Module::version
268         },
269         init_arg => undef,
270         default  => sub { \undef }
271     ))
272 );
273
274 # NOTE:
275 # By following the same conventions as version here,
276 # we are opening up the possibility that people can
277 # use the $AUTHORITY in non-Class::MOP modules as
278 # well.
279
280 Class::MOP::Module->meta->add_attribute(
281     Class::MOP::Attribute->new('authority' => (
282         reader => {
283             # NOTE:
284             # we just alias the original method
285             # rather than re-produce it here
286             'authority' => \&Class::MOP::Module::authority
287         },
288         init_arg => undef,
289         default  => sub { \undef }
290     ))
291 );
292
293 ## --------------------------------------------------------
294 ## Class::MOP::Class
295
296 Class::MOP::Class->meta->add_attribute(
297     Class::MOP::Attribute->new('attributes' => (
298         reader   => {
299             # NOTE: we need to do this in order
300             # for the instance meta-object to
301             # not fall into meta-circular death
302             #
303             # we just alias the original method
304             # rather than re-produce it here
305             'get_attribute_map' => \&Class::MOP::Class::get_attribute_map
306         },
307         init_arg => 'attributes',
308         default  => sub { {} }
309     ))
310 );
311
312 Class::MOP::Class->meta->add_attribute(
313     Class::MOP::Attribute->new('methods' => (
314         init_arg => 'methods',
315         reader   => {
316             # NOTE:
317             # we just alias the original method
318             # rather than re-produce it here
319             'get_method_map' => \&Class::MOP::Class::get_method_map
320         },
321         default => sub { {} }
322     ))
323 );
324
325 Class::MOP::Class->meta->add_attribute(
326     Class::MOP::Attribute->new('superclasses' => (
327         accessor => {
328             # NOTE:
329             # we just alias the original method
330             # rather than re-produce it here
331             'superclasses' => \&Class::MOP::Class::superclasses
332         },
333         init_arg => undef,
334         default  => sub { \undef }
335     ))
336 );
337
338 Class::MOP::Class->meta->add_attribute(
339     Class::MOP::Attribute->new('attribute_metaclass' => (
340         reader   => {
341             # NOTE:
342             # we just alias the original method
343             # rather than re-produce it here
344             'attribute_metaclass' => \&Class::MOP::Class::attribute_metaclass
345         },
346         init_arg => 'attribute_metaclass',
347         default  => 'Class::MOP::Attribute',
348     ))
349 );
350
351 Class::MOP::Class->meta->add_attribute(
352     Class::MOP::Attribute->new('method_metaclass' => (
353         reader   => {
354             # NOTE:
355             # we just alias the original method
356             # rather than re-produce it here
357             'method_metaclass' => \&Class::MOP::Class::method_metaclass
358         },
359         init_arg => 'method_metaclass',
360         default  => 'Class::MOP::Method',
361     ))
362 );
363
364 Class::MOP::Class->meta->add_attribute(
365     Class::MOP::Attribute->new('instance_metaclass' => (
366         reader   => {
367             # NOTE: we need to do this in order
368             # for the instance meta-object to
369             # not fall into meta-circular death
370             #
371             # we just alias the original method
372             # rather than re-produce it here
373             'instance_metaclass' => \&Class::MOP::Class::instance_metaclass
374         },
375         init_arg => 'instance_metaclass',
376         default  => 'Class::MOP::Instance',
377     ))
378 );
379
380 # NOTE:
381 # we don't actually need to tie the knot with
382 # Class::MOP::Class here, it is actually handled
383 # within Class::MOP::Class itself in the
384 # construct_class_instance method.
385
386 ## --------------------------------------------------------
387 ## Class::MOP::Attribute
388
389 Class::MOP::Attribute->meta->add_attribute(
390     Class::MOP::Attribute->new('name' => (
391         init_arg => 'name',
392         reader   => {
393             # NOTE: we need to do this in order
394             # for the instance meta-object to
395             # not fall into meta-circular death
396             #
397             # we just alias the original method
398             # rather than re-produce it here
399             'name' => \&Class::MOP::Attribute::name
400         }
401     ))
402 );
403
404 Class::MOP::Attribute->meta->add_attribute(
405     Class::MOP::Attribute->new('associated_class' => (
406         init_arg => 'associated_class',
407         reader   => {
408             # NOTE: we need to do this in order
409             # for the instance meta-object to
410             # not fall into meta-circular death
411             #
412             # we just alias the original method
413             # rather than re-produce it here
414             'associated_class' => \&Class::MOP::Attribute::associated_class
415         }
416     ))
417 );
418
419 Class::MOP::Attribute->meta->add_attribute(
420     Class::MOP::Attribute->new('accessor' => (
421         init_arg  => 'accessor',
422         reader    => { 'accessor'     => \&Class::MOP::Attribute::accessor     },
423         predicate => { 'has_accessor' => \&Class::MOP::Attribute::has_accessor },
424     ))
425 );
426
427 Class::MOP::Attribute->meta->add_attribute(
428     Class::MOP::Attribute->new('reader' => (
429         init_arg  => 'reader',
430         reader    => { 'reader'     => \&Class::MOP::Attribute::reader     },
431         predicate => { 'has_reader' => \&Class::MOP::Attribute::has_reader },
432     ))
433 );
434
435 Class::MOP::Attribute->meta->add_attribute(
436     Class::MOP::Attribute->new('initializer' => (
437         init_arg  => 'initializer',
438         reader    => { 'initializer'     => \&Class::MOP::Attribute::initializer     },
439         predicate => { 'has_initializer' => \&Class::MOP::Attribute::has_initializer },
440     ))
441 );
442
443 Class::MOP::Attribute->meta->add_attribute(
444     Class::MOP::Attribute->new('writer' => (
445         init_arg  => 'writer',
446         reader    => { 'writer'     => \&Class::MOP::Attribute::writer     },
447         predicate => { 'has_writer' => \&Class::MOP::Attribute::has_writer },
448     ))
449 );
450
451 Class::MOP::Attribute->meta->add_attribute(
452     Class::MOP::Attribute->new('predicate' => (
453         init_arg  => 'predicate',
454         reader    => { 'predicate'     => \&Class::MOP::Attribute::predicate     },
455         predicate => { 'has_predicate' => \&Class::MOP::Attribute::has_predicate },
456     ))
457 );
458
459 Class::MOP::Attribute->meta->add_attribute(
460     Class::MOP::Attribute->new('clearer' => (
461         init_arg  => 'clearer',
462         reader    => { 'clearer'     => \&Class::MOP::Attribute::clearer     },
463         predicate => { 'has_clearer' => \&Class::MOP::Attribute::has_clearer },
464     ))
465 );
466
467 Class::MOP::Attribute->meta->add_attribute(
468     Class::MOP::Attribute->new('builder' => (
469         init_arg  => 'builder',
470         reader    => { 'builder'     => \&Class::MOP::Attribute::builder     },
471         predicate => { 'has_builder' => \&Class::MOP::Attribute::has_builder },
472     ))
473 );
474
475 Class::MOP::Attribute->meta->add_attribute(
476     Class::MOP::Attribute->new('init_arg' => (
477         init_arg  => 'init_arg',
478         reader    => { 'init_arg'     => \&Class::MOP::Attribute::init_arg     },
479         predicate => { 'has_init_arg' => \&Class::MOP::Attribute::has_init_arg },
480     ))
481 );
482
483 Class::MOP::Attribute->meta->add_attribute(
484     Class::MOP::Attribute->new('default' => (
485         init_arg  => 'default',
486         # default has a custom 'reader' method ...
487         predicate => { 'has_default' => \&Class::MOP::Attribute::has_default },
488     ))
489 );
490
491 Class::MOP::Attribute->meta->add_attribute(
492     Class::MOP::Attribute->new('associated_methods' => (
493         init_arg => 'associated_methods',
494         reader   => { 'associated_methods' => \&Class::MOP::Attribute::associated_methods },
495         default  => sub { [] }
496     ))
497 );
498
499 # NOTE: (meta-circularity)
500 # This should be one of the last things done
501 # it will "tie the knot" with Class::MOP::Attribute
502 # so that it uses the attributes meta-objects
503 # to construct itself.
504 Class::MOP::Attribute->meta->add_method('new' => sub {
505     my ( $class, @args ) = @_;
506
507     unshift @args, "name" if @args % 2 == 1;
508     my %options = @args;
509
510     my $name = $options{name};
511
512     (defined $name && $name)
513         || confess "You must provide a name for the attribute";
514     $options{init_arg} = $name
515         if not exists $options{init_arg};
516
517     if(exists $options{builder}){
518         confess("builder must be a defined scalar value which is a method name")
519             if ref $options{builder} || !(defined $options{builder});
520         confess("Setting both default and builder is not allowed.")
521             if exists $options{default};
522     } else {
523         (Class::MOP::Attribute::is_default_a_coderef(\%options))
524             || confess("References are not allowed as default values, you must ".
525                        "wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])")
526                 if exists $options{default} && ref $options{default};
527     }
528
529     # return the new object
530     $class->meta->new_object(%options);
531 });
532
533 Class::MOP::Attribute->meta->add_method('clone' => sub {
534     my $self  = shift;
535     $self->meta->clone_object($self, @_);
536 });
537
538 ## --------------------------------------------------------
539 ## Class::MOP::Method
540 Class::MOP::Method->meta->add_attribute(
541     Class::MOP::Attribute->new('body' => (
542         init_arg => 'body',
543         reader   => { 'body' => \&Class::MOP::Method::body },
544     ))
545 );
546
547 Class::MOP::Method->meta->add_attribute(
548     Class::MOP::Attribute->new('associated_metaclass' => (
549         init_arg => 'associated_metaclass',
550         reader   => { 'associated_metaclass' => \&Class::MOP::Method::associated_metaclass },
551     ))
552 );
553
554 Class::MOP::Method->meta->add_attribute(
555     Class::MOP::Attribute->new('package_name' => (
556         init_arg => 'package_name',
557         reader   => { 'package_name' => \&Class::MOP::Method::package_name },
558     ))
559 );
560
561 Class::MOP::Method->meta->add_attribute(
562     Class::MOP::Attribute->new('name' => (
563         init_arg => 'name',
564         reader   => { 'name' => \&Class::MOP::Method::name },
565     ))
566 );
567
568 Class::MOP::Method->meta->add_method('wrap' => sub {
569     my ( $class, @args ) = @_;
570
571     unshift @args, 'body' if @args % 2 == 1;
572
573     my %options = @args;
574     my $code = $options{body};
575
576     ('CODE' eq ref($code))
577         || confess "You must supply a CODE reference to bless, not (" . ($code || 'undef') . ")";
578
579     ($options{package_name} && $options{name})
580         || confess "You must supply the package_name and name parameters";
581
582     # return the new object
583     $class->meta->new_object(%options);
584 });
585
586 Class::MOP::Method->meta->add_method('clone' => sub {
587     my $self  = shift;
588     $self->meta->clone_object($self, @_);
589 });
590
591 ## --------------------------------------------------------
592 ## Class::MOP::Method::Wrapped
593
594 # NOTE:
595 # the way this item is initialized, this
596 # really does not follow the standard
597 # practices of attributes, but we put
598 # it here for completeness
599 Class::MOP::Method::Wrapped->meta->add_attribute(
600     Class::MOP::Attribute->new('modifier_table')
601 );
602
603 ## --------------------------------------------------------
604 ## Class::MOP::Method::Generated
605
606 Class::MOP::Method::Generated->meta->add_attribute(
607     Class::MOP::Attribute->new('is_inline' => (
608         init_arg => 'is_inline',
609         reader   => { 'is_inline' => \&Class::MOP::Method::Generated::is_inline },
610         default  => 0, 
611     ))
612 );
613
614 Class::MOP::Method::Generated->meta->add_method('new' => sub {
615     my ($class, %options) = @_;
616     ($options{package_name} && $options{name})
617         || confess "You must supply the package_name and name parameters";    
618     my $self = $class->meta->new_object(%options);
619     $self->initialize_body;  
620     $self;
621 });
622
623 ## --------------------------------------------------------
624 ## Class::MOP::Method::Accessor
625
626 Class::MOP::Method::Accessor->meta->add_attribute(
627     Class::MOP::Attribute->new('attribute' => (
628         init_arg => 'attribute',
629         reader   => {
630             'associated_attribute' => \&Class::MOP::Method::Accessor::associated_attribute
631         },
632     ))
633 );
634
635 Class::MOP::Method::Accessor->meta->add_attribute(
636     Class::MOP::Attribute->new('accessor_type' => (
637         init_arg => 'accessor_type',
638         reader   => { 'accessor_type' => \&Class::MOP::Method::Accessor::accessor_type },
639     ))
640 );
641
642 Class::MOP::Method::Accessor->meta->add_method('new' => sub {
643     my $class   = shift;
644     my %options = @_;
645
646     (exists $options{attribute})
647         || confess "You must supply an attribute to construct with";
648
649     (exists $options{accessor_type})
650         || confess "You must supply an accessor_type to construct with";
651
652     (Scalar::Util::blessed($options{attribute}) && $options{attribute}->isa('Class::MOP::Attribute'))
653         || confess "You must supply an attribute which is a 'Class::MOP::Attribute' instance";
654
655     ($options{package_name} && $options{name})
656         || confess "You must supply the package_name and name parameters";
657
658     # return the new object
659     my $self = $class->meta->new_object(%options);
660     
661     # we don't want this creating
662     # a cycle in the code, if not
663     # needed
664     Scalar::Util::weaken($self->{'attribute'});
665
666     $self->initialize_body;  
667     
668     $self;
669 });
670
671
672 ## --------------------------------------------------------
673 ## Class::MOP::Method::Constructor
674
675 Class::MOP::Method::Constructor->meta->add_attribute(
676     Class::MOP::Attribute->new('options' => (
677         init_arg => 'options',
678         reader   => {
679             'options' => \&Class::MOP::Method::Constructor::options
680         },
681         default  => sub { +{} }
682     ))
683 );
684
685 Class::MOP::Method::Constructor->meta->add_attribute(
686     Class::MOP::Attribute->new('associated_metaclass' => (
687         init_arg => 'metaclass',
688         reader   => {
689             'associated_metaclass' => \&Class::MOP::Method::Constructor::associated_metaclass
690         },
691     ))
692 );
693
694 Class::MOP::Method::Constructor->meta->add_method('new' => sub {
695     my $class   = shift;
696     my %options = @_;
697
698     (Scalar::Util::blessed $options{metaclass} && $options{metaclass}->isa('Class::MOP::Class'))
699         || confess "You must pass a metaclass instance if you want to inline"
700             if $options{is_inline};
701
702     ($options{package_name} && $options{name})
703         || confess "You must supply the package_name and name parameters";
704
705     # return the new object
706     my $self = $class->meta->new_object(%options);
707     
708     # we don't want this creating
709     # a cycle in the code, if not
710     # needed
711     Scalar::Util::weaken($self->{'associated_metaclass'});
712
713     $self->initialize_body;  
714     
715     $self;
716 });
717
718 ## --------------------------------------------------------
719 ## Class::MOP::Instance
720
721 # NOTE:
722 # these don't yet do much of anything, but are just
723 # included for completeness
724
725 Class::MOP::Instance->meta->add_attribute(
726     Class::MOP::Attribute->new('associated_metaclass')
727 );
728
729 Class::MOP::Instance->meta->add_attribute(
730     Class::MOP::Attribute->new('attributes')
731 );
732
733 Class::MOP::Instance->meta->add_attribute(
734     Class::MOP::Attribute->new('slots')
735 );
736
737 Class::MOP::Instance->meta->add_attribute(
738     Class::MOP::Attribute->new('slot_hash')
739 );
740
741
742 # we need the meta instance of the meta instance to be created now, in order
743 # for the constructor to be able to use it
744 Class::MOP::Instance->meta->get_meta_instance;
745
746 Class::MOP::Instance->meta->add_method('new' => sub {
747     my $class   = shift;
748     my $options = $class->BUILDARGS(@_);
749
750     my $self = $class->meta->new_object(%$options);
751     
752     Scalar::Util::weaken($self->{'associated_metaclass'});
753
754     $self;
755 });
756
757 # pretend the add_method never happenned. it hasn't yet affected anything
758 undef Class::MOP::Instance->meta->{_package_cache_flag};
759
760 ## --------------------------------------------------------
761 ## Now close all the Class::MOP::* classes
762
763 # NOTE:
764 # we don't need to inline the
765 # constructors or the accessors
766 # this only lengthens the compile
767 # time of the MOP, and gives us
768 # no actual benefits.
769
770 $_->meta->make_immutable(
771     inline_constructor => 0,
772     inline_accessors   => 0,
773 ) for qw/
774     Class::MOP::Package
775     Class::MOP::Module
776     Class::MOP::Class
777
778     Class::MOP::Attribute
779     Class::MOP::Method
780     Class::MOP::Instance
781
782     Class::MOP::Object
783
784     Class::MOP::Method::Generated
785
786     Class::MOP::Method::Accessor
787     Class::MOP::Method::Constructor
788     Class::MOP::Method::Wrapped
789 /;
790
791 1;
792
793 __END__
794
795 =pod
796
797 =head1 NAME
798
799 Class::MOP - A Meta Object Protocol for Perl 5
800
801 =head1 DESCRIPTON
802
803 This module is a fully functioning meta object protocol for the
804 Perl 5 object system. It makes no attempt to change the behavior or
805 characteristics of the Perl 5 object system, only to create a
806 protocol for its manipulation and introspection.
807
808 That said, it does attempt to create the tools for building a rich
809 set of extensions to the Perl 5 object system. Every attempt has been
810 made for these tools to keep to the spirit of the Perl 5 object
811 system that we all know and love.
812
813 This documentation is admittedly sparse on details, as time permits
814 I will try to improve them. For now, I suggest looking at the items
815 listed in the L<SEE ALSO> section for more information. In particular
816 the book "The Art of the Meta Object Protocol" was very influential
817 in the development of this system.
818
819 =head2 What is a Meta Object Protocol?
820
821 A meta object protocol is an API to an object system.
822
823 To be more specific, it is a set of abstractions of the components of
824 an object system (typically things like; classes, object, methods,
825 object attributes, etc.). These abstractions can then be used to both
826 inspect and manipulate the object system which they describe.
827
828 It can be said that there are two MOPs for any object system; the
829 implicit MOP, and the explicit MOP. The implicit MOP handles things
830 like method dispatch or inheritance, which happen automatically as
831 part of how the object system works. The explicit MOP typically
832 handles the introspection/reflection features of the object system.
833 All object systems have implicit MOPs, without one, they would not
834 work. Explict MOPs however as less common, and depending on the
835 language can vary from restrictive (Reflection in Java or C#) to
836 wide open (CLOS is a perfect example).
837
838 =head2 Yet Another Class Builder!! Why?
839
840 This is B<not> a class builder so much as it is a I<class builder
841 B<builder>>. My intent is that an end user does not use this module
842 directly, but instead this module is used by module authors to
843 build extensions and features onto the Perl 5 object system.
844
845 =head2 Who is this module for?
846
847 This module is specifically for anyone who has ever created or
848 wanted to create a module for the Class:: namespace. The tools which
849 this module will provide will hopefully make it easier to do more
850 complex things with Perl 5 classes by removing such barriers as
851 the need to hack the symbol tables, or understand the fine details
852 of method dispatch.
853
854 =head2 What changes do I have to make to use this module?
855
856 This module was designed to be as unintrusive as possible. Many of
857 its features are accessible without B<any> change to your existsing
858 code at all. It is meant to be a compliment to your existing code and
859 not an intrusion on your code base. Unlike many other B<Class::>
860 modules, this module B<does not> require you subclass it, or even that
861 you C<use> it in within your module's package.
862
863 The only features which requires additions to your code are the
864 attribute handling and instance construction features, and these are
865 both completely optional features. The only reason for this is because
866 Perl 5's object system does not actually have these features built
867 in. More information about this feature can be found below.
868
869 =head2 A Note about Performance?
870
871 It is a common misconception that explict MOPs are performance drains.
872 But this is not a universal truth at all, it is an side-effect of
873 specific implementations. For instance, using Java reflection is much
874 slower because the JVM cannot take advantage of any compiler
875 optimizations, and the JVM has to deal with much more runtime type
876 information as well. Reflection in C# is marginally better as it was
877 designed into the language and runtime (the CLR). In contrast, CLOS
878 (the Common Lisp Object System) was built to support an explicit MOP,
879 and so performance is tuned for it.
880
881 This library in particular does it's absolute best to avoid putting
882 B<any> drain at all upon your code's performance. In fact, by itself
883 it does nothing to affect your existing code. So you only pay for
884 what you actually use.
885
886 =head2 About Metaclass compatibility
887
888 This module makes sure that all metaclasses created are both upwards
889 and downwards compatible. The topic of metaclass compatibility is
890 highly esoteric and is something only encountered when doing deep and
891 involved metaclass hacking. There are two basic kinds of metaclass
892 incompatibility; upwards and downwards.
893
894 Upwards metaclass compatibility means that the metaclass of a
895 given class is either the same as (or a subclass of) all of the
896 class's ancestors.
897
898 Downward metaclass compatibility means that the metaclasses of a
899 given class's anscestors are all either the same as (or a subclass
900 of) that metaclass.
901
902 Here is a diagram showing a set of two classes (C<A> and C<B>) and
903 two metaclasses (C<Meta::A> and C<Meta::B>) which have correct
904 metaclass compatibility both upwards and downwards.
905
906     +---------+     +---------+
907     | Meta::A |<----| Meta::B |      <....... (instance of  )
908     +---------+     +---------+      <------- (inherits from)
909          ^               ^
910          :               :
911     +---------+     +---------+
912     |    A    |<----|    B    |
913     +---------+     +---------+
914
915 As I said this is a highly esoteric topic and one you will only run
916 into if you do a lot of subclassing of B<Class::MOP::Class>. If you
917 are interested in why this is an issue see the paper
918 I<Uniform and safe metaclass composition> linked to in the
919 L<SEE ALSO> section of this document.
920
921 =head2 Using custom metaclasses
922
923 Always use the metaclass pragma when using a custom metaclass, this
924 will ensure the proper initialization order and not accidentely
925 create an incorrect type of metaclass for you. This is a very rare
926 problem, and one which can only occur if you are doing deep metaclass
927 programming. So in other words, don't worry about it.
928
929 =head1 PROTOCOLS
930
931 The protocol is divided into 4 main sub-protocols:
932
933 =over 4
934
935 =item The Class protocol
936
937 This provides a means of manipulating and introspecting a Perl 5
938 class. It handles all of symbol table hacking for you, and provides
939 a rich set of methods that go beyond simple package introspection.
940
941 See L<Class::MOP::Class> for more details.
942
943 =item The Attribute protocol
944
945 This provides a consistent represenation for an attribute of a
946 Perl 5 class. Since there are so many ways to create and handle
947 attributes in Perl 5 OO, this attempts to provide as much of a
948 unified approach as possible, while giving the freedom and
949 flexibility to subclass for specialization.
950
951 See L<Class::MOP::Attribute> for more details.
952
953 =item The Method protocol
954
955 This provides a means of manipulating and introspecting methods in
956 the Perl 5 object system. As with attributes, there are many ways to
957 approach this topic, so we try to keep it pretty basic, while still
958 making it possible to extend the system in many ways.
959
960 See L<Class::MOP::Method> for more details.
961
962 =item The Instance protocol
963
964 This provides a layer of abstraction for creating object instances. 
965 Since the other layers use this protocol, it is relatively easy to 
966 change the type of your instances from the default HASH ref to other
967 types of references. Several examples are provided in the F<examples/> 
968 directory included in this distribution.
969
970 See L<Class::MOP::Instance> for more details.
971
972 =back
973
974 =head1 FUNCTIONS
975
976 =head2 Constants
977
978 =over 4
979
980 =item I<IS_RUNNING_ON_5_10>
981
982 We set this constant depending on what version perl we are on, this 
983 allows us to take advantage of new 5.10 features and stay backwards 
984 compat.
985
986 =item I<HAVE_ISAREV>
987
988 Whether or not C<mro> provides C<get_isarev>, a much faster way to get all the
989 subclasses of a certain class.
990
991 =back
992
993 =head2 Utility functions
994
995 =over 4
996
997 =item B<load_class ($class_name)>
998
999 This will load a given C<$class_name> and if it does not have an
1000 already initialized metaclass, then it will intialize one for it.
1001 This function can be used in place of tricks like 
1002 C<eval "use $module"> or using C<require>.
1003
1004 =item B<is_class_loaded ($class_name)>
1005
1006 This will return a boolean depending on if the C<$class_name> has
1007 been loaded.
1008
1009 NOTE: This does a basic check of the symbol table to try and
1010 determine as best it can if the C<$class_name> is loaded, it
1011 is probably correct about 99% of the time.
1012
1013 =item B<check_package_cache_flag ($pkg)>
1014
1015 This will return an integer that is managed by C<Class::MOP::Class>
1016 to determine if a module's symbol table has been altered. 
1017
1018 In Perl 5.10 or greater, this flag is package specific. However in 
1019 versions prior to 5.10, this will use the C<PL_sub_generation> variable
1020 which is not package specific. 
1021
1022 =item B<get_code_info ($code)>
1023
1024 This function returns two values, the name of the package the C<$code> 
1025 is from and the name of the C<$code> itself. This is used by several 
1026 elements of the MOP to detemine where a given C<$code> reference is from.
1027
1028 =item B<subname ($name, $code)>
1029
1030 B<NOTE: DO NOT USE THIS FUNCTION, IT IS FOR INTERNAL USE ONLY!>
1031
1032 If possible, we will load the L<Sub::Name> module and this will function 
1033 as C<Sub::Name::subname> does, otherwise it will just return the C<$code>
1034 argument.
1035
1036 =back
1037
1038 =head2 Metaclass cache functions
1039
1040 Class::MOP holds a cache of metaclasses, the following are functions
1041 (B<not methods>) which can be used to access that cache. It is not
1042 recommended that you mess with this, bad things could happen. But if
1043 you are brave and willing to risk it, go for it.
1044
1045 =over 4
1046
1047 =item B<get_all_metaclasses>
1048
1049 This will return an hash of all the metaclass instances that have
1050 been cached by B<Class::MOP::Class> keyed by the package name.
1051
1052 =item B<get_all_metaclass_instances>
1053
1054 This will return an array of all the metaclass instances that have
1055 been cached by B<Class::MOP::Class>.
1056
1057 =item B<get_all_metaclass_names>
1058
1059 This will return an array of all the metaclass names that have
1060 been cached by B<Class::MOP::Class>.
1061
1062 =item B<get_metaclass_by_name ($name)>
1063
1064 This will return a cached B<Class::MOP::Class> instance of nothing
1065 if no metaclass exist by that C<$name>.
1066
1067 =item B<store_metaclass_by_name ($name, $meta)>
1068
1069 This will store a metaclass in the cache at the supplied C<$key>.
1070
1071 =item B<weaken_metaclass ($name)>
1072
1073 In rare cases it is desireable to store a weakened reference in 
1074 the metaclass cache. This function will weaken the reference to 
1075 the metaclass stored in C<$name>.
1076
1077 =item B<does_metaclass_exist ($name)>
1078
1079 This will return true of there exists a metaclass stored in the 
1080 C<$name> key and return false otherwise.
1081
1082 =item B<remove_metaclass_by_name ($name)>
1083
1084 This will remove a the metaclass stored in the C<$name> key.
1085
1086 =back
1087
1088 =head1 SEE ALSO
1089
1090 =head2 Books
1091
1092 There are very few books out on Meta Object Protocols and Metaclasses
1093 because it is such an esoteric topic. The following books are really
1094 the only ones I have found. If you know of any more, B<I<please>>
1095 email me and let me know, I would love to hear about them.
1096
1097 =over 4
1098
1099 =item "The Art of the Meta Object Protocol"
1100
1101 =item "Advances in Object-Oriented Metalevel Architecture and Reflection"
1102
1103 =item "Putting MetaClasses to Work"
1104
1105 =item "Smalltalk: The Language"
1106
1107 =back
1108
1109 =head2 Papers
1110
1111 =over 4
1112
1113 =item Uniform and safe metaclass composition
1114
1115 An excellent paper by the people who brought us the original Traits paper.
1116 This paper is on how Traits can be used to do safe metaclass composition,
1117 and offers an excellent introduction section which delves into the topic of
1118 metaclass compatibility.
1119
1120 L<http://www.iam.unibe.ch/~scg/Archive/Papers/Duca05ySafeMetaclassTrait.pdf>
1121
1122 =item Safe Metaclass Programming
1123
1124 This paper seems to precede the above paper, and propose a mix-in based
1125 approach as opposed to the Traits based approach. Both papers have similar
1126 information on the metaclass compatibility problem space.
1127
1128 L<http://citeseer.ist.psu.edu/37617.html>
1129
1130 =back
1131
1132 =head2 Prior Art
1133
1134 =over 4
1135
1136 =item The Perl 6 MetaModel work in the Pugs project
1137
1138 =over 4
1139
1140 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel>
1141
1142 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-ObjectSpace>
1143
1144 =back
1145
1146 =back
1147
1148 =head2 Articles
1149
1150 =over 4
1151
1152 =item CPAN Module Review of Class::MOP
1153
1154 L<http://www.oreillynet.com/onlamp/blog/2006/06/cpan_module_review_classmop.html>
1155
1156 =back
1157
1158 =head1 SIMILAR MODULES
1159
1160 As I have said above, this module is a class-builder-builder, so it is
1161 not the same thing as modules like L<Class::Accessor> and
1162 L<Class::MethodMaker>. That being said there are very few modules on CPAN
1163 with similar goals to this module. The one I have found which is most
1164 like this module is L<Class::Meta>, although it's philosophy and the MOP it
1165 creates are very different from this modules.
1166
1167 =head1 BUGS
1168
1169 All complex software has bugs lurking in it, and this module is no
1170 exception. If you find a bug please either email me, or add the bug
1171 to cpan-RT.
1172
1173 =head1 ACKNOWLEDGEMENTS
1174
1175 =over 4
1176
1177 =item Rob Kinyon
1178
1179 Thanks to Rob for actually getting the development of this module kick-started.
1180
1181 =back
1182
1183 =head1 AUTHORS
1184
1185 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1186
1187 B<with contributions from:>
1188
1189 Brandon (blblack) Black
1190
1191 Guillermo (groditi) Roditi
1192
1193 Matt (mst) Trout
1194
1195 Rob (robkinyon) Kinyon
1196
1197 Yuval (nothingmuch) Kogman
1198
1199 Scott (konobi) McWhirter
1200
1201 =head1 COPYRIGHT AND LICENSE
1202
1203 Copyright 2006-2008 by Infinity Interactive, Inc.
1204
1205 L<http://www.iinteractive.com>
1206
1207 This library is free software; you can redistribute it and/or modify
1208 it under the same terms as Perl itself.
1209
1210 =cut