applying patch from Robert Norris for next::can
[gitmo/Class-C3.git] / lib / Class / C3.pm
1
2 package Class::C3;
3
4 use strict;
5 use warnings;
6
7 use Scalar::Util 'blessed';
8 use Algorithm::C3;
9
10 our $VERSION = '0.12';
11
12 # this is our global stash of both 
13 # MRO's and method dispatch tables
14 # the structure basically looks like
15 # this:
16 #
17 #   $MRO{$class} = {
18 #      MRO => [ <class precendence list> ],
19 #      methods => {
20 #          orig => <original location of method>,
21 #          code => \&<ref to original method>
22 #      },
23 #      has_overload_fallback => (1 | 0)
24 #   }
25 #
26 our %MRO;
27
28 # use these for debugging ...
29 sub _dump_MRO_table { %MRO }
30 our $TURN_OFF_C3 = 0;
31
32 sub import {
33     my $class = caller();
34     # skip if the caller is main::
35     # since that is clearly not relevant
36     return if $class eq 'main';
37     return if $TURN_OFF_C3;
38     # make a note to calculate $class 
39     # during INIT phase
40     $MRO{$class} = undef unless exists $MRO{$class};
41 }
42
43 ## initializers
44
45 sub initialize {
46     # why bother if we don't have anything ...
47     return unless keys %MRO;
48     _calculate_method_dispatch_tables();
49     _apply_method_dispatch_tables();
50     %next::METHOD_CACHE = ();
51 }
52
53 sub uninitialize {
54     # why bother if we don't have anything ...
55     return unless keys %MRO;    
56     _remove_method_dispatch_tables();    
57     %next::METHOD_CACHE = ();
58 }
59
60 sub reinitialize {
61     uninitialize();
62     # clean up the %MRO before we re-initialize
63     $MRO{$_} = undef foreach keys %MRO;
64     initialize();
65 }
66
67 ## functions for applying C3 to classes
68
69 sub _calculate_method_dispatch_tables {
70     foreach my $class (keys %MRO) {
71         _calculate_method_dispatch_table($class);
72     }
73 }
74
75 sub _calculate_method_dispatch_table {
76     my $class = shift;
77     no strict 'refs';
78     my @MRO = calculateMRO($class);
79     $MRO{$class} = { MRO => \@MRO };
80     my $has_overload_fallback = 0;
81     my %methods;
82     # NOTE: 
83     # we do @MRO[1 .. $#MRO] here because it
84     # makes no sense to interogate the class
85     # which you are calculating for. 
86     foreach my $local (@MRO[1 .. $#MRO]) {
87         # if overload has tagged this module to 
88         # have use "fallback", then we want to
89         # grab that value 
90         $has_overload_fallback = ${"${local}::()"} 
91             if defined ${"${local}::()"};
92         foreach my $method (grep { defined &{"${local}::$_"} } keys %{"${local}::"}) {
93             # skip if already overriden in local class
94             next unless !defined *{"${class}::$method"}{CODE};
95             $methods{$method} = {
96                 orig => "${local}::$method",
97                 code => \&{"${local}::$method"}
98             } unless exists $methods{$method};
99         }
100     }    
101     # now stash them in our %MRO table
102     $MRO{$class}->{methods} = \%methods; 
103     $MRO{$class}->{has_overload_fallback} = $has_overload_fallback;        
104 }
105
106 sub _apply_method_dispatch_tables {
107     foreach my $class (keys %MRO) {
108         _apply_method_dispatch_table($class);
109     }     
110 }
111
112 sub _apply_method_dispatch_table {
113     my $class = shift;
114     no strict 'refs';
115     ${"${class}::()"} = $MRO{$class}->{has_overload_fallback}
116         if $MRO{$class}->{has_overload_fallback};
117     foreach my $method (keys %{$MRO{$class}->{methods}}) {
118         *{"${class}::$method"} = $MRO{$class}->{methods}->{$method}->{code};
119     }    
120 }
121
122 sub _remove_method_dispatch_tables {
123     foreach my $class (keys %MRO) {
124         _remove_method_dispatch_table($class);
125     }       
126 }
127
128 sub _remove_method_dispatch_table {
129     my $class = shift;
130     no strict 'refs';
131     delete ${"${class}::"}{"()"} if $MRO{$class}->{has_overload_fallback};    
132     foreach my $method (keys %{$MRO{$class}->{methods}}) {
133         delete ${"${class}::"}{$method}
134             if defined *{"${class}::${method}"}{CODE} && 
135                (*{"${class}::${method}"}{CODE} eq $MRO{$class}->{methods}->{$method}->{code});       
136     }   
137 }
138
139 ## functions for calculating C3 MRO
140
141 sub calculateMRO {
142     my ($class) = @_;
143     return Algorithm::C3::merge($class, sub { 
144         no strict 'refs'; 
145         @{$_[0] . '::ISA'};
146     });
147 }
148
149 package  # hide me from PAUSE
150     next; 
151
152 use strict;
153 use warnings;
154
155 use Scalar::Util 'blessed';
156
157 our $VERSION = '0.05';
158
159 our %METHOD_CACHE;
160
161 sub _find {
162     my $level = 2;
163     my ($method_caller, $label, @label);
164     while ($method_caller = (caller($level++))[3]) {
165       @label = (split '::', $method_caller);
166       $label = pop @label;
167       last unless
168         $label eq '(eval)' ||
169         $label eq '__ANON__';
170     }
171     my $caller   = join '::' => @label;    
172     my $self     = $_[0];
173     my $class    = blessed($self) || $self;
174     
175     return $METHOD_CACHE{"$class|$caller|$label"} ||= do {
176         
177         my @MRO = Class::C3::calculateMRO($class);
178         
179         my $current;
180         while ($current = shift @MRO) {
181             last if $caller eq $current;
182         }
183         
184         no strict 'refs';
185         my $found;
186         foreach my $class (@MRO) {
187             next if (defined $Class::C3::MRO{$class} && 
188                      defined $Class::C3::MRO{$class}{methods}{$label});          
189             last if (defined ($found = *{$class . '::' . $label}{CODE}));
190         }
191         
192         die "No next::method '$label' found for $_[0]" if $_[1] && !$found;
193         
194         $found;
195     };
196 }
197
198 sub method { goto &{_find($_[0], 1)} }
199
200 sub can { return _find($_[0], 0) ? 1 : 0 }
201
202 1;
203
204 __END__
205
206 =pod
207
208 =head1 NAME
209
210 Class::C3 - A pragma to use the C3 method resolution order algortihm
211
212 =head1 SYNOPSIS
213
214     package A;
215     use Class::C3;     
216     sub hello { 'A::hello' }
217
218     package B;
219     use base 'A';
220     use Class::C3;     
221
222     package C;
223     use base 'A';
224     use Class::C3;     
225
226     sub hello { 'C::hello' }
227
228     package D;
229     use base ('B', 'C');
230     use Class::C3;    
231
232     # Classic Diamond MI pattern
233     #    <A>
234     #   /   \
235     # <B>   <C>
236     #   \   /
237     #    <D>
238
239     package main;
240     
241     # initializez the C3 module 
242     # (formerly called in INIT)
243     Class::C3::initialize();  
244
245     print join ', ' => Class::C3::calculateMRO('Diamond_D') # prints D, B, C, A
246
247     print D->hello() # prints 'C::hello' instead of the standard p5 'A::hello'
248     
249     D->can('hello')->();          # can() also works correctly
250     UNIVERSAL::can('D', 'hello'); # as does UNIVERSAL::can()
251
252 =head1 DESCRIPTION
253
254 This is pragma to change Perl 5's standard method resolution order from depth-first left-to-right 
255 (a.k.a - pre-order) to the more sophisticated C3 method resolution order. 
256
257 =head2 What is C3?
258
259 C3 is the name of an algorithm which aims to provide a sane method resolution order under multiple
260 inheritence. It was first introduced in the langauge Dylan (see links in the L<SEE ALSO> section),
261 and then later adopted as the prefered MRO (Method Resolution Order) for the new-style classes in 
262 Python 2.3. Most recently it has been adopted as the 'canonical' MRO for Perl 6 classes, and the 
263 default MRO for Parrot objects as well.
264
265 =head2 How does C3 work.
266
267 C3 works by always preserving local precendence ordering. This essentially means that no class will 
268 appear before any of it's subclasses. Take the classic diamond inheritence pattern for instance:
269
270      <A>
271     /   \
272   <B>   <C>
273     \   /
274      <D>
275
276 The standard Perl 5 MRO would be (D, B, A, C). The result being that B<A> appears before B<C>, even 
277 though B<C> is the subclass of B<A>. The C3 MRO algorithm however, produces the following MRO 
278 (D, B, C, A), which does not have this same issue.
279
280 This example is fairly trival, for more complex examples and a deeper explaination, see the links in
281 the L<SEE ALSO> section.
282
283 =head2 How does this module work?
284
285 This module uses a technique similar to Perl 5's method caching. When C<Class::C3::initialize> is 
286 called, this module calculates the MRO of all the classes which called C<use Class::C3>. It then 
287 gathers information from the symbol tables of each of those classes, and builds a set of method 
288 aliases for the correct dispatch ordering. Once all these C3-based method tables are created, it 
289 then adds the method aliases into the local classes symbol table. 
290
291 The end result is actually classes with pre-cached method dispatch. However, this caching does not
292 do well if you start changing your C<@ISA> or messing with class symbol tables, so you should consider
293 your classes to be effectively closed. See the L<CAVEATS> section for more details.
294
295 =head1 OPTIONAL LOWERCASE PRAGMA
296
297 This release also includes an optional module B<c3> in the F<opt/> folder. I did not include this in 
298 the regular install since lowercase module names are considered I<"bad"> by some people. However I
299 think that code looks much nicer like this:
300
301   package MyClass;
302   use c3;
303   
304 The the more clunky:
305
306   package MyClass;
307   use Class::C3;
308   
309 But hey, it's your choice, thats why it is optional.
310
311 =head1 FUNCTIONS
312
313 =over 4
314
315 =item B<calculateMRO ($class)>
316
317 Given a C<$class> this will return an array of class names in the proper C3 method resolution order.
318
319 =item B<initialize>
320
321 This B<must be called> to initalize the C3 method dispatch tables, this module B<will not work> if 
322 you do not do this. It is advised to do this as soon as possible B<after> loading any classes which 
323 use C3. Here is a quick code example:
324   
325   package Foo;
326   use Class::C3;
327   # ... Foo methods here
328   
329   package Bar;
330   use Class::C3;
331   use base 'Foo';
332   # ... Bar methods here
333   
334   package main;
335   
336   Class::C3::initialize(); # now it is safe to use Foo and Bar
337
338 This function used to be called automatically for you in the INIT phase of the perl compiler, but 
339 that lead to warnings if this module was required at runtime. After discussion with my user base 
340 (the L<DBIx::Class> folks), we decided that calling this in INIT was more of an annoyance than a 
341 convience. I apologize to anyone this causes problems for (although i would very suprised if I had 
342 any other users other than the L<DBIx::Class> folks). The simplest solution of course is to define 
343 your own INIT method which calls this function. 
344
345 NOTE: 
346 This can B<not> be used to re-load the dispatch tables for all classes. Use C<reinitialize> for that.
347
348 =item B<uninitialize>
349
350 Calling this function results in the removal of all cached methods, and the restoration of the old Perl 5
351 style dispatch order (depth-first, left-to-right). 
352
353 =item B<reinitialize>
354
355 This effectively calls C<uninitialize> followed by C<initialize> the result of which is a reloading of
356 B<all> the calculated C3 dispatch tables. 
357
358 It should be noted that if you have a large class library, this could potentially be a rather costly 
359 operation.
360
361 =back
362
363 =head1 METHOD REDISPATCHING
364
365 It is always useful to be able to re-dispatch your method call to the "next most applicable method". This 
366 module provides a pseudo package along the lines of C<SUPER::> or C<NEXT::> which will re-dispatch the 
367 method along the C3 linearization. This is best show with an examples.
368
369   # a classic diamond MI pattern ...
370      <A>
371     /   \
372   <B>   <C>
373     \   /
374      <D>
375   
376   package A;
377   use c3; 
378   sub foo { 'A::foo' }       
379  
380   package B;
381   use base 'A'; 
382   use c3;     
383   sub foo { 'B::foo => ' . (shift)->next::method() }       
384  
385   package B;
386   use base 'A'; 
387   use c3;    
388   sub foo { 'C::foo => ' . (shift)->next::method() }   
389  
390   package D;
391   use base ('B', 'C'); 
392   use c3; 
393   sub foo { 'D::foo => ' . (shift)->next::method() }   
394   
395   print D->foo; # prints out "D::foo => B::foo => C::foo => A::foo"
396
397 A few things to note. First, we do not require you to add on the method name to the C<next::method> 
398 call (this is unlike C<NEXT::> and C<SUPER::> which do require that). This helps to enforce the rule 
399 that you cannot dispatch to a method of a different name (this is how C<NEXT::> behaves as well). 
400
401 The next thing to keep in mind is that you will need to pass all arguments to C<next::method> it can 
402 not automatically use the current C<@_>. 
403
404 If C<next::method> cannot find a next method to re-dispatch the call to, it will throw an exception.
405 You can use C<next::can> to see if C<next::method> will succeed before you call it like so:
406
407   $self->next::method(@_) if $self->next::can; 
408
409
410 There are some caveats about using C<next::method>, see below for those.
411
412 =head1 CAVEATS
413
414 This module used to be labeled as I<experimental>, however it has now been pretty heavily tested by 
415 the good folks over at L<DBIx::Class> and I am confident this module is perfectly usable for 
416 whatever your needs might be. 
417
418 But there are still caveats, so here goes ...
419
420 =over 4
421
422 =item Use of C<SUPER::>.
423
424 The idea of C<SUPER::> under multiple inheritence is ambigious, and generally not recomended anyway.
425 However, it's use in conjuntion with this module is very much not recommended, and in fact very 
426 discouraged. The recommended approach is to instead use the supplied C<next::method> feature, see
427 more details on it's usage above.
428
429 =item Changing C<@ISA>.
430
431 It is the author's opinion that changing C<@ISA> at runtime is pure insanity anyway. However, people
432 do it, so I must caveat. Any changes to the C<@ISA> will not be reflected in the MRO calculated by this
433 module, and therefor probably won't even show up. If you do this, you will need to call C<reinitialize> 
434 in order to recalulate B<all> method dispatch tables. See the C<reinitialize> documentation and an example
435 in F<t/20_reinitialize.t> for more information.
436
437 =item Adding/deleting methods from class symbol tables.
438
439 This module calculates the MRO for each requested class by interogatting the symbol tables of said classes. 
440 So any symbol table manipulation which takes place after our INIT phase is run will not be reflected in 
441 the calculated MRO. Just as with changing the C<@ISA>, you will need to call C<reinitialize> for any 
442 changes you make to take effect.
443
444 =item Calling C<next::method> from methods defined outside the class
445
446 There is an edge case when using C<next::method> from within a subroutine which was created in a different 
447 module than the one it is called from. It sounds complicated, but it really isn't. Here is an example which 
448 will not work correctly:
449
450   *Foo::foo = sub { (shift)->next::method(@_) };
451
452 The problem exists because the anonymous subroutine being assigned to the glob C<*Foo::foo> will show up 
453 in the call stack as being called C<__ANON__> and not C<foo> as you might expect. Since C<next::method> 
454 uses C<caller> to find the name of the method it was called in, it will fail in this case. 
455
456 But fear not, there is a simple solution. The module C<Sub::Name> will reach into the perl internals and 
457 assign a name to an anonymous subroutine for you. Simply do this:
458     
459   use Sub::Name 'subname';
460   *Foo::foo = subname 'Foo::foo' => sub { (shift)->next::method(@_) };
461
462 and things will Just Work. Of course this is not always possible to do, but to be honest, I just can't 
463 manage to find a workaround for it, so until someone gives me a working patch this will be a known 
464 limitation of this module.
465
466 =back
467
468 =head1 CODE COVERAGE
469
470 I use B<Devel::Cover> to test the code coverage of my tests, below is the B<Devel::Cover> report on this 
471 module's test suite.
472
473  ---------------------------- ------ ------ ------ ------ ------ ------ ------
474  File                           stmt   bran   cond    sub    pod   time  total
475  ---------------------------- ------ ------ ------ ------ ------ ------ ------
476  Class/C3.pm                    98.3   84.4   80.0   96.2  100.0   98.4   94.4
477  ---------------------------- ------ ------ ------ ------ ------ ------ ------
478  Total                          98.3   84.4   80.0   96.2  100.0   98.4   94.4
479  ---------------------------- ------ ------ ------ ------ ------ ------ ------
480
481 =head1 SEE ALSO
482
483 =head2 The original Dylan paper
484
485 =over 4
486
487 =item L<http://www.webcom.com/haahr/dylan/linearization-oopsla96.html>
488
489 =back
490
491 =head2 The prototype Perl 6 Object Model uses C3
492
493 =over 4
494
495 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel/>
496
497 =back
498
499 =head2 Parrot now uses C3
500
501 =over 4
502
503 =item L<http://aspn.activestate.com/ASPN/Mail/Message/perl6-internals/2746631>
504
505 =item L<http://use.perl.org/~autrijus/journal/25768>
506
507 =back
508
509 =head2 Python 2.3 MRO related links
510
511 =over 4
512
513 =item L<http://www.python.org/2.3/mro.html>
514
515 =item L<http://www.python.org/2.2.2/descrintro.html#mro>
516
517 =back
518
519 =head2 C3 for TinyCLOS
520
521 =over 4
522
523 =item L<http://www.call-with-current-continuation.org/eggs/c3.html>
524
525 =back 
526
527 =head1 ACKNOWLEGEMENTS
528
529 =over 4
530
531 =item Thanks to Matt S. Trout for using this module in his module L<DBIx::Class> 
532 and finding many bugs and providing fixes.
533
534 =item Thanks to Justin Guenther for making C<next::method> more robust by handling 
535 calls inside C<eval> and anon-subs.
536
537 =back
538
539 =head1 AUTHOR
540
541 Stevan Little, E<lt>stevan@iinteractive.comE<gt>
542
543 =head1 COPYRIGHT AND LICENSE
544
545 Copyright 2005, 2006 by Infinity Interactive, Inc.
546
547 L<http://www.iinteractive.com>
548
549 This library is free software; you can redistribute it and/or modify
550 it under the same terms as Perl itself. 
551
552 =cut