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