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