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