Antlr4-JS 语法中的动作:如何访问令牌并定义 funcs ?(直接在java中,而不是在JS中) [英] Antlr4-JS actions in grammar: how to access tokens and define funcs ? (direct in java, not in JS)
问题描述
我正在尝试适应 JS 目标 本书的 Expr.g4.
在这个例子中,动作直接在语法中.它们包括在@parser::members 中定义的实用函数,这些函数在规则中被调用.
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.
该示例在 Java 中运行良好,但在其 JS 翻译中我有两个问题:
The example works well in Java, but in its JS translation I have 2 problems:
- 获取动作规则可见的动作函数
- 获取函数中识别的令牌.
我终于设法得到这个有效的公式:
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 是动作函数.MUL、DIV 等是语法标记.Expr_jsParser 是 Antlr 生成的类)
我很确定有一种更简洁的方法可以做到这一点,不是吗?
(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?
推荐答案
Eric Vergnaud(Antlr 的 JS 专家)告诉我这是常规行为.简单地说,Java 接受跳过 Expr_jsParser
前缀,而 JS 不接受.
Eric Vergnaud (the JS guy of Antlr) tells me that it's the regular behavior. Simply, Java accepts skipping the Expr_jsParser
prefix while JS does not.
这篇关于Antlr4-JS 语法中的动作:如何访问令牌并定义 funcs ?(直接在java中,而不是在JS中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!