gpt4 book ai didi

parsing - ANTLR 4 : Bad grammar and 'no viable alternative at input'

转载 作者:行者123 更新时间:2023-12-05 08:44:14 29 4
gpt4 key购买 nike

我正在这样使用 ANTLR 4:

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStream;

public class Builder
{
public static void main(String[] args)
{
CharStream input = new ANTLRInputStream("ON M1==2 && M3 == 5 && (M2 > 1 || M5 <= 5.0) "
+ "DO P5:42 P4:10");
ExprLexer lexer = new ExprLexer(input);
TokenStream tokens = new CommonTokenStream(lexer);
ExprParser parser = new ExprParser(tokens);
ExprParser.ExpressionContext uu = parser.expression();
for (int i = 0; i < uu.getChildCount(); ++i)
System.out.println(uu.getChild(i));
}
}

以及以下语法:

grammar Expr;
options
{
// antlr will generate java lexer and parser
language = Java;

}
WS : [ \t\r\n]+ -> skip ;
OP : '&&' | '||';
COMP : '==' | '<' | '>' | '<=' | '>=' | '!=';
INT : [0-9]+;
REAL : INT '.' INT | INT;

ACTION : 'P' INT ':' INT;
MEASURE : 'M' INT;

// ***************** parser rules:
cond : MEASURE COMP REAL;
condexpr : '(' condexpr ')' | cond OP condexpr | cond;
actionexpr : ACTION actionexpr | ACTION;
expression : 'ON' condexpr 'DO' actionexpr;

我有以下输出:

line 1:7 no viable alternative at input 'M1==2'
ON
[29]
DO
[31]

我认为我的语法有错误,但我没有看到。你有想法吗?

为了您的帮助,提前致谢。

最佳答案

您的INT 规则应该是片段 规则。实际上,表达式 M1==2 被标记为 [MEASURE, COMP, INT] 而不是您期望的 [MEASURE, COMP, REAL]。

fragment INT : [0-9]+;

关于parsing - ANTLR 4 : Bad grammar and 'no viable alternative at input' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14623058/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com