Antlr4-JS actions in grammar: how to access tokens

2019-05-21 14:47发布

问题:

I'm trying to adapt to JS target the Expr.g4 of the book. In this example, actions are directly in the grammar. They include utility functions defined in @parser::members , that are called in the rules.

The example works well in Java, but in its JS translation I have 2 problem: - getting the action function visible by the action rule - getting the tokens recognized in the function.

I finally manage to get this working formulation:

@parser::members {

  myeval =  function(left, op, right) {
        switch ( op ) {
            case Expr_jsParser.MUL : return left * right;
            case Expr_jsParser.DIV : return left / right;
            case Expr_jsParser.ADD : return left + right;
            case Expr_jsParser.SUB : return left - right;
        }
        return 0;
    };
}

( myeval is the action function. MUL, DIV, etc are the grammar tokens. Expr_jsParser is a class generated by Antlr) I'm pretty sure there is a cleaner way to do this, isn't it ?

回答1:

Eric Vergnaud (the JS guy of Antlr) tells me that it's the regular behavior. Simply, java accept skipping the prefix while JS does not.