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