Proper pluggable Method Resolution Orders. 'c3' is now implemented outside the
[p5sagit/p5-mst-13.2.git] / ext / mro / mro.pm
1 #      mro.pm
2 #
3 #      Copyright (c) 2007 Brandon L Black
4 #      Copyright (c) 2008 Larry Wall and others
5 #
6 #      You may distribute under the terms of either the GNU General Public
7 #      License or the Artistic License, as specified in the README file.
8 #
9 package mro;
10 use strict;
11 use warnings;
12
13 # mro.pm versions < 1.00 reserved for MRO::Compat
14 #  for partial back-compat to 5.[68].x
15 our $VERSION = '1.01';
16
17 sub import {
18     mro::set_mro(scalar(caller), $_[1]) if $_[1];
19 }
20
21 package # hide me from PAUSE
22     next;
23
24 sub can { mro::_nextcan($_[0], 0) }
25
26 sub method {
27     my $method = mro::_nextcan($_[0], 1);
28     goto &$method;
29 }
30
31 package # hide me from PAUSE
32     maybe::next;
33
34 sub method {
35     my $method = mro::_nextcan($_[0], 0);
36     goto &$method if defined $method;
37     return;
38 }
39
40 require XSLoader;
41 XSLoader::load('mro', $VERSION);
42
43 1;
44
45 __END__
46
47 =head1 NAME
48
49 mro - Method Resolution Order
50
51 =head1 SYNOPSIS
52
53   use mro; # enables next::method and friends globally
54
55   use mro 'dfs'; # enable DFS MRO for this class (Perl default)
56   use mro 'c3'; # enable C3 MRO for this class
57
58 =head1 DESCRIPTION
59
60 The "mro" namespace provides several utilities for dealing
61 with method resolution order and method caching in general.
62
63 These interfaces are only available in Perl 5.9.5 and higher.
64 See L<MRO::Compat> on CPAN for a mostly forwards compatible
65 implementation for older Perls.
66
67 =head1 OVERVIEW
68
69 It's possible to change the MRO of a given class either by using C<use
70 mro> as shown in the synopsis, or by using the L</mro::set_mro> function
71 below.  The functions in the mro namespace do not require loading the
72 C<mro> module, as they are actually provided by the core perl interpreter.
73
74 The special methods C<next::method>, C<next::can>, and
75 C<maybe::next::method> are not available until this C<mro> module
76 has been loaded via C<use> or C<require>.
77
78 =head1 The C3 MRO
79
80 In addition to the traditional Perl default MRO (depth first
81 search, called C<DFS> here), Perl now offers the C3 MRO as
82 well.  Perl's support for C3 is based on the work done in
83 Stevan Little's module L<Class::C3>, and most of the C3-related
84 documentation here is ripped directly from there.
85
86 =head2 What is C3?
87
88 C3 is the name of an algorithm which aims to provide a sane method
89 resolution order under multiple inheritance. It was first introduced in
90 the language Dylan (see links in the L</"SEE ALSO"> section), and then
91 later adopted as the preferred MRO (Method Resolution Order) for the
92 new-style classes in Python 2.3. Most recently it has been adopted as the
93 "canonical" MRO for Perl 6 classes, and the default MRO for Parrot objects
94 as well.
95
96 =head2 How does C3 work
97
98 C3 works by always preserving local precendence ordering. This essentially
99 means that no class will appear before any of its subclasses. Take, for
100 instance, the classic diamond inheritance pattern:
101
102      <A>
103     /   \
104   <B>   <C>
105     \   /
106      <D>
107
108 The standard Perl 5 MRO would be (D, B, A, C). The result being that B<A>
109 appears before B<C>, even though B<C> is the subclass of B<A>. The C3 MRO
110 algorithm however, produces the following order: (D, B, C, A), which does
111 not have this issue.
112
113 This example is fairly trivial; for more complex cases and a deeper
114 explanation, see the links in the L</"SEE ALSO"> section.
115
116 =head1 Functions
117
118 =head2 mro::get_linear_isa($classname[, $type])
119
120 Returns an arrayref which is the linearized MRO of the given class.
121 Uses whichever MRO is currently in effect for that class by default,
122 or the given MRO (either C<c3> or C<dfs> if specified as C<$type>).
123
124 The linearized MRO of a class is an ordered array of all of the
125 classes one would search when resolving a method on that class,
126 starting with the class itself.
127
128 If the requested class doesn't yet exist, this function will still
129 succeed, and return C<[ $classname ]>
130
131 Note that C<UNIVERSAL> (and any members of C<UNIVERSAL>'s MRO) are not
132 part of the MRO of a class, even though all classes implicitly inherit
133 methods from C<UNIVERSAL> and its parents.
134
135 =head2 mro::set_mro($classname, $type)
136
137 Sets the MRO of the given class to the C<$type> argument (either
138 C<c3> or C<dfs>).
139
140 =head2 mro::get_mro($classname)
141
142 Returns the MRO of the given class (either C<c3> or C<dfs>).
143
144 =head2 mro::get_isarev($classname)
145
146 Gets the C<mro_isarev> for this class, returned as an
147 arrayref of class names.  These are every class that "isa"
148 the given class name, even if the isa relationship is
149 indirect.  This is used internally by the MRO code to
150 keep track of method/MRO cache invalidations.
151
152 Currently, this list only grows, it never shrinks.  This
153 was a performance consideration (properly tracking and
154 deleting isarev entries when someone removes an entry
155 from an C<@ISA> is costly, and it doesn't happen often
156 anyways).  The fact that a class which no longer truly
157 "isa" this class at runtime remains on the list should be
158 considered a quirky implementation detail which is subject
159 to future change.  It shouldn't be an issue as long as
160 you're looking at this list for the same reasons the
161 core code does: as a performance optimization
162 over having to search every class in existence.
163
164 As with C<mro::get_mro> above, C<UNIVERSAL> is special.
165 C<UNIVERSAL> (and parents') isarev lists do not include
166 every class in existence, even though all classes are
167 effectively descendants for method inheritance purposes.
168
169 =head2 mro::is_universal($classname)
170
171 Returns a boolean status indicating whether or not
172 the given classname is either C<UNIVERSAL> itself,
173 or one of C<UNIVERSAL>'s parents by C<@ISA> inheritance.
174
175 Any class for which this function returns true is
176 "universal" in the sense that all classes potentially
177 inherit methods from it.
178
179 For similar reasons to C<isarev> above, this flag is
180 permanent.  Once it is set, it does not go away, even
181 if the class in question really isn't universal anymore.
182
183 =head2 mro::invalidate_all_method_caches()
184
185 Increments C<PL_sub_generation>, which invalidates method
186 caching in all packages.
187
188 =head2 mro::method_changed_in($classname)
189
190 Invalidates the method cache of any classes dependent on the
191 given class.  This is not normally necessary.  The only
192 known case where pure perl code can confuse the method
193 cache is when you manually install a new constant
194 subroutine by using a readonly scalar value, like the
195 internals of L<constant> do.  If you find another case,
196 please report it so we can either fix it or document
197 the exception here.
198
199 =head2 mro::get_pkg_gen($classname)
200
201 Returns an integer which is incremented every time a
202 real local method in the package C<$classname> changes,
203 or the local C<@ISA> of C<$classname> is modified.
204
205 This is intended for authors of modules which do lots
206 of class introspection, as it allows them to very quickly
207 check if anything important about the local properties
208 of a given class have changed since the last time they
209 looked.  It does not increment on method/C<@ISA>
210 changes in superclasses.
211
212 It's still up to you to seek out the actual changes,
213 and there might not actually be any.  Perhaps all
214 of the changes since you last checked cancelled each
215 other out and left the package in the state it was in
216 before.
217
218 This integer normally starts off at a value of C<1>
219 when a package stash is instantiated.  Calling it
220 on packages whose stashes do not exist at all will
221 return C<0>.  If a package stash is completely
222 deleted (not a normal occurence, but it can happen
223 if someone does something like C<undef %PkgName::>),
224 the number will be reset to either C<0> or C<1>,
225 depending on how completely package was wiped out.
226
227 =head2 next::method
228
229 This is somewhat like C<SUPER>, but it uses the C3 method
230 resolution order to get better consistency in multiple
231 inheritance situations.  Note that while inheritance in
232 general follows whichever MRO is in effect for the
233 given class, C<next::method> only uses the C3 MRO.
234
235 One generally uses it like so:
236
237   sub some_method {
238     my $self = shift;
239     my $superclass_answer = $self->next::method(@_);
240     return $superclass_answer + 1;
241   }
242
243 Note that you don't (re-)specify the method name.
244 It forces you to always use the same method name
245 as the method you started in.
246
247 It can be called on an object or a class, of course.
248
249 The way it resolves which actual method to call is:
250
251 =over 4
252
253 =item 1
254
255 First, it determines the linearized C3 MRO of
256 the object or class it is being called on.
257
258 =item 2
259
260 Then, it determines the class and method name
261 of the context it was invoked from.
262
263 =item 3
264
265 Finally, it searches down the C3 MRO list until
266 it reaches the contextually enclosing class, then
267 searches further down the MRO list for the next
268 method with the same name as the contextually
269 enclosing method.
270
271 =back
272
273 Failure to find a next method will result in an
274 exception being thrown (see below for alternatives).
275
276 This is substantially different than the behavior
277 of C<SUPER> under complex multiple inheritance.
278 (This becomes obvious when one realizes that the
279 common superclasses in the C3 linearizations of
280 a given class and one of its parents will not
281 always be ordered the same for both.)
282
283 B<Caveat>: Calling C<next::method> from methods defined outside the class:
284
285 There is an edge case when using C<next::method> from within a subroutine
286 which was created in a different module than the one it is called from. It
287 sounds complicated, but it really isn't. Here is an example which will not
288 work correctly:
289
290   *Foo::foo = sub { (shift)->next::method(@_) };
291
292 The problem exists because the anonymous subroutine being assigned to the
293 C<*Foo::foo> glob will show up in the call stack as being called
294 C<__ANON__> and not C<foo> as you might expect. Since C<next::method> uses
295 C<caller> to find the name of the method it was called in, it will fail in
296 this case. 
297
298 But fear not, there's a simple solution. The module C<Sub::Name> will
299 reach into the perl internals and assign a name to an anonymous subroutine
300 for you. Simply do this:
301
302   use Sub::Name 'subname';
303   *Foo::foo = subname 'Foo::foo' => sub { (shift)->next::method(@_) };
304
305 and things will Just Work.
306
307 =head2 next::can
308
309 This is similar to C<next::method>, but just returns either a code
310 reference or C<undef> to indicate that no further methods of this name
311 exist.
312
313 =head2 maybe::next::method
314
315 In simple cases, it is equivalent to:
316
317    $self->next::method(@_) if $self->next::can;
318
319 But there are some cases where only this solution
320 works (like C<goto &maybe::next::method>);
321
322 =head1 SEE ALSO
323
324 =head2 The original Dylan paper
325
326 =over 4
327
328 =item L<http://www.webcom.com/haahr/dylan/linearization-oopsla96.html>
329
330 =back
331
332 =head2 The prototype Perl 6 Object Model uses C3
333
334 =over 4
335
336 =item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel/>
337
338 =back
339
340 =head2 Parrot now uses C3
341
342 =over 4
343
344 =item L<http://aspn.activestate.com/ASPN/Mail/Message/perl6-internals/2746631>
345
346 =item L<http://use.perl.org/~autrijus/journal/25768>
347
348 =back
349
350 =head2 Python 2.3 MRO related links
351
352 =over 4
353
354 =item L<http://www.python.org/2.3/mro.html>
355
356 =item L<http://www.python.org/2.2.2/descrintro.html#mro>
357
358 =back
359
360 =head2 C3 for TinyCLOS
361
362 =over 4
363
364 =item L<http://www.call-with-current-continuation.org/eggs/c3.html>
365
366 =back 
367
368 =head2 Class::C3
369
370 =over 4
371
372 =item L<Class::C3>
373
374 =back
375
376 =head1 AUTHOR
377
378 Brandon L. Black, E<lt>blblack@gmail.comE<gt>
379
380 Based on Stevan Little's L<Class::C3>
381
382 =cut