Skip to content Skip to sidebar Skip to footer

Antlr4 Javascript Target - Issue With Visitor And Labeled Alternative

I'm using antlr4 (4.5.3) with Javascript target, and trying to implement a visitor. Following the antlr4 book's calculator example (great book BTW) I'm trying to create a similar g

Solution 1:

I believed this is a bug. In runtime source code, ParseTreeVisitor.visit in the latest javascript runtime(4.5.2) is a bit different from python2 version(4.5.3). In python2 version, ParseTreeVisitor.visit leverage RuleContext.accept method to trigger different visitor events. I assumed developers of Antlr4 forgot to update javascript runtime.

There is quick workaround.

antlr4/tree/Tree.js

ParseTreeVisitor.prototype.visit = function(ctx) {
    //if (Utils.isArray(ctx)) {
    //  var self = this;
    //return ctx.map(function(child) { return visitAtom(self, child)});
    // } else {
    //return visitAtom(this, ctx);
    // }
    return ctx.accept(this)
};

There is a better way which doesn't modify library function.

ValidatorVisitor.prototype.visitExpr = function(ctx) {
    return ctx.accept(this);
}

Solution 2:

I believe that this problem has been fixed in antlr 4.7:

ParseTreeVisitor.prototype.visit = function(ctx) {
    if (Array.isArray(ctx)) {
        return ctx.map(function(child) {
            return child.accept(this);
        }, this);
    } else {
        return ctx.accept(this);
    }
};

Post a Comment for "Antlr4 Javascript Target - Issue With Visitor And Labeled Alternative"