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