antlr4 icon indicating copy to clipboard operation
antlr4 copied to clipboard

[TypeScript] Class Visitor defines instance member property visit, but extended class defines it as instance member function.

Open tpluscode opened this issue 1 year ago • 4 comments

The TypeScript target produces a visitor similar to the following:

export default class FooVisitor<Result> extends ParseTreeVisitor<Result> {
	/**
	 * Visit a parse tree produced by `FooParser.bar`.
	 * @param ctx the parse tree
	 * @return the visitor result
	 */
	visitBar?: (ctx: BarContext) => Result;
}

When overridden as shown in the docs, the code doesn't work (override is never called) and the compiler will show an error explaining the reason:

TS2425: Class FooVisitor<X> defines instance member property visitBar, but extended class CustomVisitor defines it as instance member function.

As a workaround, it is possible to switch to a property:

class CustomVisitor extends FooVisitor<X> {
  visitBar = (ctx: BarContext): X => {
    return new X()
  }
}

but I expect that the intent from the target is overloading, same as one would overload the visitor methods in plain JS target. To allow that, the target can be modified to

-export default class FooVisitor<Result> extends ParseTreeVisitor<Result> {
+export default abstract class FooVisitor<Result> extends ParseTreeVisitor<Result> {
	/**
	 * Visit a parse tree produced by `FooParser.bar`.
	 * @param ctx the parse tree
	 * @return the visitor result
	 */
-	visitBar?: (ctx: BarContext) => Result;
+	visitBar?(ctx: BarContext) => Result;
}

tpluscode avatar Oct 24 '24 11:10 tpluscode

Hi, thanks for this. Can you provide a pointer to the docs you are referring to?

ericvergnaud avatar Oct 24 '24 11:10 ericvergnaud

https://github.com/antlr/antlr4/blob/dev/doc/typescript-target.md#how-do-i-create-and-run-a-visitor

tpluscode avatar Oct 24 '24 12:10 tpluscode

For reference, here's an SO question which links to relevant TypeScript docs: https://stackoverflow.com/questions/44153378/typescript-abstract-optional-method

tpluscode avatar Oct 24 '24 12:10 tpluscode

This also prohibits from using super in child class methods. Obviously a bug, I wonder why it's not being fixed yet.

crabvk avatar Mar 13 '25 13:03 crabvk