8 use Scalar::Util 'weaken';
10 use Class::MOP::Class;
11 use Class::MOP::Attribute;
12 use Class::MOP::Method;
14 use Class::MOP::Class::Immutable;
16 our $VERSION = '0.36';
17 our $AUTHORITY = 'cpan:STEVAN';
20 # Metaclasses are singletons, so we cache them here.
21 # there is no need to worry about destruction though
22 # because they should die only when the program dies.
23 # After all, do package definitions even get reaped?
26 # means of accessing all the metaclasses that have
27 # been initialized thus far (for mugwumps obj browser)
28 sub get_all_metaclasses { %METAS }
29 sub get_all_metaclass_instances { values %METAS }
30 sub get_all_metaclass_names { keys %METAS }
31 sub get_metaclass_by_name { $METAS{$_[0]} }
32 sub store_metaclass_by_name { $METAS{$_[0]} = $_[1] }
33 sub weaken_metaclass { weaken($METAS{$_[0]}) }
34 sub does_metaclass_exist { exists $METAS{$_[0]} && defined $METAS{$_[0]} }
35 sub remove_metaclass_by_name { $METAS{$_[0]} = undef }
38 # We only cache metaclasses, meaning instances of
39 # Class::MOP::Class. We do not cache instance of
40 # Class::MOP::Package or Class::MOP::Module. Mostly
41 # because I don't yet see a good reason to do so.
44 ## ----------------------------------------------------------------------------
45 ## Setting up our environment ...
46 ## ----------------------------------------------------------------------------
47 ## Class::MOP needs to have a few things in the global perl environment so
48 ## that it can operate effectively. Those things are done here.
49 ## ----------------------------------------------------------------------------
51 # ... nothing yet actually ;)
53 ## ----------------------------------------------------------------------------
55 ## ----------------------------------------------------------------------------
56 ## The code below here is to bootstrap our MOP with itself. This is also
57 ## sometimes called "tying the knot". By doing this, we make it much easier
58 ## to extend the MOP through subclassing and such since now you can use the
59 ## MOP itself to extend itself.
61 ## Yes, I know, thats weird and insane, but it's a good thing, trust me :)
62 ## ----------------------------------------------------------------------------
64 # We need to add in the meta-attributes here so that
65 # any subclass of Class::MOP::* will be able to
66 # inherit them using &construct_instance
68 ## --------------------------------------------------------
69 ## Class::MOP::Package
71 Class::MOP::Package->meta->add_attribute(
72 Class::MOP::Attribute->new('$:package' => (
74 # NOTE: we need to do this in order
75 # for the instance meta-object to
76 # not fall into meta-circular death
78 # we just alias the original method
79 # rather than re-produce it here
80 'name' => \&Class::MOP::Package::name
82 init_arg => ':package',
86 Class::MOP::Package->meta->add_attribute(
87 Class::MOP::Attribute->new('%:namespace' => (
90 # we just alias the original method
91 # rather than re-produce it here
92 'namespace' => \&Class::MOP::Package::namespace
95 # protect this from silliness
96 init_arg => '!............( DO NOT DO THIS )............!',
97 default => sub { \undef }
102 # use the metaclass to construct the meta-package
103 # which is a superclass of the metaclass itself :P
104 Class::MOP::Package->meta->add_method('initialize' => sub {
106 my $package_name = shift;
107 $class->meta->new_object(':package' => $package_name, @_);
110 ## --------------------------------------------------------
111 ## Class::MOP::Module
114 # yeah this is kind of stretching things a bit,
115 # but truthfully the version should be an attribute
116 # of the Module, the weirdness comes from having to
117 # stick to Perl 5 convention and store it in the
118 # $VERSION package variable. Basically if you just
119 # squint at it, it will look how you want it to look.
120 # Either as a package variable, or as a attribute of
121 # the metaclass, isn't abstraction great :)
123 Class::MOP::Module->meta->add_attribute(
124 Class::MOP::Attribute->new('$:version' => (
127 # we just alias the original method
128 # rather than re-produce it here
129 'version' => \&Class::MOP::Module::version
132 # protect this from silliness
133 init_arg => '!............( DO NOT DO THIS )............!',
134 default => sub { \undef }
139 # By following the same conventions as version here,
140 # we are opening up the possibility that people can
141 # use the $AUTHORITY in non-Class::MOP modules as
144 Class::MOP::Module->meta->add_attribute(
145 Class::MOP::Attribute->new('$:authority' => (
148 # we just alias the original method
149 # rather than re-produce it here
150 'authority' => \&Class::MOP::Module::authority
153 # protect this from silliness
154 init_arg => '!............( DO NOT DO THIS )............!',
155 default => sub { \undef }
159 ## --------------------------------------------------------
162 Class::MOP::Class->meta->add_attribute(
163 Class::MOP::Attribute->new('%:attributes' => (
165 # NOTE: we need to do this in order
166 # for the instance meta-object to
167 # not fall into meta-circular death
169 # we just alias the original method
170 # rather than re-produce it here
171 'get_attribute_map' => \&Class::MOP::Class::get_attribute_map
173 init_arg => ':attributes',
174 default => sub { {} }
178 Class::MOP::Class->meta->add_attribute(
179 Class::MOP::Attribute->new('%:methods' => (
182 # we just alias the original method
183 # rather than re-produce it here
184 'get_method_map' => \&Class::MOP::Class::get_method_map
186 default => sub { {} }
190 Class::MOP::Class->meta->add_attribute(
191 Class::MOP::Attribute->new('$:attribute_metaclass' => (
194 # we just alias the original method
195 # rather than re-produce it here
196 'attribute_metaclass' => \&Class::MOP::Class::attribute_metaclass
198 init_arg => ':attribute_metaclass',
199 default => 'Class::MOP::Attribute',
203 Class::MOP::Class->meta->add_attribute(
204 Class::MOP::Attribute->new('$:method_metaclass' => (
207 # we just alias the original method
208 # rather than re-produce it here
209 'method_metaclass' => \&Class::MOP::Class::method_metaclass
211 init_arg => ':method_metaclass',
212 default => 'Class::MOP::Method',
216 Class::MOP::Class->meta->add_attribute(
217 Class::MOP::Attribute->new('$:instance_metaclass' => (
219 # NOTE: we need to do this in order
220 # for the instance meta-object to
221 # not fall into meta-circular death
223 # we just alias the original method
224 # rather than re-produce it here
225 'instance_metaclass' => \&Class::MOP::Class::instance_metaclass
227 init_arg => ':instance_metaclass',
228 default => 'Class::MOP::Instance',
233 # we don't actually need to tie the knot with
234 # Class::MOP::Class here, it is actually handled
235 # within Class::MOP::Class itself in the
236 # construct_class_instance method.
238 ## --------------------------------------------------------
239 ## Class::MOP::Attribute
241 Class::MOP::Attribute->meta->add_attribute(
242 Class::MOP::Attribute->new('name' => (
244 # NOTE: we need to do this in order
245 # for the instance meta-object to
246 # not fall into meta-circular death
248 # we just alias the original method
249 # rather than re-produce it here
250 'name' => \&Class::MOP::Attribute::name
255 Class::MOP::Attribute->meta->add_attribute(
256 Class::MOP::Attribute->new('associated_class' => (
258 # NOTE: we need to do this in order
259 # for the instance meta-object to
260 # not fall into meta-circular death
262 # we just alias the original method
263 # rather than re-produce it here
264 'associated_class' => \&Class::MOP::Attribute::associated_class
269 Class::MOP::Attribute->meta->add_attribute(
270 Class::MOP::Attribute->new('accessor' => (
271 reader => { 'accessor' => \&Class::MOP::Attribute::accessor },
272 predicate => { 'has_accessor' => \&Class::MOP::Attribute::has_accessor },
276 Class::MOP::Attribute->meta->add_attribute(
277 Class::MOP::Attribute->new('reader' => (
278 reader => { 'reader' => \&Class::MOP::Attribute::reader },
279 predicate => { 'has_reader' => \&Class::MOP::Attribute::has_reader },
283 Class::MOP::Attribute->meta->add_attribute(
284 Class::MOP::Attribute->new('writer' => (
285 reader => { 'writer' => \&Class::MOP::Attribute::writer },
286 predicate => { 'has_writer' => \&Class::MOP::Attribute::has_writer },
290 Class::MOP::Attribute->meta->add_attribute(
291 Class::MOP::Attribute->new('predicate' => (
292 reader => { 'predicate' => \&Class::MOP::Attribute::predicate },
293 predicate => { 'has_predicate' => \&Class::MOP::Attribute::has_predicate },
297 Class::MOP::Attribute->meta->add_attribute(
298 Class::MOP::Attribute->new('clearer' => (
299 reader => { 'clearer' => \&Class::MOP::Attribute::clearer },
300 predicate => { 'has_clearer' => \&Class::MOP::Attribute::has_clearer },
304 Class::MOP::Attribute->meta->add_attribute(
305 Class::MOP::Attribute->new('init_arg' => (
306 reader => { 'init_arg' => \&Class::MOP::Attribute::init_arg },
307 predicate => { 'has_init_arg' => \&Class::MOP::Attribute::has_init_arg },
311 Class::MOP::Attribute->meta->add_attribute(
312 Class::MOP::Attribute->new('default' => (
313 # default has a custom 'reader' method ...
314 predicate => { 'has_default' => \&Class::MOP::Attribute::has_default },
318 Class::MOP::Attribute->meta->add_attribute(
319 Class::MOP::Attribute->new('associated_methods' => (
320 reader => { 'associated_methods' => \&Class::MOP::Attribute::associated_methods },
321 default => sub { [] }
325 # NOTE: (meta-circularity)
326 # This should be one of the last things done
327 # it will "tie the knot" with Class::MOP::Attribute
328 # so that it uses the attributes meta-objects
329 # to construct itself.
330 Class::MOP::Attribute->meta->add_method('new' => sub {
335 (defined $name && $name)
336 || confess "You must provide a name for the attribute";
337 $options{init_arg} = $name
338 if not exists $options{init_arg};
340 (Class::MOP::Attribute::is_default_a_coderef(\%options))
341 || confess("References are not allowed as default values, you must ".
342 "wrap then in a CODE reference (ex: sub { [] } and not [])")
343 if exists $options{default} && ref $options{default};
345 # return the new object
346 $class->meta->new_object(name => $name, %options);
349 Class::MOP::Attribute->meta->add_method('clone' => sub {
351 $self->meta->clone_object($self, @_);
354 ## --------------------------------------------------------
355 ## Class::MOP::Method
357 Class::MOP::Method->meta->add_attribute(
358 Class::MOP::Attribute->new('body' => (
359 reader => { 'body' => \&Class::MOP::Method::body },
363 ## --------------------------------------------------------
364 ## Class::MOP::Method::Wrapped
367 # the way this item is initialized, this
368 # really does not follow the standard
369 # practices of attributes, but we put
370 # it here for completeness
371 Class::MOP::Method::Wrapped->meta->add_attribute(
372 Class::MOP::Attribute->new('modifier_table')
375 ## --------------------------------------------------------
376 ## Class::MOP::Method::Accessor
378 Class::MOP::Method::Accessor->meta->add_attribute(
379 Class::MOP::Attribute->new('attribute' => (
381 'associated_attribute' => \&Class::MOP::Method::Accessor::associated_attribute
386 Class::MOP::Method::Accessor->meta->add_attribute(
387 Class::MOP::Attribute->new('accessor_type' => (
388 reader => { 'accessor_type' => \&Class::MOP::Method::Accessor::accessor_type },
392 Class::MOP::Method::Accessor->meta->add_attribute(
393 Class::MOP::Attribute->new('is_inline' => (
394 reader => { 'is_inline' => \&Class::MOP::Method::Accessor::is_inline },
398 ## --------------------------------------------------------
399 ## Class::MOP::Method::Constructor
401 Class::MOP::Method::Constructor->meta->add_attribute(
402 Class::MOP::Attribute->new('options' => (
404 'options' => \&Class::MOP::Method::Constructor::options
409 Class::MOP::Method::Constructor->meta->add_attribute(
410 Class::MOP::Attribute->new('meta_instance' => (
412 'meta_instance' => \&Class::MOP::Method::Constructor::meta_instance
417 Class::MOP::Method::Constructor->meta->add_attribute(
418 Class::MOP::Attribute->new('attributes' => (
420 'attributes' => \&Class::MOP::Method::Constructor::attributes
425 ## --------------------------------------------------------
426 ## Class::MOP::Instance
429 # these don't yet do much of anything, but are just
430 # included for completeness
432 Class::MOP::Instance->meta->add_attribute(
433 Class::MOP::Attribute->new('meta')
436 Class::MOP::Instance->meta->add_attribute(
437 Class::MOP::Attribute->new('slots')
440 ## --------------------------------------------------------
441 ## Now close all the Class::MOP::* classes
444 # we don't need to inline the
445 # constructors or the accessors
446 # this only lengthens the compile
447 # time of the MOP, and gives us
448 # no actual benefits.
450 $_->meta->make_immutable(
451 inline_constructor => 0,
452 inline_accessors => 0,
458 Class::MOP::Attribute
464 Class::MOP::Method::Accessor
465 Class::MOP::Method::Constructor
466 Class::MOP::Method::Wrapped
477 Class::MOP - A Meta Object Protocol for Perl 5
481 # ... This will come later, for now see
482 # the other SYNOPSIS for more information
486 This module is an attempt to create a meta object protocol for the
487 Perl 5 object system. It makes no attempt to change the behavior or
488 characteristics of the Perl 5 object system, only to create a
489 protocol for its manipulation and introspection.
491 That said, it does attempt to create the tools for building a rich
492 set of extensions to the Perl 5 object system. Every attempt has been
493 made for these tools to keep to the spirit of the Perl 5 object
494 system that we all know and love.
496 This documentation is admittedly sparse on details, as time permits
497 I will try to improve them. For now, I suggest looking at the items
498 listed in the L<SEE ALSO> section for more information. In particular
499 the book "The Art of the Meta Object Protocol" was very influential
500 in the development of this system.
502 =head2 What is a Meta Object Protocol?
504 A meta object protocol is an API to an object system.
506 To be more specific, it is a set of abstractions of the components of
507 an object system (typically things like; classes, object, methods,
508 object attributes, etc.). These abstractions can then be used to both
509 inspect and manipulate the object system which they describe.
511 It can be said that there are two MOPs for any object system; the
512 implicit MOP, and the explicit MOP. The implicit MOP handles things
513 like method dispatch or inheritance, which happen automatically as
514 part of how the object system works. The explicit MOP typically
515 handles the introspection/reflection features of the object system.
516 All object systems have implicit MOPs, without one, they would not
517 work. Explict MOPs however as less common, and depending on the
518 language can vary from restrictive (Reflection in Java or C#) to
519 wide open (CLOS is a perfect example).
521 =head2 Yet Another Class Builder!! Why?
523 This is B<not> a class builder so much as it is a I<class builder
524 B<builder>>. My intent is that an end user does not use this module
525 directly, but instead this module is used by module authors to
526 build extensions and features onto the Perl 5 object system.
528 =head2 Who is this module for?
530 This module is specifically for anyone who has ever created or
531 wanted to create a module for the Class:: namespace. The tools which
532 this module will provide will hopefully make it easier to do more
533 complex things with Perl 5 classes by removing such barriers as
534 the need to hack the symbol tables, or understand the fine details
537 =head2 What changes do I have to make to use this module?
539 This module was designed to be as unintrusive as possible. Many of
540 its features are accessible without B<any> change to your existsing
541 code at all. It is meant to be a compliment to your existing code and
542 not an intrusion on your code base. Unlike many other B<Class::>
543 modules, this module B<does not> require you subclass it, or even that
544 you C<use> it in within your module's package.
546 The only features which requires additions to your code are the
547 attribute handling and instance construction features, and these are
548 both completely optional features. The only reason for this is because
549 Perl 5's object system does not actually have these features built
550 in. More information about this feature can be found below.
552 =head2 A Note about Performance?
554 It is a common misconception that explict MOPs are performance drains.
555 But this is not a universal truth at all, it is an side-effect of
556 specific implementations. For instance, using Java reflection is much
557 slower because the JVM cannot take advantage of any compiler
558 optimizations, and the JVM has to deal with much more runtime type
559 information as well. Reflection in C# is marginally better as it was
560 designed into the language and runtime (the CLR). In contrast, CLOS
561 (the Common Lisp Object System) was built to support an explicit MOP,
562 and so performance is tuned for it.
564 This library in particular does it's absolute best to avoid putting
565 B<any> drain at all upon your code's performance. In fact, by itself
566 it does nothing to affect your existing code. So you only pay for
567 what you actually use.
569 =head2 About Metaclass compatibility
571 This module makes sure that all metaclasses created are both upwards
572 and downwards compatible. The topic of metaclass compatibility is
573 highly esoteric and is something only encountered when doing deep and
574 involved metaclass hacking. There are two basic kinds of metaclass
575 incompatibility; upwards and downwards.
577 Upwards metaclass compatibility means that the metaclass of a
578 given class is either the same as (or a subclass of) all of the
581 Downward metaclass compatibility means that the metaclasses of a
582 given class's anscestors are all either the same as (or a subclass
585 Here is a diagram showing a set of two classes (C<A> and C<B>) and
586 two metaclasses (C<Meta::A> and C<Meta::B>) which have correct
587 metaclass compatibility both upwards and downwards.
589 +---------+ +---------+
590 | Meta::A |<----| Meta::B | <....... (instance of )
591 +---------+ +---------+ <------- (inherits from)
594 +---------+ +---------+
596 +---------+ +---------+
598 As I said this is a highly esoteric topic and one you will only run
599 into if you do a lot of subclassing of B<Class::MOP::Class>. If you
600 are interested in why this is an issue see the paper
601 I<Uniform and safe metaclass composition> linked to in the
602 L<SEE ALSO> section of this document.
604 =head2 Using custom metaclasses
606 Always use the metaclass pragma when using a custom metaclass, this
607 will ensure the proper initialization order and not accidentely
608 create an incorrect type of metaclass for you. This is a very rare
609 problem, and one which can only occur if you are doing deep metaclass
610 programming. So in other words, don't worry about it.
614 The protocol is divided into 3 main sub-protocols:
618 =item The Class protocol
620 This provides a means of manipulating and introspecting a Perl 5
621 class. It handles all of symbol table hacking for you, and provides
622 a rich set of methods that go beyond simple package introspection.
624 See L<Class::MOP::Class> for more details.
626 =item The Attribute protocol
628 This provides a consistent represenation for an attribute of a
629 Perl 5 class. Since there are so many ways to create and handle
630 atttributes in Perl 5 OO, this attempts to provide as much of a
631 unified approach as possible, while giving the freedom and
632 flexibility to subclass for specialization.
634 See L<Class::MOP::Attribute> for more details.
636 =item The Method protocol
638 This provides a means of manipulating and introspecting methods in
639 the Perl 5 object system. As with attributes, there are many ways to
640 approach this topic, so we try to keep it pretty basic, while still
641 making it possible to extend the system in many ways.
643 See L<Class::MOP::Method> for more details.
649 Class::MOP holds a cache of metaclasses, the following are functions
650 (B<not methods>) which can be used to access that cache. It is not
651 recommended that you mess with this, bad things could happen. But if
652 you are brave and willing to risk it, go for it.
656 =item B<get_all_metaclasses>
658 This will return an hash of all the metaclass instances that have
659 been cached by B<Class::MOP::Class> keyed by the package name.
661 =item B<get_all_metaclass_instances>
663 This will return an array of all the metaclass instances that have
664 been cached by B<Class::MOP::Class>.
666 =item B<get_all_metaclass_names>
668 This will return an array of all the metaclass names that have
669 been cached by B<Class::MOP::Class>.
671 =item B<get_metaclass_by_name ($name)>
673 =item B<store_metaclass_by_name ($name, $meta)>
675 =item B<weaken_metaclass ($name)>
677 =item B<does_metaclass_exist ($name)>
679 =item B<remove_metaclass_by_name ($name)>
687 There are very few books out on Meta Object Protocols and Metaclasses
688 because it is such an esoteric topic. The following books are really
689 the only ones I have found. If you know of any more, B<I<please>>
690 email me and let me know, I would love to hear about them.
694 =item "The Art of the Meta Object Protocol"
696 =item "Advances in Object-Oriented Metalevel Architecture and Reflection"
698 =item "Putting MetaClasses to Work"
700 =item "Smalltalk: The Language"
708 =item Uniform and safe metaclass composition
710 An excellent paper by the people who brought us the original Traits paper.
711 This paper is on how Traits can be used to do safe metaclass composition,
712 and offers an excellent introduction section which delves into the topic of
713 metaclass compatibility.
715 L<http://www.iam.unibe.ch/~scg/Archive/Papers/Duca05ySafeMetaclassTrait.pdf>
717 =item Safe Metaclass Programming
719 This paper seems to precede the above paper, and propose a mix-in based
720 approach as opposed to the Traits based approach. Both papers have similar
721 information on the metaclass compatibility problem space.
723 L<http://citeseer.ist.psu.edu/37617.html>
731 =item The Perl 6 MetaModel work in the Pugs project
735 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel>
737 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-ObjectSpace>
747 =item CPAN Module Review of Class::MOP
749 L<http://www.oreillynet.com/onlamp/blog/2006/06/cpan_module_review_classmop.html>
753 =head1 SIMILAR MODULES
755 As I have said above, this module is a class-builder-builder, so it is
756 not the same thing as modules like L<Class::Accessor> and
757 L<Class::MethodMaker>. That being said there are very few modules on CPAN
758 with similar goals to this module. The one I have found which is most
759 like this module is L<Class::Meta>, although it's philosophy and the MOP it
760 creates are very different from this modules.
764 All complex software has bugs lurking in it, and this module is no
765 exception. If you find a bug please either email me, or add the bug
770 I use L<Devel::Cover> to test the code coverage of my tests, below is the
771 L<Devel::Cover> report on this module's test suite.
773 ---------------------------- ------ ------ ------ ------ ------ ------ ------
774 File stmt bran cond sub pod time total
775 ---------------------------- ------ ------ ------ ------ ------ ------ ------
776 Class/MOP.pm 97.7 100.0 88.9 94.7 100.0 3.2 96.6
777 Class/MOP/Attribute.pm 75.5 77.9 82.4 88.3 100.0 4.0 81.5
778 Class/MOP/Class.pm 96.9 88.8 72.1 98.2 100.0 35.8 91.4
779 Class/MOP/Class/Immutable.pm 88.2 60.0 n/a 95.5 100.0 0.5 84.6
780 Class/MOP/Instance.pm 86.4 75.0 33.3 86.2 100.0 1.2 87.5
781 Class/MOP/Method.pm 97.5 75.0 61.5 80.6 100.0 12.7 89.7
782 Class/MOP/Module.pm 100.0 n/a 55.6 100.0 100.0 0.1 90.7
783 Class/MOP/Object.pm 73.3 n/a 20.0 80.0 100.0 0.1 66.7
784 Class/MOP/Package.pm 94.6 71.7 33.3 100.0 100.0 42.2 87.0
785 metaclass.pm 100.0 100.0 83.3 100.0 n/a 0.2 97.7
786 ---------------------------- ------ ------ ------ ------ ------ ------ ------
787 Total 91.3 80.4 69.8 91.9 100.0 100.0 88.1
788 ---------------------------- ------ ------ ------ ------ ------ ------ ------
790 =head1 ACKNOWLEDGEMENTS
796 Thanks to Rob for actually getting the development of this module kick-started.
802 Stevan Little E<lt>stevan@iinteractive.comE<gt>
804 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
806 =head1 COPYRIGHT AND LICENSE
808 Copyright 2006 by Infinity Interactive, Inc.
810 L<http://www.iinteractive.com>
812 This library is free software; you can redistribute it and/or modify
813 it under the same terms as Perl itself.