adding in tests
[gitmo/Class-MOP.git] / lib / Class / MOP.pm
1
2 package Class::MOP;
3
4 use strict;
5 use warnings;
6
7 use Scalar::Util 'blessed';
8 use Carp         'confess';
9 use SUPER         ();
10
11 use Class::MOP::Class;
12 use Class::MOP::Attribute;
13 use Class::MOP::Method;
14
15 our $VERSION = '0.07';
16
17 sub import {
18     shift;
19     return unless @_;
20     if ($_[0] eq ':universal') {
21         *UNIVERSAL::meta = sub { 
22             Class::MOP::Class->initialize(blessed($_[0]) || $_[0]) 
23         };
24     }
25     else {
26         my $pkg = caller();
27         no strict 'refs';
28         *{$pkg . '::' . $_[0]} = sub { 
29             Class::MOP::Class->initialize(blessed($_[0]) || $_[0]) 
30         };        
31     }
32 }
33
34 ## ----------------------------------------------------------------------------
35 ## Bootstrapping 
36 ## ----------------------------------------------------------------------------
37 ## The code below here is to bootstrap our MOP with itself. This is also 
38 ## sometimes called "tying the knot". By doing this, we make it much easier
39 ## to extend the MOP through subclassing and such since now you can use the
40 ## MOP itself to extend itself. 
41 ## 
42 ## Yes, I know, thats weird and insane, but it's a good thing, trust me :)
43 ## ---------------------------------------------------------------------------- 
44
45 # We need to add in the meta-attributes here so that 
46 # any subclass of Class::MOP::* will be able to 
47 # inherit them using &construct_instance
48
49 ## Class::MOP::Class
50
51 Class::MOP::Class->meta->add_attribute(
52     Class::MOP::Attribute->new('$:package' => (
53         reader   => 'name',
54         init_arg => ':package',
55     ))
56 );
57
58 Class::MOP::Class->meta->add_attribute(
59     Class::MOP::Attribute->new('%:attributes' => (
60         reader   => 'get_attribute_map',
61         init_arg => ':attributes',
62         default  => sub { {} }
63     ))
64 );
65
66 Class::MOP::Class->meta->add_attribute(
67     Class::MOP::Attribute->new('$:attribute_metaclass' => (
68         reader   => 'attribute_metaclass',
69         init_arg => ':attribute_metaclass',
70         default  => 'Class::MOP::Attribute',
71     ))
72 );
73
74 Class::MOP::Class->meta->add_attribute(
75     Class::MOP::Attribute->new('$:method_metaclass' => (
76         reader   => 'method_metaclass',
77         init_arg => ':method_metaclass',
78         default  => 'Class::MOP::Method',        
79     ))
80 );
81
82 ## Class::MOP::Attribute
83
84 Class::MOP::Attribute->meta->add_attribute(
85     Class::MOP::Attribute->new('name' => (
86         reader => 'name'
87     ))
88 );
89
90 Class::MOP::Attribute->meta->add_attribute(
91     Class::MOP::Attribute->new('associated_class' => (
92         reader => 'associated_class'
93     ))
94 );
95
96 Class::MOP::Attribute->meta->add_attribute(
97     Class::MOP::Attribute->new('accessor' => (
98         reader    => 'accessor',
99         predicate => 'has_accessor',
100     ))
101 );
102
103 Class::MOP::Attribute->meta->add_attribute(
104     Class::MOP::Attribute->new('reader' => (
105         reader    => 'reader',
106         predicate => 'has_reader',
107     ))
108 );
109
110 Class::MOP::Attribute->meta->add_attribute(
111     Class::MOP::Attribute->new('writer' => (
112         reader    => 'writer',
113         predicate => 'has_writer',
114     ))
115 );
116
117 Class::MOP::Attribute->meta->add_attribute(
118     Class::MOP::Attribute->new('predicate' => (
119         reader    => 'predicate',
120         predicate => 'has_predicate',
121     ))
122 );
123
124 Class::MOP::Attribute->meta->add_attribute(
125     Class::MOP::Attribute->new('init_arg' => (
126         reader    => 'init_arg',
127         predicate => 'has_init_arg',
128     ))
129 );
130
131 Class::MOP::Attribute->meta->add_attribute(
132     Class::MOP::Attribute->new('default' => (
133         # default has a custom 'reader' method ...
134         predicate => 'has_default',
135     ))
136 );
137
138
139 # NOTE: (meta-circularity)
140 # This should be one of the last things done
141 # it will "tie the knot" with Class::MOP::Attribute
142 # so that it uses the attributes meta-objects 
143 # to construct itself. 
144 Class::MOP::Attribute->meta->add_method('new' => sub {
145     my $class   = shift;
146     my $name    = shift;
147     my %options = @_;    
148         
149     (defined $name && $name)
150         || confess "You must provide a name for the attribute";
151     $options{init_arg} = $name 
152         if not exists $options{init_arg};
153
154     # return the new object
155     $class->meta->new_object(name => $name, %options);
156 });
157
158 Class::MOP::Attribute->meta->add_method('clone' => sub {
159     my $self  = shift;
160     my $class = $self->associated_class;
161     $self->detach_from_class() if defined $class;
162     my $clone = $self->meta->clone_object($self, @_);  
163     if (defined $class) {
164         $self->attach_to_class($class);
165         $clone->attach_to_class($class);
166     }
167     return $clone;  
168 });
169
170 1;
171
172 __END__
173
174 =pod
175
176 =head1 NAME 
177
178 Class::MOP - A Meta Object Protocol for Perl 5
179
180 =head1 SYNOPSIS
181
182   # ... This will come later, for now see
183   # the other SYNOPSIS for more information
184
185 =head1 DESCRIPTON
186
187 This module is an attempt to create a meta object protocol for the 
188 Perl 5 object system. It makes no attempt to change the behavior or 
189 characteristics of the Perl 5 object system, only to create a 
190 protocol for its manipulation and introspection.
191
192 That said, it does attempt to create the tools for building a rich 
193 set of extensions to the Perl 5 object system. Every attempt has been 
194 made for these tools to keep to the spirit of the Perl 5 object 
195 system that we all know and love.
196
197 =head2 What is a Meta Object Protocol?
198
199 A meta object protocol is an API to an object system. 
200
201 To be more specific, it is a set of abstractions of the components of 
202 an object system (typically things like; classes, object, methods, 
203 object attributes, etc.). These abstractions can then be used to both 
204 inspect and manipulate the object system which they describe.
205
206 It can be said that there are two MOPs for any object system; the 
207 implicit MOP, and the explicit MOP. The implicit MOP handles things 
208 like method dispatch or inheritance, which happen automatically as 
209 part of how the object system works. The explicit MOP typically 
210 handles the introspection/reflection features of the object system. 
211 All object systems have implicit MOPs, without one, they would not 
212 work. Explict MOPs however as less common, and depending on the 
213 language can vary from restrictive (Reflection in Java or C#) to 
214 wide open (CLOS is a perfect example). 
215
216 =head2 Yet Another Class Builder!! Why?
217
218 This is B<not> a class builder so much as it is a I<class builder 
219 B<builder>>. My intent is that an end user does not use this module 
220 directly, but instead this module is used by module authors to 
221 build extensions and features onto the Perl 5 object system. 
222
223 =head2 Who is this module for?
224
225 This module is specifically for anyone who has ever created or 
226 wanted to create a module for the Class:: namespace. The tools which 
227 this module will provide will hopefully make it easier to do more 
228 complex things with Perl 5 classes by removing such barriers as 
229 the need to hack the symbol tables, or understand the fine details 
230 of method dispatch. 
231
232 =head2 What changes do I have to make to use this module?
233
234 This module was designed to be as unintrusive as possible. Many of 
235 its features are accessible without B<any> change to your existsing 
236 code at all. It is meant to be a compliment to your existing code and 
237 not an intrusion on your code base. Unlike many other B<Class::> 
238 modules, this module B<does not> require you subclass it, or even that 
239 you C<use> it in within your module's package. 
240
241 The only features which requires additions to your code are the 
242 attribute handling and instance construction features, and these are
243 both completely optional features. The only reason for this is because 
244 Perl 5's object system does not actually have these features built 
245 in. More information about this feature can be found below.
246
247 =head2 A Note about Performance?
248
249 It is a common misconception that explict MOPs are performance drains. 
250 But this is not a universal truth at all, it is an side-effect of 
251 specific implementations. For instance, using Java reflection is much 
252 slower because the JVM cannot take advantage of any compiler 
253 optimizations, and the JVM has to deal with much more runtime type 
254 information as well. Reflection in C# is marginally better as it was 
255 designed into the language and runtime (the CLR). In contrast, CLOS 
256 (the Common Lisp Object System) was built to support an explicit MOP, 
257 and so performance is tuned for it. 
258
259 This library in particular does it's absolute best to avoid putting 
260 B<any> drain at all upon your code's performance. In fact, by itself 
261 it does nothing to affect your existing code. So you only pay for 
262 what you actually use.
263
264 =head2 About Metaclass compatibility
265
266 This module makes sure that all metaclasses created are both upwards 
267 and downwards compatible. The topic of metaclass compatibility is 
268 highly esoteric and is something only encountered when doing deep and 
269 involved metaclass hacking. There are two basic kinds of metaclass 
270 incompatibility; upwards and downwards. 
271
272 Upwards metaclass compatibility means that the metaclass of a 
273 given class is either the same as (or a subclass of) all of the 
274 class's ancestors.
275
276 Downward metaclass compatibility means that the metaclasses of a 
277 given class's anscestors are all either the same as (or a subclass 
278 of) that metaclass.
279
280 Here is a diagram showing a set of two classes (C<A> and C<B>) and 
281 two metaclasses (C<Meta::A> and C<Meta::B>) which have correct  
282 metaclass compatibility both upwards and downwards.
283
284     +---------+     +---------+
285     | Meta::A |<----| Meta::B |      <....... (instance of  )
286     +---------+     +---------+      <------- (inherits from)  
287          ^               ^
288          :               :
289     +---------+     +---------+
290     |    A    |<----|    B    |
291     +---------+     +---------+
292
293 As I said this is a highly esoteric topic and one you will only run 
294 into if you do a lot of subclassing of B<Class::MOP::Class>. If you 
295 are interested in why this is an issue see the paper 
296 I<Uniform and safe metaclass composition> linked to in the 
297 L<SEE ALSO> section of this document.
298
299 =head1 PROTOCOLS
300
301 The protocol is divided into 3 main sub-protocols:
302
303 =over 4
304
305 =item The Class protocol
306
307 This provides a means of manipulating and introspecting a Perl 5 
308 class. It handles all of symbol table hacking for you, and provides 
309 a rich set of methods that go beyond simple package introspection.
310
311 See L<Class::MOP::Class> for more details.
312
313 =item The Attribute protocol
314
315 This provides a consistent represenation for an attribute of a 
316 Perl 5 class. Since there are so many ways to create and handle 
317 atttributes in Perl 5 OO, this attempts to provide as much of a 
318 unified approach as possible, while giving the freedom and 
319 flexibility to subclass for specialization.
320
321 See L<Class::MOP::Attribute> for more details.
322
323 =item The Method protocol
324
325 This provides a means of manipulating and introspecting methods in 
326 the Perl 5 object system. As with attributes, there are many ways to 
327 approach this topic, so we try to keep it pretty basic, while still 
328 making it possible to extend the system in many ways.
329
330 See L<Class::MOP::Method> for more details.
331
332 =back
333
334 =head1 SEE ALSO
335
336 =head2 Books
337
338 There are very few books out on Meta Object Protocols and Metaclasses 
339 because it is such an esoteric topic. The following books are really 
340 the only ones I have found. If you know of any more, B<I<please>> 
341 email me and let me know, I would love to hear about them.
342
343 =over 4
344
345 =item "The Art of the Meta Object Protocol"
346
347 =item "Advances in Object-Oriented Metalevel Architecture and Reflection"
348
349 =item "Putting MetaClasses to Work"
350
351 =item "Smalltalk: The Language"
352
353 =back
354
355 =head2 Papers
356
357 =over 4
358
359 =item Uniform and safe metaclass composition
360
361 An excellent paper by the people who brought us the original Traits paper. 
362 This paper is on how Traits can be used to do safe metaclass composition, 
363 and offers an excellent introduction section which delves into the topic of 
364 metaclass compatibility.
365
366 L<http://www.iam.unibe.ch/~scg/Archive/Papers/Duca05ySafeMetaclassTrait.pdf>
367
368 =item Safe Metaclass Programming
369
370 This paper seems to precede the above paper, and propose a mix-in based 
371 approach as opposed to the Traits based approach. Both papers have similar 
372 information on the metaclass compatibility problem space. 
373
374 L<http://citeseer.ist.psu.edu/37617.html>
375
376 =back
377
378 =head2 Prior Art
379
380 =over 4
381
382 =item The Perl 6 MetaModel work in the Pugs project
383
384 =over 4
385
386 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel>
387
388 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-ObjectSpace>
389
390 =back
391
392 =back
393
394 =head1 SIMILAR MODULES
395
396 As I have said above, this module is a class-builder-builder, so it is 
397 not the same thing as modules like L<Class::Accessor> and 
398 L<Class::MethodMaker>. That being said there are very few modules on CPAN 
399 with similar goals to this module. The one I have found which is most 
400 like this module is L<Class::Meta>, although it's philosophy and the MOP it 
401 creates are very different from this modules. 
402
403 =head1 BUGS
404
405 All complex software has bugs lurking in it, and this module is no 
406 exception. If you find a bug please either email me, or add the bug
407 to cpan-RT.
408
409 =head1 ACKNOWLEDGEMENTS
410
411 =over 4
412
413 =item Rob Kinyon E<lt>rob@iinteractive.comE<gt>
414
415 Thanks to Rob for actually getting the development of this module kick-started. 
416
417 =back
418
419 =head1 AUTHOR
420
421 Stevan Little E<lt>stevan@iinteractive.comE<gt>
422
423 =head1 COPYRIGHT AND LICENSE
424
425 Copyright 2006 by Infinity Interactive, Inc.
426
427 L<http://www.iinteractive.com>
428
429 This library is free software; you can redistribute it and/or modify
430 it under the same terms as Perl itself. 
431
432 =cut