Limited double dispatch for ADTs #5909
Labels
Area-Language Design
Resolution-Won't Fix
A real bug, but Triage feels that the issue is not impactful enough to spend time on.
Right now the simulation of double dispatch is very cumbersome, you have to provide a visitor method for each derived class in the base class and so on. For example, this is what it takes to implement a virtual operator:
But if C#7 is to have compiler-verified closed inheritance hierarchies (#188), why not automate that?
For example, you could write
and C# would perform the following analysis:
M
marked withDoubleDispatchAttribute
must be declared in asealed abstract
class (BaseReceiver
) and its first argument must be asealed abstract
class as well (BaseArgument
) (BaseReceiver
andBaseArgument
can be the same class, as in the example above).M
in derived classes ofBaseReceiver
can be covariant on their first argument.BaseReceiver
andBaseArgument
must have an implementation. IfBaseReceiver.M(BaseArgument, other_args...)
is declared abstract, it is redefined to throw an exception (otherwise the program won't compile), but this redefinition doesn't count as an implementation for this step.M
is moved into the appropriate child ofBaseArgument
with a mangled nameMMangled
and swapped receiver and first argument.BaseReceiver
inheritance tree receives an implementation ofM(BaseArgument baseArgument, other_args...)
with the same bodyreturn baseArgument.MMangled(this, other_args...);
.Some examples where this would be useful.
Pattern + Pattern
producesnew Sequence(Pattern, Pattern)
, butLiteralPattern + LiteralPattern
producesnew LiteralPattern(lhs.Text + rhs.Text)
;Pattern | Pattern
producesnew Choice(Pattern, Pattern)
, butPattern | Choice
producesnew Choice(Pattern, Choice)
(a different constructor).State
producesIEnumerable<Decision> PossibleDecisions()
and has aState Proceed(Decision decision)
method.Proceed
could use explicit pattern matching to enumerate all allowed decisions, but since each decision-taking method is relatively lengthy, they have to be split into separate methods anyway and choosing between them is a housekeeping task best delegated to the compiler.The text was updated successfully, but these errors were encountered: