ANTLR引发错误但语法功能正常

时间:2014-10-05 05:48:25

标签: syntax-error antlr antlr4 rule

我有这个语法:

grammar Flow;

@header { import java.util.HashMap; }

@members { HashMap<String, String> vars = new HashMap<>(); }

WS:         (' '|'\n'|'\r'|'\t') -> skip;

flow:       (print|var)+ EOF;

print:      'print' (toPrint=PRINTABLE { System.out.println($toPrint.text); })|(id=ID {
    if (vars.containsKey($id.text)) {
        System.out.println(vars.get($id.text));
    } else {
        System.err.println("This variable is not assigned!");
    }
});

var:        'var' id=ID '=' val=PRINTABLE { vars.put($id.text, $val.text); };

PRINTABLE:  STRING|NUMBER|LETTER|DIGIT;

STRING:     '"' (.)*? '"';

fragment LETTER: ('a'..'z'|'A'..'Z');
fragment DIGIT:  ('0'..'9');

NUMBER:     DIGIT+ ('.' DIGIT+)?;

ID:         LETTER (LETTER|DIGIT)*;

当我调用启动规则&#39; flow&#39;并输入一些有效变量并尝试打印它,TestRig抛出错误:

第2:6行输出&#39;输出&#39;

但一切都很好。 如何阻止这个恼人的错误?

感谢您的反馈!

1 个答案:

答案 0 :(得分:0)

不是解决问题的方法,而是针对我的评论中提到的问题略微改进的语法版本:

grammar Flow;

@header { import java.util.HashMap; }

@members { HashMap<String, String> vars = new HashMap<>(); }

WS:         (' '|'\n'|'\r'|'\t') -> skip;

flow:       (print|var)+ EOF;

print:        'print' (toPrint=printable { System.out.println($toPrint.text); })
            | (id=ID {
                      if (vars.containsKey($id.text)) {
                         System.out.println(vars.get($id.text));
                       } else {
                          System.err.println("This variable is not assigned!");
                       }
                     }
              )
            ;

var:        'var' id=ID '=' val=printable { vars.put($id.text, $val.text); };

printable:  STRING|NUMBER|ID|NUMBER;

STRING:     '"' (.)*? '"';

NUMBER:     DIGIT+ ('.' DIGIT+)?;

ID:         LETTER (LETTER|DIGIT)*;

fragment LETTER: ('a'..'z'|'A'..'Z');
fragment DIGIT:  ('0'..'9');