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