I have an antlr4 grammar with dozens of rules. There’s code I want to run as the Visitor
enters each node, i.e. shared behaviour across all node types. For example, I might have a grammar like this…
lost : jack | kate;
jack : 'JACK';
kate : 'KATE';
…and a visitor like this (I’m using antlr4ts, so the generated code is in TypeScript)…
export default class MyVisitor extends VisitorInterface {
sharedBehaviour(ctx: ParseNode) {
// ...
}
visitLost(ctx: LostContext) {
this.sharedBehaviour(ctx);
// ...
}
visitJack(ctx: JackContext) {
this.sharedBehaviour(ctx);
// ...
}
visitKate(ctx: KateContext) {
this.sharedBehaviour(ctx);
// ...
}
}
How can I replicate this without copy/pasting this.sharedBehaviour(ctx)
into every single visitX
method?
Based on the docs, I thought I could maybe define a custom superclass for all the parse nodes, and in the accept(...)
method of my custom parse node, I could call visitor.sharedBehaviour(...)
. But I’m not sure how to add this sharedBehaviour(...)
method to the antlr-generated visitor interface (which I called VisitorInterface
above), so that it’s visible to the parse nodes. Also, I’d prefer to avoid messing with the code generation, and I thought there’d be an easier way to do this.
3