0.33
[gitmo/Class-MOP.git] / lib / Class / MOP.pm
CommitLineData
94b19069 1
2package Class::MOP;
3
4use strict;
5use warnings;
6
727919c5 7use Carp 'confess';
be7677c7 8use Scalar::Util 'weaken';
8b978dd5 9
2eb717d5 10use Class::MOP::Class;
11use Class::MOP::Attribute;
12use Class::MOP::Method;
13
857f87a7 14use Class::MOP::Class::Immutable;
15
148b4697 16our $VERSION = '0.33';
f0480c45 17our $AUTHORITY = 'cpan:STEVAN';
94b19069 18
be7677c7 19{
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?
24 my %METAS;
25
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 }
36
37 # NOTE:
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.
42}
43
aa448b16 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## ----------------------------------------------------------------------------
50
3bf7644b 51# ... nothing yet actually ;)
8b978dd5 52
b51af7f9 53## ----------------------------------------------------------------------------
54## Bootstrapping
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.
60##
61## Yes, I know, thats weird and insane, but it's a good thing, trust me :)
62## ----------------------------------------------------------------------------
727919c5 63
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
67
f0480c45 68## --------------------------------------------------------
6d5355c3 69## Class::MOP::Package
727919c5 70
6d5355c3 71Class::MOP::Package->meta->add_attribute(
351bd7d4 72 Class::MOP::Attribute->new('$:package' => (
b880e0de 73 reader => {
74 # NOTE: we need to do this in order
75 # for the instance meta-object to
76 # not fall into meta-circular death
77 'name' => sub { (shift)->{'$:package'} }
78 },
7b31baf4 79 init_arg => ':package',
727919c5 80 ))
81);
82
a5e51f0b 83Class::MOP::Package->meta->add_attribute(
84 Class::MOP::Attribute->new('%:namespace' => (
85 reader => {
56dcfc1a 86 # NOTE:
87 # because of issues with the Perl API
88 # to the typeglob in some versions, we
89 # need to just always grab a new
90 # reference to the hash here. Ideally
91 # we could just store a ref and it would
92 # Just Work, but oh well :\
93 'namespace' => sub {
94 no strict 'refs';
95 \%{$_[0]->name . '::'}
96 }
a5e51f0b 97 },
98 # NOTE:
99 # protect this from silliness
a2ee6c61 100 init_arg => '!............( DO NOT DO THIS )............!',
a5e51f0b 101 ))
102);
103
9d6dce77 104# NOTE:
105# use the metaclass to construct the meta-package
106# which is a superclass of the metaclass itself :P
107Class::MOP::Package->meta->add_method('initialize' => sub {
108 my $class = shift;
109 my $package_name = shift;
110 $class->meta->new_object(':package' => $package_name, @_);
111});
112
f0480c45 113## --------------------------------------------------------
114## Class::MOP::Module
115
116# NOTE:
117# yeah this is kind of stretching things a bit,
118# but truthfully the version should be an attribute
119# of the Module, the weirdness comes from having to
120# stick to Perl 5 convention and store it in the
121# $VERSION package variable. Basically if you just
122# squint at it, it will look how you want it to look.
123# Either as a package variable, or as a attribute of
124# the metaclass, isn't abstraction great :)
125
126Class::MOP::Module->meta->add_attribute(
127 Class::MOP::Attribute->new('$:version' => (
128 reader => {
129 'version' => sub {
130 my $self = shift;
131 ${$self->get_package_symbol('$VERSION')};
132 }
133 },
134 # NOTE:
135 # protect this from silliness
136 init_arg => '!............( DO NOT DO THIS )............!',
137 ))
138);
139
140# NOTE:
141# By following the same conventions as version here,
142# we are opening up the possibility that people can
143# use the $AUTHORITY in non-Class::MOP modules as
144# well.
145
146Class::MOP::Module->meta->add_attribute(
147 Class::MOP::Attribute->new('$:authority' => (
148 reader => {
149 'authority' => sub {
150 my $self = shift;
151 ${$self->get_package_symbol('$AUTHORITY')};
152 }
153 },
154 # NOTE:
155 # protect this from silliness
156 init_arg => '!............( DO NOT DO THIS )............!',
157 ))
158);
159
160## --------------------------------------------------------
6d5355c3 161## Class::MOP::Class
162
727919c5 163Class::MOP::Class->meta->add_attribute(
351bd7d4 164 Class::MOP::Attribute->new('%:attributes' => (
f7259199 165 reader => {
166 # NOTE: we need to do this in order
167 # for the instance meta-object to
168 # not fall into meta-circular death
169 'get_attribute_map' => sub { (shift)->{'%:attributes'} }
170 },
351bd7d4 171 init_arg => ':attributes',
727919c5 172 default => sub { {} }
173 ))
174);
175
351bd7d4 176Class::MOP::Class->meta->add_attribute(
177 Class::MOP::Attribute->new('$:attribute_metaclass' => (
7b31baf4 178 reader => 'attribute_metaclass',
351bd7d4 179 init_arg => ':attribute_metaclass',
180 default => 'Class::MOP::Attribute',
181 ))
182);
183
184Class::MOP::Class->meta->add_attribute(
185 Class::MOP::Attribute->new('$:method_metaclass' => (
7b31baf4 186 reader => 'method_metaclass',
351bd7d4 187 init_arg => ':method_metaclass',
188 default => 'Class::MOP::Method',
189 ))
190);
191
2bab2be6 192Class::MOP::Class->meta->add_attribute(
193 Class::MOP::Attribute->new('$:instance_metaclass' => (
b880e0de 194 reader => {
195 # NOTE: we need to do this in order
196 # for the instance meta-object to
197 # not fall into meta-circular death
198 'instance_metaclass' => sub { (shift)->{'$:instance_metaclass'} }
199 },
2bab2be6 200 init_arg => ':instance_metaclass',
201 default => 'Class::MOP::Instance',
202 ))
203);
204
9d6dce77 205# NOTE:
206# we don't actually need to tie the knot with
207# Class::MOP::Class here, it is actually handled
208# within Class::MOP::Class itself in the
209# construct_class_instance method.
210
f0480c45 211## --------------------------------------------------------
727919c5 212## Class::MOP::Attribute
213
7b31baf4 214Class::MOP::Attribute->meta->add_attribute(
215 Class::MOP::Attribute->new('name' => (
b880e0de 216 reader => {
217 # NOTE: we need to do this in order
218 # for the instance meta-object to
219 # not fall into meta-circular death
220 'name' => sub { (shift)->{name} }
221 }
7b31baf4 222 ))
223);
224
225Class::MOP::Attribute->meta->add_attribute(
226 Class::MOP::Attribute->new('associated_class' => (
b880e0de 227 reader => {
228 # NOTE: we need to do this in order
229 # for the instance meta-object to
230 # not fall into meta-circular death
231 'associated_class' => sub { (shift)->{associated_class} }
232 }
7b31baf4 233 ))
234);
235
236Class::MOP::Attribute->meta->add_attribute(
237 Class::MOP::Attribute->new('accessor' => (
238 reader => 'accessor',
239 predicate => 'has_accessor',
240 ))
241);
242
243Class::MOP::Attribute->meta->add_attribute(
244 Class::MOP::Attribute->new('reader' => (
245 reader => 'reader',
246 predicate => 'has_reader',
247 ))
248);
249
250Class::MOP::Attribute->meta->add_attribute(
251 Class::MOP::Attribute->new('writer' => (
252 reader => 'writer',
253 predicate => 'has_writer',
254 ))
255);
256
257Class::MOP::Attribute->meta->add_attribute(
258 Class::MOP::Attribute->new('predicate' => (
259 reader => 'predicate',
260 predicate => 'has_predicate',
261 ))
262);
263
264Class::MOP::Attribute->meta->add_attribute(
7d28758b 265 Class::MOP::Attribute->new('clearer' => (
266 reader => 'clearer',
267 predicate => 'has_clearer',
268 ))
269);
270
271Class::MOP::Attribute->meta->add_attribute(
7b31baf4 272 Class::MOP::Attribute->new('init_arg' => (
273 reader => 'init_arg',
274 predicate => 'has_init_arg',
275 ))
276);
277
278Class::MOP::Attribute->meta->add_attribute(
279 Class::MOP::Attribute->new('default' => (
280 # default has a custom 'reader' method ...
281 predicate => 'has_default',
282 ))
283);
284
727919c5 285
286# NOTE: (meta-circularity)
287# This should be one of the last things done
288# it will "tie the knot" with Class::MOP::Attribute
289# so that it uses the attributes meta-objects
290# to construct itself.
291Class::MOP::Attribute->meta->add_method('new' => sub {
292 my $class = shift;
293 my $name = shift;
294 my %options = @_;
295
296 (defined $name && $name)
297 || confess "You must provide a name for the attribute";
5659d76e 298 $options{init_arg} = $name
299 if not exists $options{init_arg};
148b4697 300
301 (Class::MOP::Attribute::is_default_a_coderef(\%options))
302 || confess("References are not allowed as default values, you must ".
303 "wrap then in a CODE reference (ex: sub { [] } and not [])")
304 if exists $options{default} && ref $options{default};
651955fb 305
5659d76e 306 # return the new object
307 $class->meta->new_object(name => $name, %options);
308});
309
310Class::MOP::Attribute->meta->add_method('clone' => sub {
a740253a 311 my $self = shift;
a27ae83f 312 $self->meta->clone_object($self, @_);
727919c5 313});
314
f0480c45 315## --------------------------------------------------------
316## Now close all the Class::MOP::* classes
4d47b77f 317
318Class::MOP::Package ->meta->make_immutable(inline_constructor => 0);
319Class::MOP::Module ->meta->make_immutable(inline_constructor => 0);
320Class::MOP::Class ->meta->make_immutable(inline_constructor => 0);
321Class::MOP::Attribute->meta->make_immutable(inline_constructor => 0);
322Class::MOP::Method ->meta->make_immutable(inline_constructor => 0);
323Class::MOP::Instance ->meta->make_immutable(inline_constructor => 0);
6e57504d 324Class::MOP::Object ->meta->make_immutable(inline_constructor => 0);
4d47b77f 325
94b19069 3261;
327
328__END__
329
330=pod
331
332=head1 NAME
333
334Class::MOP - A Meta Object Protocol for Perl 5
335
336=head1 SYNOPSIS
337
a2e85e6c 338 # ... This will come later, for now see
339 # the other SYNOPSIS for more information
94b19069 340
341=head1 DESCRIPTON
342
343This module is an attempt to create a meta object protocol for the
344Perl 5 object system. It makes no attempt to change the behavior or
345characteristics of the Perl 5 object system, only to create a
27e31eaf 346protocol for its manipulation and introspection.
94b19069 347
348That said, it does attempt to create the tools for building a rich
349set of extensions to the Perl 5 object system. Every attempt has been
350made for these tools to keep to the spirit of the Perl 5 object
351system that we all know and love.
352
40483095 353This documentation is admittedly sparse on details, as time permits
354I will try to improve them. For now, I suggest looking at the items
355listed in the L<SEE ALSO> section for more information. In particular
356the book "The Art of the Meta Object Protocol" was very influential
357in the development of this system.
358
bfe4d0fc 359=head2 What is a Meta Object Protocol?
360
361A meta object protocol is an API to an object system.
362
363To be more specific, it is a set of abstractions of the components of
364an object system (typically things like; classes, object, methods,
365object attributes, etc.). These abstractions can then be used to both
366inspect and manipulate the object system which they describe.
367
368It can be said that there are two MOPs for any object system; the
369implicit MOP, and the explicit MOP. The implicit MOP handles things
370like method dispatch or inheritance, which happen automatically as
371part of how the object system works. The explicit MOP typically
372handles the introspection/reflection features of the object system.
373All object systems have implicit MOPs, without one, they would not
374work. Explict MOPs however as less common, and depending on the
375language can vary from restrictive (Reflection in Java or C#) to
376wide open (CLOS is a perfect example).
377
e16da3e6 378=head2 Yet Another Class Builder!! Why?
379
380This is B<not> a class builder so much as it is a I<class builder
381B<builder>>. My intent is that an end user does not use this module
382directly, but instead this module is used by module authors to
383build extensions and features onto the Perl 5 object system.
384
94b19069 385=head2 Who is this module for?
386
387This module is specifically for anyone who has ever created or
388wanted to create a module for the Class:: namespace. The tools which
389this module will provide will hopefully make it easier to do more
390complex things with Perl 5 classes by removing such barriers as
391the need to hack the symbol tables, or understand the fine details
392of method dispatch.
393
bfe4d0fc 394=head2 What changes do I have to make to use this module?
395
2eb717d5 396This module was designed to be as unintrusive as possible. Many of
343203ee 397its features are accessible without B<any> change to your existsing
bfe4d0fc 398code at all. It is meant to be a compliment to your existing code and
2eb717d5 399not an intrusion on your code base. Unlike many other B<Class::>
a2e85e6c 400modules, this module B<does not> require you subclass it, or even that
401you C<use> it in within your module's package.
bfe4d0fc 402
2eb717d5 403The only features which requires additions to your code are the
404attribute handling and instance construction features, and these are
a2e85e6c 405both completely optional features. The only reason for this is because
2eb717d5 406Perl 5's object system does not actually have these features built
407in. More information about this feature can be found below.
bfe4d0fc 408
409=head2 A Note about Performance?
410
411It is a common misconception that explict MOPs are performance drains.
412But this is not a universal truth at all, it is an side-effect of
413specific implementations. For instance, using Java reflection is much
414slower because the JVM cannot take advantage of any compiler
415optimizations, and the JVM has to deal with much more runtime type
416information as well. Reflection in C# is marginally better as it was
417designed into the language and runtime (the CLR). In contrast, CLOS
418(the Common Lisp Object System) was built to support an explicit MOP,
419and so performance is tuned for it.
420
421This library in particular does it's absolute best to avoid putting
2eb717d5 422B<any> drain at all upon your code's performance. In fact, by itself
423it does nothing to affect your existing code. So you only pay for
424what you actually use.
bfe4d0fc 425
550d56db 426=head2 About Metaclass compatibility
427
428This module makes sure that all metaclasses created are both upwards
429and downwards compatible. The topic of metaclass compatibility is
430highly esoteric and is something only encountered when doing deep and
431involved metaclass hacking. There are two basic kinds of metaclass
432incompatibility; upwards and downwards.
433
434Upwards metaclass compatibility means that the metaclass of a
435given class is either the same as (or a subclass of) all of the
436class's ancestors.
437
438Downward metaclass compatibility means that the metaclasses of a
439given class's anscestors are all either the same as (or a subclass
440of) that metaclass.
441
442Here is a diagram showing a set of two classes (C<A> and C<B>) and
443two metaclasses (C<Meta::A> and C<Meta::B>) which have correct
444metaclass compatibility both upwards and downwards.
445
446 +---------+ +---------+
447 | Meta::A |<----| Meta::B | <....... (instance of )
448 +---------+ +---------+ <------- (inherits from)
449 ^ ^
450 : :
451 +---------+ +---------+
452 | A |<----| B |
453 +---------+ +---------+
454
455As I said this is a highly esoteric topic and one you will only run
456into if you do a lot of subclassing of B<Class::MOP::Class>. If you
457are interested in why this is an issue see the paper
458I<Uniform and safe metaclass composition> linked to in the
459L<SEE ALSO> section of this document.
460
aa448b16 461=head2 Using custom metaclasses
462
463Always use the metaclass pragma when using a custom metaclass, this
464will ensure the proper initialization order and not accidentely
465create an incorrect type of metaclass for you. This is a very rare
466problem, and one which can only occur if you are doing deep metaclass
467programming. So in other words, don't worry about it.
468
94b19069 469=head1 PROTOCOLS
470
471The protocol is divided into 3 main sub-protocols:
472
473=over 4
474
475=item The Class protocol
476
477This provides a means of manipulating and introspecting a Perl 5
478class. It handles all of symbol table hacking for you, and provides
479a rich set of methods that go beyond simple package introspection.
480
552e3d24 481See L<Class::MOP::Class> for more details.
482
94b19069 483=item The Attribute protocol
484
485This provides a consistent represenation for an attribute of a
486Perl 5 class. Since there are so many ways to create and handle
487atttributes in Perl 5 OO, this attempts to provide as much of a
488unified approach as possible, while giving the freedom and
489flexibility to subclass for specialization.
490
552e3d24 491See L<Class::MOP::Attribute> for more details.
492
94b19069 493=item The Method protocol
494
495This provides a means of manipulating and introspecting methods in
496the Perl 5 object system. As with attributes, there are many ways to
497approach this topic, so we try to keep it pretty basic, while still
498making it possible to extend the system in many ways.
499
552e3d24 500See L<Class::MOP::Method> for more details.
94b19069 501
502=back
503
be7677c7 504=head1 FUNCTIONS
505
506Class::MOP holds a cache of metaclasses, the following are functions
507(B<not methods>) which can be used to access that cache. It is not
508recommended that you mess with this, bad things could happen. But if
509you are brave and willing to risk it, go for it.
510
511=over 4
512
513=item B<get_all_metaclasses>
514
b9d9fc0b 515This will return an hash of all the metaclass instances that have
516been cached by B<Class::MOP::Class> keyed by the package name.
517
be7677c7 518=item B<get_all_metaclass_instances>
519
b9d9fc0b 520This will return an array of all the metaclass instances that have
521been cached by B<Class::MOP::Class>.
522
be7677c7 523=item B<get_all_metaclass_names>
524
b9d9fc0b 525This will return an array of all the metaclass names that have
526been cached by B<Class::MOP::Class>.
527
be7677c7 528=item B<get_metaclass_by_name ($name)>
529
530=item B<store_metaclass_by_name ($name, $meta)>
531
532=item B<weaken_metaclass ($name)>
533
534=item B<does_metaclass_exist ($name)>
535
536=item B<remove_metaclass_by_name ($name)>
537
538=back
539
552e3d24 540=head1 SEE ALSO
8b978dd5 541
552e3d24 542=head2 Books
8b978dd5 543
a2e85e6c 544There are very few books out on Meta Object Protocols and Metaclasses
545because it is such an esoteric topic. The following books are really
546the only ones I have found. If you know of any more, B<I<please>>
547email me and let me know, I would love to hear about them.
548
8b978dd5 549=over 4
550
552e3d24 551=item "The Art of the Meta Object Protocol"
8b978dd5 552
552e3d24 553=item "Advances in Object-Oriented Metalevel Architecture and Reflection"
8b978dd5 554
b51af7f9 555=item "Putting MetaClasses to Work"
556
a2e85e6c 557=item "Smalltalk: The Language"
558
94b19069 559=back
560
550d56db 561=head2 Papers
562
563=over 4
564
565=item Uniform and safe metaclass composition
566
567An excellent paper by the people who brought us the original Traits paper.
568This paper is on how Traits can be used to do safe metaclass composition,
569and offers an excellent introduction section which delves into the topic of
570metaclass compatibility.
571
572L<http://www.iam.unibe.ch/~scg/Archive/Papers/Duca05ySafeMetaclassTrait.pdf>
573
574=item Safe Metaclass Programming
575
576This paper seems to precede the above paper, and propose a mix-in based
577approach as opposed to the Traits based approach. Both papers have similar
578information on the metaclass compatibility problem space.
579
580L<http://citeseer.ist.psu.edu/37617.html>
581
582=back
583
552e3d24 584=head2 Prior Art
8b978dd5 585
586=over 4
587
7184ca14 588=item The Perl 6 MetaModel work in the Pugs project
8b978dd5 589
590=over 4
591
552e3d24 592=item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel>
8b978dd5 593
552e3d24 594=item L<http://svn.openfoundry.org/pugs/perl5/Perl6-ObjectSpace>
8b978dd5 595
596=back
597
94b19069 598=back
599
a2e85e6c 600=head1 SIMILAR MODULES
601
602As I have said above, this module is a class-builder-builder, so it is
603not the same thing as modules like L<Class::Accessor> and
604L<Class::MethodMaker>. That being said there are very few modules on CPAN
605with similar goals to this module. The one I have found which is most
550d56db 606like this module is L<Class::Meta>, although it's philosophy and the MOP it
607creates are very different from this modules.
94b19069 608
a2e85e6c 609=head1 BUGS
610
611All complex software has bugs lurking in it, and this module is no
612exception. If you find a bug please either email me, or add the bug
613to cpan-RT.
614
22286063 615=head1 CODE COVERAGE
616
617I use L<Devel::Cover> to test the code coverage of my tests, below is the
618L<Devel::Cover> report on this module's test suite.
619
620 ---------------------------- ------ ------ ------ ------ ------ ------ ------
621 File stmt bran cond sub pod time total
622 ---------------------------- ------ ------ ------ ------ ------ ------ ------
b9d9fc0b 623 Class/MOP.pm 78.0 87.5 55.6 71.4 100.0 12.4 76.8
624 Class/MOP/Attribute.pm 83.4 75.6 86.7 94.4 100.0 8.9 85.2
625 Class/MOP/Class.pm 96.9 75.8 43.2 98.0 100.0 55.3 83.6
626 Class/MOP/Class/Immutable.pm 88.5 53.8 n/a 95.8 100.0 1.1 84.7
627 Class/MOP/Instance.pm 87.9 75.0 33.3 89.7 100.0 10.1 89.1
628 Class/MOP/Method.pm 97.6 60.0 57.9 76.9 100.0 1.5 82.8
629 Class/MOP/Module.pm 87.5 n/a 11.1 83.3 100.0 0.3 66.7
630 Class/MOP/Object.pm 100.0 n/a 33.3 100.0 100.0 0.1 89.5
631 Class/MOP/Package.pm 95.1 69.0 33.3 100.0 100.0 9.9 85.5
632 metaclass.pm 100.0 100.0 83.3 100.0 n/a 0.5 97.7
22286063 633 ---------------------------- ------ ------ ------ ------ ------ ------ ------
b9d9fc0b 634 Total 91.5 72.1 48.8 90.7 100.0 100.0 84.2
22286063 635 ---------------------------- ------ ------ ------ ------ ------ ------ ------
636
a2e85e6c 637=head1 ACKNOWLEDGEMENTS
638
639=over 4
640
b9d9fc0b 641=item Rob Kinyon
a2e85e6c 642
643Thanks to Rob for actually getting the development of this module kick-started.
644
645=back
646
1a09d9cc 647=head1 AUTHORS
94b19069 648
a2e85e6c 649Stevan Little E<lt>stevan@iinteractive.comE<gt>
552e3d24 650
1a09d9cc 651Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
652
94b19069 653=head1 COPYRIGHT AND LICENSE
654
655Copyright 2006 by Infinity Interactive, Inc.
656
657L<http://www.iinteractive.com>
658
659This library is free software; you can redistribute it and/or modify
660it under the same terms as Perl itself.
661
662=cut