Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

readme.md example visitor does not compile #97

Open
kaby76 opened this issue Sep 16, 2024 · 1 comment
Open

readme.md example visitor does not compile #97

kaby76 opened this issue Sep 16, 2024 · 1 comment
Labels
possible-bug Could be a bug

Comments

@kaby76
Copy link

kaby76 commented Sep 16, 2024

From the readme.md:

antlr4ng/ReadMe.md

Lines 80 to 99 in e1984c4

```typescript
import { ExpressionVisitor } from "./generated/ExpressionVisitor.js";
class MyVisitor extends ExpressionVisitor<number> {
public visitAdd = (ctx: AddContext): number {
return this.visit(ctx.expression(0)) + this.visit(ctx.expression(1));
}
public visitMultiply = (ctx: MultiplyContext): number {
return this.visit(ctx.expression(0)) * this.visit(ctx.expression(1));
}
public visitNumber = (ctx: NumberContext): number {
return Number.parseInt(ctx.NUMBER().text);
}
}
const visitor = new MyVisitor();
const result = visitor.visit(tree);
```

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 mike-lischke added the possible-bug Could be a bug label Sep 17, 2024
@mike-lischke
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
possible-bug Could be a bug
Projects
None yet
Development

No branches or pull requests

2 participants