antlr / antlr4

ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.
http://antlr.org
BSD 3-Clause "New" or "Revised" License
17.14k stars 3.28k forks source link

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

Open tpluscode opened 2 days ago

tpluscode commented 2 days ago

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 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;
}
ericvergnaud commented 2 days ago

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

tpluscode commented 2 days ago

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

tpluscode commented 2 days ago

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