1

我正在使用这样的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]

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

为了您的帮助,在此先感谢。

4

1 回答 1

10

你的INT规则应该是fragment规则。照原样,表达式M1==2被标记为 [MEASURE, COMP, INT] 而不是您期望的 [MEASURE, COMP, REAL]。

fragment INT : [0-9]+;
于 2013-01-31T14:30:10.880 回答