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