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