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