mike-lischke / antlr4ng

Next Generation TypeScript runtime for ANTLR4
Other
87 stars 15 forks source link

readme.md example visitor does not compile #97

Open kaby76 opened 1 month ago

kaby76 commented 1 month ago

From the readme.md:

https://github.com/mike-lischke/antlr4ng/blob/e1984c4a8ba6cf8ff2e814666db74ff536345e03/ReadMe.md?plain=1#L80-L99

This code doesn't compile, tsc --version "Version 5.6.2". MyVisitor.ts:4:47 - error TS1005: '=>' expected. tree is undefined. *Context are all undefined. .text is used instead of .getText(). Also, visitStart() has to be define otherwise none of the other overrides are called, and "null" is returned.

The code should look something like this.

import { StartContext, ExpressionContext, MultiplyContext, DivideContext, AddContext, SubtractContext, NumberContext } from "./ExpressionParser.js";
import { ExpressionVisitor } from "./ExpressionVisitor.js";

export class MyVisitor extends ExpressionVisitor<number> {
  public visitStart = (ctx: StartContext) => {
    return this.visit(ctx.getChild(0));
  }

  public visitAdd = (ctx: AddContext) => {
    return this.visit(ctx.expression(0)) + this.visit(ctx.expression(1));
  }

  public visitMultiply = (ctx: MultiplyContext) => {
    return this.visit(ctx.expression(0)) * this.visit(ctx.expression(1));
  }

  public visitNumber = (ctx: NumberContext) => {
    return Number.parseInt(ctx.NUMBER().getText());
  }
}
mike-lischke commented 1 month ago

I'll add a test case for that in the unit tests.