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