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