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