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