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