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>
26 # use this for debugging ...
27 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
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();
61 ## functions for applying C3 to classes
63 sub _calculate_method_dispatch_tables {
64 foreach my $class (keys %MRO) {
65 _calculate_method_dispatch_table($class);
69 sub _calculate_method_dispatch_table {
72 my @MRO = calculateMRO($class);
73 $MRO{$class} = { MRO => \@MRO };
76 # we do @MRO[1 .. $#MRO] here because it
77 # makes no sense to interogate the class
78 # which you are calculating for.
79 foreach my $local (@MRO[1 .. $#MRO]) {
80 foreach my $method (grep { defined &{"${local}::$_"} } keys %{"${local}::"}) {
81 # skip if already overriden in local class
82 next unless !defined *{"${class}::$method"}{CODE};
84 orig => "${local}::$method",
85 code => \&{"${local}::$method"}
86 } unless exists $methods{$method};
89 # now stash them in our %MRO table
90 $MRO{$class}->{methods} = \%methods;
93 sub _apply_method_dispatch_tables {
94 foreach my $class (keys %MRO) {
95 _apply_method_dispatch_table($class);
99 sub _apply_method_dispatch_table {
102 foreach my $method (keys %{$MRO{$class}->{methods}}) {
103 *{"${class}::$method"} = $MRO{$class}->{methods}->{$method}->{code};
107 ## functions for calculating C3 MRO
109 # this function is a perl-port of the
110 # python code on this page:
111 # http://www.python.org/2.3/mro.html
116 # remove all empty seqences
117 my @nonemptyseqs = (map { (@{$_} ? $_ : ()) } @seqs);
118 # return the list if we have no more no-empty sequences
119 return @res if not @nonemptyseqs;
120 my $cand; # a canidate ..
121 foreach my $seq (@nonemptyseqs) {
122 $cand = $seq->[0]; # get the head of the list
124 foreach my $sub_seq (@nonemptyseqs) {
125 # XXX - this is instead of the python "in"
126 my %in_tail = (map { $_ => 1 } @{$sub_seq}[ 1 .. $#{$sub_seq} ]);
128 # jump out as soon as we find one matching
129 # there is no reason not too. However, if
130 # we find one, then just remove the '&& last'
131 $nothead++ && last if exists $in_tail{$cand};
133 last unless $nothead; # leave the loop with our canidate ...
134 $cand = undef; # otherwise, reject it ...
136 die "Inconsistent hierarchy" if not $cand;
138 # now loop through our non-empties and pop
139 # off the head if it matches our canidate
140 foreach my $seq (@nonemptyseqs) {
141 shift @{$seq} if $seq->[0] eq $cand;
150 [ $class ], # the class we are linearizing
151 (map { [ calculateMRO($_) ] } @{"${class}::ISA"}), # the MRO of all the superclasses
152 [ @{"${class}::ISA"} ] # a list of all the superclasses
164 Class::C3 - A pragma to use the C3 method resolution order algortihm
170 sub hello { 'A::hello' }
180 sub hello { 'C::hello' }
186 # Classic Diamond MI pattern
195 print join ', ' => Class::C3::calculateMRO('Diamond_D') # prints D, B, C, A
197 print D->hello() # prints 'C::hello' instead of the standard p5 'A::hello'
199 D->can('hello')->(); # can() also works correctly
200 UNIVERSAL::can('D', 'hello'); # as does UNIVERSAL::can()
204 This is currently an experimental pragma to change Perl 5's standard method resolution order
205 from depth-first left-to-right (a.k.a - pre-order) to the more sophisticated C3 method resolution
210 C3 is the name of an algorithm which aims to provide a sane method resolution order under multiple
211 inheritence. It was first introduced in the langauge Dylan (see links in the L<SEE ALSO> section),
212 and then later adopted as the prefered MRO (Method Resolution Order) for the new-style classes in
213 Python 2.3. Most recently it has been adopted as the 'canonical' MRO for Perl 6 classes, and the
214 default MRO for Parrot objects as well.
216 =head2 How does C3 work.
218 C3 works by always preserving local precendence ordering. This essentially means that no class will
219 appear before any of it's subclasses. Take the classic diamond inheritence pattern for instance:
227 The standard Perl 5 MRO would be (D, B, A, C). The result being that B<A> appears before B<C>, even
228 though B<C> is the subclass of B<A>. The C3 MRO algorithm however, produces the following MRO
229 (D, B, C, A), which does not have this same issue.
231 This example is fairly trival, for more complex examples and a deeper explaination, see the links in
232 the L<SEE ALSO> section.
234 =head2 How does this module work?
236 This module uses a technique similar to Perl 5's method caching. During the INIT phase, this module
237 calculates the MRO of all the classes which called C<use Class::C3>. It then gathers information from
238 the symbol tables of each of those classes, and builds a set of method aliases for the correct
239 dispatch ordering. Once all these C3-based method tables are created, it then adds the method aliases
240 into the local classes symbol table.
242 The end result is actually classes with pre-cached method dispatch. However, this caching does not
243 do well if you start changing your C<@ISA> or messing with class symbol tables, so you should consider
244 your classes to be effectively closed. See the L<CAVEATS> section for more details.
246 =head1 OPTIONAL LOWERCASE PRAGMA
248 This release also includes an optional module B<c3> in the F<opt/> folder. I did not include this in
249 the regular install since lowercase module names are considered I<"bad"> by some people. However I
250 think that code looks much nicer like this:
260 But hey, it's your choice, thats why it is optional.
266 =item B<calculateMRO ($class)>
268 Given a C<$class> this will return an array of class names in the proper C3 method resolution order.
272 This can be used to initalize the C3 method dispatch tables. You need to call this if you are running
273 under mod_perl, or in any other environment which does not run the INIT phase of the perl compiler.
276 This can B<not> be used to re-load the dispatch tables for all classes. This is because it does not first
277 return the classes to their virginal state, which would need to happen in order for the dispatch tables
278 to be properly reloaded.
284 Let me first say, this is an experimental module, and so it should not be used for anything other
285 then other experimentation for the time being.
287 That said, it is the authors intention to make this into a completely usable and production stable
288 module if possible. Time will tell.
290 And now, onto the caveats.
294 =item Use of C<SUPER::>.
296 The idea of C<SUPER::> under multiple inheritence is ambigious, and generally not recomended anyway.
297 However, it's use in conjuntion with this module is very much not recommended, and in fact very
298 discouraged. In the future I plan to support a C<NEXT::> style interface to be used to move to the
299 next most appropriate method in the MRO.
301 =item Changing C<@ISA>.
303 It is the author's opinion that changing C<@ISA> at runtime is pure insanity anyway. However, people
304 do it, so I must caveat. Any changes to the C<@ISA> will not be reflected in the MRO calculated by this
305 module, and therefor probably won't even show up. I am considering some kind of C<recalculateMRO> function
306 which can be used to recalculate the MRO on demand at runtime, but that is still off in the future.
308 =item Adding/deleting methods from class symbol tables.
310 This module calculates the MRO for each requested class during the INIT phase by interogatting the symbol
311 tables of said classes. So any symbol table manipulation which takes place after our INIT phase is run will
312 not be reflected in the calculated MRO.
322 You can never have enough tests :)
324 I need to convert the other MRO and class-precendence-list related tests from the Perl6-MetaModel (see link
325 in L<SEE ALSO>). In addition, I need to add some method checks to these tests as well.
327 =item call-next-method / NEXT:: / next METHOD
329 I am contemplating some kind of psudeo-package which can dispatch to the next most relevant method in the
330 MRO. This should not be too hard to implement when the time comes.
334 This being Perl, it would be remiss of me to force people to close thier classes at runtime. So I need to
335 develop a means for recalculating the MRO for a given class.
341 =head2 The original Dylan paper
345 =item L<http://www.webcom.com/haahr/dylan/linearization-oopsla96.html>
349 =head2 The prototype Perl 6 Object Model uses C3
353 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel/>
357 =head2 Parrot now uses C3
361 =item L<http://aspn.activestate.com/ASPN/Mail/Message/perl6-internals/2746631>
363 =item L<http://use.perl.org/~autrijus/journal/25768>
367 =head2 Python 2.3 MRO related links
371 =item L<http://www.python.org/2.3/mro.html>
373 =item L<http://www.python.org/2.2.2/descrintro.html#mro>
377 =head2 C3 for TinyCLOS
381 =item L<http://www.call-with-current-continuation.org/eggs/c3.html>
387 Stevan Little, E<lt>stevan@iinteractive.comE<gt>
389 =head1 COPYRIGHT AND LICENSE
391 Copyright 2005 by Infinity Interactive, Inc.
393 L<http://www.iinteractive.com>
395 This library is free software; you can redistribute it and/or modify
396 it under the same terms as Perl itself.