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