7 use Scalar::Util 'blessed';
11 # this is our global stash of both
12 # MRO's and method dispatch tables
13 # the structure basically looks like
17 # MRO => [ <class precendence list> ],
19 # orig => <original location of method>,
20 # code => \&<ref to original method>
22 # has_overload_fallback => (1 | 0)
27 # use these for debugging ...
28 sub _dump_MRO_table { %MRO }
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
39 $MRO{$class} = undef unless exists $MRO{$class};
45 # this will not run under the following
48 # - require Class::C3;
49 # - eval "use Class::C3"
50 # in all those cases, you need to call
51 # the initialize() function manually
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 = ();
63 # why bother if we don't have anything ...
64 return unless keys %MRO;
65 _remove_method_dispatch_tables();
66 %next::METHOD_CACHE = ();
71 # clean up the %MRO before we re-initialize
72 $MRO{$_} = undef foreach keys %MRO;
76 ## functions for applying C3 to classes
78 sub _calculate_method_dispatch_tables {
79 foreach my $class (keys %MRO) {
80 _calculate_method_dispatch_table($class);
84 sub _calculate_method_dispatch_table {
87 my @MRO = calculateMRO($class);
88 $MRO{$class} = { MRO => \@MRO };
89 my $has_overload_fallback = 0;
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
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};
110 # now stash them in our %MRO table
111 $MRO{$class}->{methods} = \%methods;
112 $MRO{$class}->{has_overload_fallback} = $has_overload_fallback;
115 sub _apply_method_dispatch_tables {
116 foreach my $class (keys %MRO) {
117 _apply_method_dispatch_table($class);
121 sub _apply_method_dispatch_table {
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};
131 sub _remove_method_dispatch_tables {
132 foreach my $class (keys %MRO) {
133 _remove_method_dispatch_table($class);
137 sub _remove_method_dispatch_table {
140 delete ${"${class}::"}{"()"} if $MRO{$class}->{has_overload_fallback};
141 foreach my $method (keys %{$MRO{$class}->{methods}}) {
142 ${"${class}::"}{$method}{CODE} = undef
143 if defined ${"${class}::"}{$method}{CODE} &&
144 ${"${class}::"}{$method}{CODE} eq $MRO{$class}->{methods}->{$method}->{code};
148 ## functions for calculating C3 MRO
150 # this function is a perl-port of the
151 # python code on this page:
152 # http://www.python.org/2.3/mro.html
155 my $class_being_merged = $seqs[0]->[0];
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;
163 my $cand; # a canidate ..
164 foreach my $seq (@nonemptyseqs) {
165 $cand = $seq->[0]; # get the head of the list
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} ]);
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'
174 ++$nothead && last if exists $in_tail{$cand};
176 last unless $nothead; # leave the loop with our canidate ...
178 $cand = undef; # otherwise, reject it ...
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;
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;
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
202 package # hide me from PAUSE
208 use Scalar::Util 'blessed';
210 our $VERSION = '0.05';
217 while ($method_caller = (caller($level++))[3]) {
218 last unless $method_caller eq '(eval)';
220 my @label = (split '::', $method_caller);
221 #my @label = (split '::', (caller(1))[3]);
222 my $label = pop @label;
223 my $caller = join '::' => @label;
225 my $class = blessed($self) || $self;
227 goto &{ $METHOD_CACHE{"$class|$caller|$label"} ||= do {
229 my @MRO = Class::C3::calculateMRO($class);
232 while ($current = shift @MRO) {
233 last if $caller eq $current;
238 foreach my $class (@MRO) {
239 next if (defined $Class::C3::MRO{$class} &&
240 defined $Class::C3::MRO{$class}{methods}{$label});
241 last if (defined ($found = *{$class . '::' . $label}{CODE}));
244 die "No next::method '$label' found for $self" unless $found;
258 Class::C3 - A pragma to use the C3 method resolution order algortihm
264 sub hello { 'A::hello' }
274 sub hello { 'C::hello' }
280 # Classic Diamond MI pattern
289 print join ', ' => Class::C3::calculateMRO('Diamond_D') # prints D, B, C, A
291 print D->hello() # prints 'C::hello' instead of the standard p5 'A::hello'
293 D->can('hello')->(); # can() also works correctly
294 UNIVERSAL::can('D', 'hello'); # as does UNIVERSAL::can()
298 This is currently an experimental pragma to change Perl 5's standard method resolution order
299 from depth-first left-to-right (a.k.a - pre-order) to the more sophisticated C3 method resolution
304 C3 is the name of an algorithm which aims to provide a sane method resolution order under multiple
305 inheritence. It was first introduced in the langauge Dylan (see links in the L<SEE ALSO> section),
306 and then later adopted as the prefered MRO (Method Resolution Order) for the new-style classes in
307 Python 2.3. Most recently it has been adopted as the 'canonical' MRO for Perl 6 classes, and the
308 default MRO for Parrot objects as well.
310 =head2 How does C3 work.
312 C3 works by always preserving local precendence ordering. This essentially means that no class will
313 appear before any of it's subclasses. Take the classic diamond inheritence pattern for instance:
321 The standard Perl 5 MRO would be (D, B, A, C). The result being that B<A> appears before B<C>, even
322 though B<C> is the subclass of B<A>. The C3 MRO algorithm however, produces the following MRO
323 (D, B, C, A), which does not have this same issue.
325 This example is fairly trival, for more complex examples and a deeper explaination, see the links in
326 the L<SEE ALSO> section.
328 =head2 How does this module work?
330 This module uses a technique similar to Perl 5's method caching. During the INIT phase, this module
331 calculates the MRO of all the classes which called C<use Class::C3>. It then gathers information from
332 the symbol tables of each of those classes, and builds a set of method aliases for the correct
333 dispatch ordering. Once all these C3-based method tables are created, it then adds the method aliases
334 into the local classes symbol table.
336 The end result is actually classes with pre-cached method dispatch. However, this caching does not
337 do well if you start changing your C<@ISA> or messing with class symbol tables, so you should consider
338 your classes to be effectively closed. See the L<CAVEATS> section for more details.
340 =head1 OPTIONAL LOWERCASE PRAGMA
342 This release also includes an optional module B<c3> in the F<opt/> folder. I did not include this in
343 the regular install since lowercase module names are considered I<"bad"> by some people. However I
344 think that code looks much nicer like this:
354 But hey, it's your choice, thats why it is optional.
360 =item B<calculateMRO ($class)>
362 Given a C<$class> this will return an array of class names in the proper C3 method resolution order.
366 This can be used to initalize the C3 method dispatch tables. You need to call this if you are running
367 under mod_perl, or in any other environment which does not run the INIT phase of the perl compiler.
370 This can B<not> be used to re-load the dispatch tables for all classes. Use C<reinitialize> for that.
372 =item B<uninitialize>
374 Calling this function results in the removal of all cached methods, and the restoration of the old Perl 5
375 style dispatch order (depth-first, left-to-right).
377 =item B<reinitialize>
379 This effectively calls C<uninitialize> followed by C<initialize> the result of which is a reloading of
380 B<all> the calculated C3 dispatch tables.
382 It should be noted that if you have a large class library, this could potentially be a rather costly
387 =head1 METHOD REDISPATCHING
389 It is always useful to be able to re-dispatch your method call to the "next most applicable method". This
390 module provides a pseudo package along the lines of C<SUPER::> or C<NEXT::> which will re-dispatch the
391 method along the C3 linearization. This is best show with an examples.
393 # a classic diamond MI pattern ...
407 sub foo { 'B::foo => ' . (shift)->next::method() }
412 sub foo { 'C::foo => ' . (shift)->next::method() }
417 sub foo { 'D::foo => ' . (shift)->next::method() }
419 print D->foo; # prints out "D::foo => B::foo => C::foo => A::foo"
421 A few things to note. First, we do not require you to add on the method name to the C<next::method>
422 call (this is unlike C<NEXT::> and C<SUPER::> which do require that). This helps to enforce the rule
423 that you cannot dispatch to a method of a different name (this is how C<NEXT::> behaves as well).
425 The next thing to keep in mind is that you will need to pass all arguments to C<next::method> it can
426 not automatically use the current C<@_>.
430 Let me first say, this is an experimental module, and so it should not be used for anything other
431 then other experimentation for the time being.
433 That said, it is the authors intention to make this into a completely usable and production stable
434 module if possible. Time will tell.
436 And now, onto the caveats.
440 =item Use of C<SUPER::>.
442 The idea of C<SUPER::> under multiple inheritence is ambigious, and generally not recomended anyway.
443 However, it's use in conjuntion with this module is very much not recommended, and in fact very
444 discouraged. The recommended approach is to instead use the supplied C<next::method> feature, see
445 more details on it's usage above.
447 =item Changing C<@ISA>.
449 It is the author's opinion that changing C<@ISA> at runtime is pure insanity anyway. However, people
450 do it, so I must caveat. Any changes to the C<@ISA> will not be reflected in the MRO calculated by this
451 module, and therefor probably won't even show up. If you do this, you will need to call C<reinitialize>
452 in order to recalulate B<all> method dispatch tables. See the C<reinitialize> documentation and an example
453 in F<t/20_reinitialize.t> for more information.
455 =item Adding/deleting methods from class symbol tables.
457 This module calculates the MRO for each requested class during the INIT phase by interogatting the symbol
458 tables of said classes. So any symbol table manipulation which takes place after our INIT phase is run will
459 not be reflected in the calculated MRO. Just as with changing the C<@ISA>, you will need to call
460 C<reinitialize> for any changes you make to take effect.
470 You can never have enough tests :)
476 I use B<Devel::Cover> to test the code coverage of my tests, below is the B<Devel::Cover> report on this
479 ---------------------------- ------ ------ ------ ------ ------ ------ ------
480 File stmt bran cond sub pod time total
481 ---------------------------- ------ ------ ------ ------ ------ ------ ------
482 Class/C3.pm 98.6 88.6 75.0 96.0 100.0 70.4 95.2
483 ---------------------------- ------ ------ ------ ------ ------ ------ ------
484 Total 98.6 88.6 75.0 96.0 100.0 70.4 95.2
485 ---------------------------- ------ ------ ------ ------ ------ ------ ------
489 =head2 The original Dylan paper
493 =item L<http://www.webcom.com/haahr/dylan/linearization-oopsla96.html>
497 =head2 The prototype Perl 6 Object Model uses C3
501 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel/>
505 =head2 Parrot now uses C3
509 =item L<http://aspn.activestate.com/ASPN/Mail/Message/perl6-internals/2746631>
511 =item L<http://use.perl.org/~autrijus/journal/25768>
515 =head2 Python 2.3 MRO related links
519 =item L<http://www.python.org/2.3/mro.html>
521 =item L<http://www.python.org/2.2.2/descrintro.html#mro>
525 =head2 C3 for TinyCLOS
529 =item L<http://www.call-with-current-continuation.org/eggs/c3.html>
535 Stevan Little, E<lt>stevan@iinteractive.comE<gt>
537 =head1 COPYRIGHT AND LICENSE
539 Copyright 2005 by Infinity Interactive, Inc.
541 L<http://www.iinteractive.com>
543 This library is free software; you can redistribute it and/or modify
544 it under the same terms as Perl itself.