break out most of the code to ::PurePerl
[gitmo/Class-C3.git] / lib / Class / C3.pm
1
2 package Class::C3;
3
4 use strict;
5 use warnings;
6
7 our $VERSION = '0.15';
8
9 BEGIN {
10     eval { require Class::C3::XS };
11     if($@) {
12         eval { require Class::C3::PurePerl };
13         if($@) {
14             die 'Could not load Class::C3::XS or Class::C3::PurePerl!';
15         }
16     }
17 }
18
19 1;
20
21 __END__
22
23 =pod
24
25 =head1 NAME
26
27 Class::C3 - A pragma to use the C3 method resolution order algortihm
28
29 =head1 SYNOPSIS
30
31     package A;
32     use Class::C3;     
33     sub hello { 'A::hello' }
34
35     package B;
36     use base 'A';
37     use Class::C3;     
38
39     package C;
40     use base 'A';
41     use Class::C3;     
42
43     sub hello { 'C::hello' }
44
45     package D;
46     use base ('B', 'C');
47     use Class::C3;    
48
49     # Classic Diamond MI pattern
50     #    <A>
51     #   /   \
52     # <B>   <C>
53     #   \   /
54     #    <D>
55
56     package main;
57     
58     # initializez the C3 module 
59     # (formerly called in INIT)
60     Class::C3::initialize();  
61
62     print join ', ' => Class::C3::calculateMRO('Diamond_D') # prints D, B, C, A
63
64     print D->hello() # prints 'C::hello' instead of the standard p5 'A::hello'
65     
66     D->can('hello')->();          # can() also works correctly
67     UNIVERSAL::can('D', 'hello'); # as does UNIVERSAL::can()
68
69 =head1 DESCRIPTION
70
71 This is pragma to change Perl 5's standard method resolution order from depth-first left-to-right 
72 (a.k.a - pre-order) to the more sophisticated C3 method resolution order. 
73
74 =head2 What is C3?
75
76 C3 is the name of an algorithm which aims to provide a sane method resolution order under multiple
77 inheritence. It was first introduced in the langauge Dylan (see links in the L<SEE ALSO> section),
78 and then later adopted as the prefered MRO (Method Resolution Order) for the new-style classes in 
79 Python 2.3. Most recently it has been adopted as the 'canonical' MRO for Perl 6 classes, and the 
80 default MRO for Parrot objects as well.
81
82 =head2 How does C3 work.
83
84 C3 works by always preserving local precendence ordering. This essentially means that no class will 
85 appear before any of it's subclasses. Take the classic diamond inheritence pattern for instance:
86
87      <A>
88     /   \
89   <B>   <C>
90     \   /
91      <D>
92
93 The standard Perl 5 MRO would be (D, B, A, C). The result being that B<A> appears before B<C>, even 
94 though B<C> is the subclass of B<A>. The C3 MRO algorithm however, produces the following MRO 
95 (D, B, C, A), which does not have this same issue.
96
97 This example is fairly trival, for more complex examples and a deeper explaination, see the links in
98 the L<SEE ALSO> section.
99
100 =head2 How does this module work?
101
102 This module uses a technique similar to Perl 5's method caching. When C<Class::C3::initialize> is 
103 called, this module calculates the MRO of all the classes which called C<use Class::C3>. It then 
104 gathers information from the symbol tables of each of those classes, and builds a set of method 
105 aliases for the correct dispatch ordering. Once all these C3-based method tables are created, it 
106 then adds the method aliases into the local classes symbol table. 
107
108 The end result is actually classes with pre-cached method dispatch. However, this caching does not
109 do well if you start changing your C<@ISA> or messing with class symbol tables, so you should consider
110 your classes to be effectively closed. See the L<CAVEATS> section for more details.
111
112 =head1 OPTIONAL LOWERCASE PRAGMA
113
114 This release also includes an optional module B<c3> in the F<opt/> folder. I did not include this in 
115 the regular install since lowercase module names are considered I<"bad"> by some people. However I
116 think that code looks much nicer like this:
117
118   package MyClass;
119   use c3;
120   
121 The the more clunky:
122
123   package MyClass;
124   use Class::C3;
125   
126 But hey, it's your choice, thats why it is optional.
127
128 =head1 FUNCTIONS
129
130 =over 4
131
132 =item B<calculateMRO ($class)>
133
134 Given a C<$class> this will return an array of class names in the proper C3 method resolution order.
135
136 =item B<initialize>
137
138 This B<must be called> to initalize the C3 method dispatch tables, this module B<will not work> if 
139 you do not do this. It is advised to do this as soon as possible B<after> loading any classes which 
140 use C3. Here is a quick code example:
141   
142   package Foo;
143   use Class::C3;
144   # ... Foo methods here
145   
146   package Bar;
147   use Class::C3;
148   use base 'Foo';
149   # ... Bar methods here
150   
151   package main;
152   
153   Class::C3::initialize(); # now it is safe to use Foo and Bar
154
155 This function used to be called automatically for you in the INIT phase of the perl compiler, but 
156 that lead to warnings if this module was required at runtime. After discussion with my user base 
157 (the L<DBIx::Class> folks), we decided that calling this in INIT was more of an annoyance than a 
158 convience. I apologize to anyone this causes problems for (although i would very suprised if I had 
159 any other users other than the L<DBIx::Class> folks). The simplest solution of course is to define 
160 your own INIT method which calls this function. 
161
162 NOTE: 
163
164 If C<initialize> detects that C<initialize> has already been executed, it will L</uninitialize> and
165 clear the MRO cache first.
166
167 =item B<uninitialize>
168
169 Calling this function results in the removal of all cached methods, and the restoration of the old Perl 5
170 style dispatch order (depth-first, left-to-right). 
171
172 =item B<reinitialize>
173
174 This is an alias for L</initialize> above.
175
176 =back
177
178 =head1 METHOD REDISPATCHING
179
180 It is always useful to be able to re-dispatch your method call to the "next most applicable method". This 
181 module provides a pseudo package along the lines of C<SUPER::> or C<NEXT::> which will re-dispatch the 
182 method along the C3 linearization. This is best show with an examples.
183
184   # a classic diamond MI pattern ...
185      <A>
186     /   \
187   <B>   <C>
188     \   /
189      <D>
190   
191   package A;
192   use c3; 
193   sub foo { 'A::foo' }       
194  
195   package B;
196   use base 'A'; 
197   use c3;     
198   sub foo { 'B::foo => ' . (shift)->next::method() }       
199  
200   package B;
201   use base 'A'; 
202   use c3;    
203   sub foo { 'C::foo => ' . (shift)->next::method() }   
204  
205   package D;
206   use base ('B', 'C'); 
207   use c3; 
208   sub foo { 'D::foo => ' . (shift)->next::method() }   
209   
210   print D->foo; # prints out "D::foo => B::foo => C::foo => A::foo"
211
212 A few things to note. First, we do not require you to add on the method name to the C<next::method> 
213 call (this is unlike C<NEXT::> and C<SUPER::> which do require that). This helps to enforce the rule 
214 that you cannot dispatch to a method of a different name (this is how C<NEXT::> behaves as well). 
215
216 The next thing to keep in mind is that you will need to pass all arguments to C<next::method> it can 
217 not automatically use the current C<@_>. 
218
219 If C<next::method> cannot find a next method to re-dispatch the call to, it will throw an exception.
220 You can use C<next::can> to see if C<next::method> will succeed before you call it like so:
221
222   $self->next::method(@_) if $self->next::can; 
223
224 Additionally, you can use C<maybe::next::method> as a shortcut to only call the next method if it exists. 
225 The previous example could be simply written as:
226
227   $self->maybe::next::method(@_);
228
229 There are some caveats about using C<next::method>, see below for those.
230
231 =head1 CAVEATS
232
233 This module used to be labeled as I<experimental>, however it has now been pretty heavily tested by 
234 the good folks over at L<DBIx::Class> and I am confident this module is perfectly usable for 
235 whatever your needs might be. 
236
237 But there are still caveats, so here goes ...
238
239 =over 4
240
241 =item Use of C<SUPER::>.
242
243 The idea of C<SUPER::> under multiple inheritence is ambigious, and generally not recomended anyway.
244 However, it's use in conjuntion with this module is very much not recommended, and in fact very 
245 discouraged. The recommended approach is to instead use the supplied C<next::method> feature, see
246 more details on it's usage above.
247
248 =item Changing C<@ISA>.
249
250 It is the author's opinion that changing C<@ISA> at runtime is pure insanity anyway. However, people
251 do it, so I must caveat. Any changes to the C<@ISA> will not be reflected in the MRO calculated by this
252 module, and therefor probably won't even show up. If you do this, you will need to call C<reinitialize> 
253 in order to recalulate B<all> method dispatch tables. See the C<reinitialize> documentation and an example
254 in F<t/20_reinitialize.t> for more information.
255
256 =item Adding/deleting methods from class symbol tables.
257
258 This module calculates the MRO for each requested class by interogatting the symbol tables of said classes. 
259 So any symbol table manipulation which takes place after our INIT phase is run will not be reflected in 
260 the calculated MRO. Just as with changing the C<@ISA>, you will need to call C<reinitialize> for any 
261 changes you make to take effect.
262
263 =item Calling C<next::method> from methods defined outside the class
264
265 There is an edge case when using C<next::method> from within a subroutine which was created in a different 
266 module than the one it is called from. It sounds complicated, but it really isn't. Here is an example which 
267 will not work correctly:
268
269   *Foo::foo = sub { (shift)->next::method(@_) };
270
271 The problem exists because the anonymous subroutine being assigned to the glob C<*Foo::foo> will show up 
272 in the call stack as being called C<__ANON__> and not C<foo> as you might expect. Since C<next::method> 
273 uses C<caller> to find the name of the method it was called in, it will fail in this case. 
274
275 But fear not, there is a simple solution. The module C<Sub::Name> will reach into the perl internals and 
276 assign a name to an anonymous subroutine for you. Simply do this:
277     
278   use Sub::Name 'subname';
279   *Foo::foo = subname 'Foo::foo' => sub { (shift)->next::method(@_) };
280
281 and things will Just Work. Of course this is not always possible to do, but to be honest, I just can't 
282 manage to find a workaround for it, so until someone gives me a working patch this will be a known 
283 limitation of this module.
284
285 =back
286
287 =head1 CODE COVERAGE
288
289 I use B<Devel::Cover> to test the code coverage of my tests, below is the B<Devel::Cover> report on this 
290 module's test suite.
291
292  ---------------------------- ------ ------ ------ ------ ------ ------ ------
293  File                           stmt   bran   cond    sub    pod   time  total
294  ---------------------------- ------ ------ ------ ------ ------ ------ ------
295  Class/C3.pm                    98.3   84.4   80.0   96.2  100.0   98.4   94.4
296  ---------------------------- ------ ------ ------ ------ ------ ------ ------
297  Total                          98.3   84.4   80.0   96.2  100.0   98.4   94.4
298  ---------------------------- ------ ------ ------ ------ ------ ------ ------
299
300 =head1 SEE ALSO
301
302 =head2 The original Dylan paper
303
304 =over 4
305
306 =item L<http://www.webcom.com/haahr/dylan/linearization-oopsla96.html>
307
308 =back
309
310 =head2 The prototype Perl 6 Object Model uses C3
311
312 =over 4
313
314 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel/>
315
316 =back
317
318 =head2 Parrot now uses C3
319
320 =over 4
321
322 =item L<http://aspn.activestate.com/ASPN/Mail/Message/perl6-internals/2746631>
323
324 =item L<http://use.perl.org/~autrijus/journal/25768>
325
326 =back
327
328 =head2 Python 2.3 MRO related links
329
330 =over 4
331
332 =item L<http://www.python.org/2.3/mro.html>
333
334 =item L<http://www.python.org/2.2.2/descrintro.html#mro>
335
336 =back
337
338 =head2 C3 for TinyCLOS
339
340 =over 4
341
342 =item L<http://www.call-with-current-continuation.org/eggs/c3.html>
343
344 =back 
345
346 =head1 ACKNOWLEGEMENTS
347
348 =over 4
349
350 =item Thanks to Matt S. Trout for using this module in his module L<DBIx::Class> 
351 and finding many bugs and providing fixes.
352
353 =item Thanks to Justin Guenther for making C<next::method> more robust by handling 
354 calls inside C<eval> and anon-subs.
355
356 =item Thanks to Robert Norris for adding support for C<next::can> and 
357 C<maybe::next::method>.
358
359 =back
360
361 =head1 AUTHOR
362
363 Stevan Little, E<lt>stevan@iinteractive.comE<gt>
364
365 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
366
367 =head1 COPYRIGHT AND LICENSE
368
369 Copyright 2005, 2006 by Infinity Interactive, Inc.
370
371 L<http://www.iinteractive.com>
372
373 This library is free software; you can redistribute it and/or modify
374 it under the same terms as Perl itself. 
375
376 =cut