Tags
There are no tags for this page.
Attachments
Perl 6
SMOP Multi Sub Dispatch
Multi subs in Perl 6 support two features:
- lexical variants of outer-or-global multi subs
- variant disambiguation
What do they mean?
Lexical Variants
my multi foo (Foo $a) {...};
for 1..4 {
my multi foo (Bar $a) {...};
# foo(Bar) is visible here
}
# but not here
Variant Disambiguation
class A {};
class B is A {};
multi foo (A $a) { say 1 };
multi foo (B $a) { say 2 };
foo(A.new());
foo(B.new());
Most languages that support multi dispatch doesn't support this feature, this is usually seen as a compile-time error, since the two variant are ambiguous. But this is a very important feature to Perl 6, since that's how objects can overload most operators. Which means you need a disambiguation code to sort all the matching candidates.
How to make it work
The dispatching would implement the following steps:
- manual traversal of the lexical scope searching for variants: This is not a simple lookup because we need the variant declared in an inner scope not to hide the declaration in an outer scope.
- check if package CANDO this sub: sub dispatch is 'no strict', meaning that if the symbol is not found in the current lexical scope, it might be in the package.
- grep all the variants for ACCEPTS
- sort them according to a "pluggable disambiguation code"
- invoke the topmost variant on the sorted list
API
class MultiSub {
has @.variants;
}
module MultiSubDispatcher {
only sub lookup ($name, $capture, $lexpad, $package) --> Code {...}
only sub dispatch ($name, $capture, $lexpad, $package) --> Object {
lookup($name, $capture, $lexpad, $package).($capture);
}
}
role MultiVariantDisambiguator {
only sub disambiguate (*@variants) --> Code {...}
}
Room for optimization
Each variant declaration could hold a cache of all the outer declarations already sorted, meaning that it would just consume the first element of the lazy return of grep. Of course runtime declarations would drop the cache entirely and it would need to be rebuilt.
|