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