Part 1 of the great clone plan.
[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_attribute(
492     Class::MOP::Attribute->new('original_method' => (
493         reader   => { 'original_method'      => \&Class::MOP::Method::original_method },
494         writer   => { '_set_original_method' => \&Class::MOP::Method::_set_original_method },
495     ))
496 );
497
498 Class::MOP::Method->meta->add_method('clone' => sub {
499     my $self  = shift;
500     my $clone = $self->meta->clone_object($self, @_);
501     $clone->_set_original_method($self);
502     return $clone;
503 });
504
505 ## --------------------------------------------------------
506 ## Class::MOP::Method::Wrapped
507
508 # NOTE:
509 # the way this item is initialized, this
510 # really does not follow the standard
511 # practices of attributes, but we put
512 # it here for completeness
513 Class::MOP::Method::Wrapped->meta->add_attribute(
514     Class::MOP::Attribute->new('modifier_table')
515 );
516
517 ## --------------------------------------------------------
518 ## Class::MOP::Method::Generated
519
520 Class::MOP::Method::Generated->meta->add_attribute(
521     Class::MOP::Attribute->new('is_inline' => (
522         reader   => { 'is_inline' => \&Class::MOP::Method::Generated::is_inline },
523         default  => 0, 
524     ))
525 );
526
527 ## --------------------------------------------------------
528 ## Class::MOP::Method::Accessor
529
530 Class::MOP::Method::Accessor->meta->add_attribute(
531     Class::MOP::Attribute->new('attribute' => (
532         reader   => {
533             'associated_attribute' => \&Class::MOP::Method::Accessor::associated_attribute
534         },
535     ))
536 );
537
538 Class::MOP::Method::Accessor->meta->add_attribute(
539     Class::MOP::Attribute->new('accessor_type' => (
540         reader   => { 'accessor_type' => \&Class::MOP::Method::Accessor::accessor_type },
541     ))
542 );
543
544 ## --------------------------------------------------------
545 ## Class::MOP::Method::Constructor
546
547 Class::MOP::Method::Constructor->meta->add_attribute(
548     Class::MOP::Attribute->new('options' => (
549         reader   => {
550             'options' => \&Class::MOP::Method::Constructor::options
551         },
552         default  => sub { +{} }
553     ))
554 );
555
556 Class::MOP::Method::Constructor->meta->add_attribute(
557     Class::MOP::Attribute->new('associated_metaclass' => (
558         init_arg => "metaclass", # FIXME alias and rename
559         reader   => {
560             'associated_metaclass' => \&Class::MOP::Method::Constructor::associated_metaclass
561         },
562     ))
563 );
564
565 ## --------------------------------------------------------
566 ## Class::MOP::Instance
567
568 # NOTE:
569 # these don't yet do much of anything, but are just
570 # included for completeness
571
572 Class::MOP::Instance->meta->add_attribute(
573     Class::MOP::Attribute->new('associated_metaclass',
574         reader   => { associated_metaclass => \&Class::MOP::Instance::associated_metaclass },
575     ),
576 );
577
578 Class::MOP::Instance->meta->add_attribute(
579     Class::MOP::Attribute->new('_class_name',
580         init_arg => undef,
581         reader   => { _class_name => \&Class::MOP::Instance::_class_name },
582         #lazy     => 1, # not yet supported by Class::MOP but out our version does it anyway
583         #default  => sub { $_[0]->associated_metaclass->name },
584     ),
585 );
586
587 Class::MOP::Instance->meta->add_attribute(
588     Class::MOP::Attribute->new('attributes',
589         reader   => { attributes => \&Class::MOP::Instance::get_all_attributes },
590     ),
591 );
592
593 Class::MOP::Instance->meta->add_attribute(
594     Class::MOP::Attribute->new('slots',
595         reader   => { slots => \&Class::MOP::Instance::slots },
596     ),
597 );
598
599 Class::MOP::Instance->meta->add_attribute(
600     Class::MOP::Attribute->new('slot_hash',
601         reader   => { slot_hash => \&Class::MOP::Instance::slot_hash },
602     ),
603 );
604
605
606 # we need the meta instance of the meta instance to be created now, in order
607 # for the constructor to be able to use it
608 Class::MOP::Instance->meta->get_meta_instance;
609
610 # pretend the add_method never happenned. it hasn't yet affected anything
611 undef Class::MOP::Instance->meta->{_package_cache_flag};
612
613 ## --------------------------------------------------------
614 ## Now close all the Class::MOP::* classes
615
616 # NOTE:
617 # we don't need to inline the
618 # constructors or the accessors
619 # this only lengthens the compile
620 # time of the MOP, and gives us
621 # no actual benefits.
622
623 $_->meta->make_immutable(
624     inline_constructor  => 1,
625     replace_constructor => 1,
626     constructor_name    => "_new",
627     inline_accessors => 0,
628 ) for qw/
629     Class::MOP::Package
630     Class::MOP::Module
631     Class::MOP::Class
632
633     Class::MOP::Attribute
634     Class::MOP::Method
635     Class::MOP::Instance
636
637     Class::MOP::Object
638
639     Class::MOP::Method::Generated
640
641     Class::MOP::Method::Accessor
642     Class::MOP::Method::Constructor
643     Class::MOP::Method::Wrapped
644 /;
645
646 1;
647
648 __END__
649
650 =pod
651
652 =head1 NAME
653
654 Class::MOP - A Meta Object Protocol for Perl 5
655
656 =head1 DESCRIPTON
657
658 This module is a fully functioning meta object protocol for the
659 Perl 5 object system. It makes no attempt to change the behavior or
660 characteristics of the Perl 5 object system, only to create a
661 protocol for its manipulation and introspection.
662
663 That said, it does attempt to create the tools for building a rich
664 set of extensions to the Perl 5 object system. Every attempt has been
665 made for these tools to keep to the spirit of the Perl 5 object
666 system that we all know and love.
667
668 This documentation is admittedly sparse on details, as time permits
669 I will try to improve them. For now, I suggest looking at the items
670 listed in the L<SEE ALSO> section for more information. In particular
671 the book "The Art of the Meta Object Protocol" was very influential
672 in the development of this system.
673
674 =head2 What is a Meta Object Protocol?
675
676 A meta object protocol is an API to an object system.
677
678 To be more specific, it is a set of abstractions of the components of
679 an object system (typically things like; classes, object, methods,
680 object attributes, etc.). These abstractions can then be used to both
681 inspect and manipulate the object system which they describe.
682
683 It can be said that there are two MOPs for any object system; the
684 implicit MOP, and the explicit MOP. The implicit MOP handles things
685 like method dispatch or inheritance, which happen automatically as
686 part of how the object system works. The explicit MOP typically
687 handles the introspection/reflection features of the object system.
688 All object systems have implicit MOPs, without one, they would not
689 work. Explict MOPs however as less common, and depending on the
690 language can vary from restrictive (Reflection in Java or C#) to
691 wide open (CLOS is a perfect example).
692
693 =head2 Yet Another Class Builder!! Why?
694
695 This is B<not> a class builder so much as it is a I<class builder
696 B<builder>>. My intent is that an end user does not use this module
697 directly, but instead this module is used by module authors to
698 build extensions and features onto the Perl 5 object system.
699
700 =head2 Who is this module for?
701
702 This module is specifically for anyone who has ever created or
703 wanted to create a module for the Class:: namespace. The tools which
704 this module will provide will hopefully make it easier to do more
705 complex things with Perl 5 classes by removing such barriers as
706 the need to hack the symbol tables, or understand the fine details
707 of method dispatch.
708
709 =head2 What changes do I have to make to use this module?
710
711 This module was designed to be as unintrusive as possible. Many of
712 its features are accessible without B<any> change to your existsing
713 code at all. It is meant to be a compliment to your existing code and
714 not an intrusion on your code base. Unlike many other B<Class::>
715 modules, this module B<does not> require you subclass it, or even that
716 you C<use> it in within your module's package.
717
718 The only features which requires additions to your code are the
719 attribute handling and instance construction features, and these are
720 both completely optional features. The only reason for this is because
721 Perl 5's object system does not actually have these features built
722 in. More information about this feature can be found below.
723
724 =head2 A Note about Performance?
725
726 It is a common misconception that explict MOPs are performance drains.
727 But this is not a universal truth at all, it is an side-effect of
728 specific implementations. For instance, using Java reflection is much
729 slower because the JVM cannot take advantage of any compiler
730 optimizations, and the JVM has to deal with much more runtime type
731 information as well. Reflection in C# is marginally better as it was
732 designed into the language and runtime (the CLR). In contrast, CLOS
733 (the Common Lisp Object System) was built to support an explicit MOP,
734 and so performance is tuned for it.
735
736 This library in particular does it's absolute best to avoid putting
737 B<any> drain at all upon your code's performance. In fact, by itself
738 it does nothing to affect your existing code. So you only pay for
739 what you actually use.
740
741 =head2 About Metaclass compatibility
742
743 This module makes sure that all metaclasses created are both upwards
744 and downwards compatible. The topic of metaclass compatibility is
745 highly esoteric and is something only encountered when doing deep and
746 involved metaclass hacking. There are two basic kinds of metaclass
747 incompatibility; upwards and downwards.
748
749 Upwards metaclass compatibility means that the metaclass of a
750 given class is either the same as (or a subclass of) all of the
751 class's ancestors.
752
753 Downward metaclass compatibility means that the metaclasses of a
754 given class's anscestors are all either the same as (or a subclass
755 of) that metaclass.
756
757 Here is a diagram showing a set of two classes (C<A> and C<B>) and
758 two metaclasses (C<Meta::A> and C<Meta::B>) which have correct
759 metaclass compatibility both upwards and downwards.
760
761     +---------+     +---------+
762     | Meta::A |<----| Meta::B |      <....... (instance of  )
763     +---------+     +---------+      <------- (inherits from)
764          ^               ^
765          :               :
766     +---------+     +---------+
767     |    A    |<----|    B    |
768     +---------+     +---------+
769
770 As I said this is a highly esoteric topic and one you will only run
771 into if you do a lot of subclassing of B<Class::MOP::Class>. If you
772 are interested in why this is an issue see the paper
773 I<Uniform and safe metaclass composition> linked to in the
774 L<SEE ALSO> section of this document.
775
776 =head2 Using custom metaclasses
777
778 Always use the metaclass pragma when using a custom metaclass, this
779 will ensure the proper initialization order and not accidentely
780 create an incorrect type of metaclass for you. This is a very rare
781 problem, and one which can only occur if you are doing deep metaclass
782 programming. So in other words, don't worry about it.
783
784 =head1 PROTOCOLS
785
786 The protocol is divided into 4 main sub-protocols:
787
788 =over 4
789
790 =item The Class protocol
791
792 This provides a means of manipulating and introspecting a Perl 5
793 class. It handles all of symbol table hacking for you, and provides
794 a rich set of methods that go beyond simple package introspection.
795
796 See L<Class::MOP::Class> for more details.
797
798 =item The Attribute protocol
799
800 This provides a consistent represenation for an attribute of a
801 Perl 5 class. Since there are so many ways to create and handle
802 attributes in Perl 5 OO, this attempts to provide as much of a
803 unified approach as possible, while giving the freedom and
804 flexibility to subclass for specialization.
805
806 See L<Class::MOP::Attribute> for more details.
807
808 =item The Method protocol
809
810 This provides a means of manipulating and introspecting methods in
811 the Perl 5 object system. As with attributes, there are many ways to
812 approach this topic, so we try to keep it pretty basic, while still
813 making it possible to extend the system in many ways.
814
815 See L<Class::MOP::Method> for more details.
816
817 =item The Instance protocol
818
819 This provides a layer of abstraction for creating object instances. 
820 Since the other layers use this protocol, it is relatively easy to 
821 change the type of your instances from the default HASH ref to other
822 types of references. Several examples are provided in the F<examples/> 
823 directory included in this distribution.
824
825 See L<Class::MOP::Instance> for more details.
826
827 =back
828
829 =head1 FUNCTIONS
830
831 =head2 Constants
832
833 =over 4
834
835 =item I<IS_RUNNING_ON_5_10>
836
837 We set this constant depending on what version perl we are on, this 
838 allows us to take advantage of new 5.10 features and stay backwards 
839 compat.
840
841 =item I<HAVE_ISAREV>
842
843 Whether or not C<mro> provides C<get_isarev>, a much faster way to get all the
844 subclasses of a certain class.
845
846 =back
847
848 =head2 Utility functions
849
850 Note that these are all called as B<functions, not methods>.
851
852 =over 4
853
854 =item B<load_class ($class_name)>
855
856 This will load a given C<$class_name> and if it does not have an
857 already initialized metaclass, then it will intialize one for it.
858 This function can be used in place of tricks like 
859 C<eval "use $module"> or using C<require>.
860
861 =item B<is_class_loaded ($class_name)>
862
863 This will return a boolean depending on if the C<$class_name> has
864 been loaded.
865
866 NOTE: This does a basic check of the symbol table to try and
867 determine as best it can if the C<$class_name> is loaded, it
868 is probably correct about 99% of the time.
869
870 =item B<check_package_cache_flag ($pkg)>
871
872 B<NOTE: DO NOT USE THIS FUNCTION, IT IS FOR INTERNAL USE ONLY!>
873
874 This will return an integer that is managed by C<Class::MOP::Class>
875 to determine if a module's symbol table has been altered. 
876
877 In Perl 5.10 or greater, this flag is package specific. However in 
878 versions prior to 5.10, this will use the C<PL_sub_generation> variable
879 which is not package specific. 
880
881 =item B<get_code_info ($code)>
882
883 B<NOTE: DO NOT USE THIS FUNCTION, IT IS FOR INTERNAL USE ONLY!>
884
885 This function returns two values, the name of the package the C<$code> 
886 is from and the name of the C<$code> itself. This is used by several 
887 elements of the MOP to detemine where a given C<$code> reference is from.
888
889 =item B<subname ($name, $code)>
890
891 B<NOTE: DO NOT USE THIS FUNCTION, IT IS FOR INTERNAL USE ONLY!>
892
893 If possible, we will load the L<Sub::Name> module and this will function 
894 as C<Sub::Name::subname> does, otherwise it will just return the C<$code>
895 argument.
896
897 =item B<in_global_destruction>
898
899 B<NOTE: DO NOT USE THIS FUNCTION, IT IS FOR INTERNAL USE ONLY!>
900
901 If L<Devel::GlobalDestruction> is available, this returns true under global
902 destruction.
903
904 Otherwise it's a constant returning false.
905
906 =back
907
908 =head2 Metaclass cache functions
909
910 Class::MOP holds a cache of metaclasses, the following are functions
911 (B<not methods>) which can be used to access that cache. It is not
912 recommended that you mess with this, bad things could happen. But if
913 you are brave and willing to risk it, go for it.
914
915 =over 4
916
917 =item B<get_all_metaclasses>
918
919 This will return an hash of all the metaclass instances that have
920 been cached by B<Class::MOP::Class> keyed by the package name.
921
922 =item B<get_all_metaclass_instances>
923
924 This will return an array of all the metaclass instances that have
925 been cached by B<Class::MOP::Class>.
926
927 =item B<get_all_metaclass_names>
928
929 This will return an array of all the metaclass names that have
930 been cached by B<Class::MOP::Class>.
931
932 =item B<get_metaclass_by_name ($name)>
933
934 This will return a cached B<Class::MOP::Class> instance of nothing
935 if no metaclass exist by that C<$name>.
936
937 =item B<store_metaclass_by_name ($name, $meta)>
938
939 This will store a metaclass in the cache at the supplied C<$key>.
940
941 =item B<weaken_metaclass ($name)>
942
943 In rare cases it is desireable to store a weakened reference in 
944 the metaclass cache. This function will weaken the reference to 
945 the metaclass stored in C<$name>.
946
947 =item B<does_metaclass_exist ($name)>
948
949 This will return true of there exists a metaclass stored in the 
950 C<$name> key and return false otherwise.
951
952 =item B<remove_metaclass_by_name ($name)>
953
954 This will remove a the metaclass stored in the C<$name> key.
955
956 =back
957
958 =head1 SEE ALSO
959
960 =head2 Books
961
962 There are very few books out on Meta Object Protocols and Metaclasses
963 because it is such an esoteric topic. The following books are really
964 the only ones I have found. If you know of any more, B<I<please>>
965 email me and let me know, I would love to hear about them.
966
967 =over 4
968
969 =item "The Art of the Meta Object Protocol"
970
971 =item "Advances in Object-Oriented Metalevel Architecture and Reflection"
972
973 =item "Putting MetaClasses to Work"
974
975 =item "Smalltalk: The Language"
976
977 =back
978
979 =head2 Papers
980
981 =over 4
982
983 =item Uniform and safe metaclass composition
984
985 An excellent paper by the people who brought us the original Traits paper.
986 This paper is on how Traits can be used to do safe metaclass composition,
987 and offers an excellent introduction section which delves into the topic of
988 metaclass compatibility.
989
990 L<http://www.iam.unibe.ch/~scg/Archive/Papers/Duca05ySafeMetaclassTrait.pdf>
991
992 =item Safe Metaclass Programming
993
994 This paper seems to precede the above paper, and propose a mix-in based
995 approach as opposed to the Traits based approach. Both papers have similar
996 information on the metaclass compatibility problem space.
997
998 L<http://citeseer.ist.psu.edu/37617.html>
999
1000 =back
1001
1002 =head2 Prior Art
1003
1004 =over 4
1005
1006 =item The Perl 6 MetaModel work in the Pugs project
1007
1008 =over 4
1009
1010 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel>
1011
1012 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-ObjectSpace>
1013
1014 =back
1015
1016 =back
1017
1018 =head2 Articles
1019
1020 =over 4
1021
1022 =item CPAN Module Review of Class::MOP
1023
1024 L<http://www.oreillynet.com/onlamp/blog/2006/06/cpan_module_review_classmop.html>
1025
1026 =back
1027
1028 =head1 SIMILAR MODULES
1029
1030 As I have said above, this module is a class-builder-builder, so it is
1031 not the same thing as modules like L<Class::Accessor> and
1032 L<Class::MethodMaker>. That being said there are very few modules on CPAN
1033 with similar goals to this module. The one I have found which is most
1034 like this module is L<Class::Meta>, although it's philosophy and the MOP it
1035 creates are very different from this modules.
1036
1037 =head1 BUGS
1038
1039 All complex software has bugs lurking in it, and this module is no
1040 exception. If you find a bug please either email me, or add the bug
1041 to cpan-RT.
1042
1043 =head1 ACKNOWLEDGEMENTS
1044
1045 =over 4
1046
1047 =item Rob Kinyon
1048
1049 Thanks to Rob for actually getting the development of this module kick-started.
1050
1051 =back
1052
1053 =head1 AUTHORS
1054
1055 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1056
1057 B<with contributions from:>
1058
1059 Brandon (blblack) Black
1060
1061 Guillermo (groditi) Roditi
1062
1063 Matt (mst) Trout
1064
1065 Rob (robkinyon) Kinyon
1066
1067 Yuval (nothingmuch) Kogman
1068
1069 Scott (konobi) McWhirter
1070
1071 =head1 COPYRIGHT AND LICENSE
1072
1073 Copyright 2006-2008 by Infinity Interactive, Inc.
1074
1075 L<http://www.iinteractive.com>
1076
1077 This library is free software; you can redistribute it and/or modify
1078 it under the same terms as Perl itself.
1079
1080 =cut