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