ANTLR 异常处理与“$",Java [英] ANTLR exception handling with "$", Java

查看:29
本文介绍了ANTLR 异常处理与“$",Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我在 ANTLR 中的语法,我的 java 代码可以捕获并打印包含$"的输入的错误.在我的实现中,我需要打印出成功"才能成功输入.所以,我在我的 Java 代码中做了以下操作,

For my grammar in ANTLR, my java code can catch and print errors for inputs containing "$". In my implementation, I need to print out "success" for successful input. So, I do following in my java code,

CharStream charStream = new ANTLRFileStream(filePath);
myLexer lexer = new myLexer(charStream);
TokenStream tokens = new CommonTokenStream(lexer);
myParser parser = new myParser(tokens);

/*if there is an error throws an exception message*/
parser.program(); 

/*if there is an error find how many, if 0 then print success,*/
int errorsCount = parser.getNumberOfSyntaxErrors();
if(errorsCount == 0){
  System.out.println("parsing successful");
}

getNumberofSyntaxErrors 在我的例子中为错误的输入返回大于 0 的数字.对于int i;",输出只是;

getNumberofSyntaxErrors returns numbers greater than 0 for wrong inputs in my case. For "int i;", the output is just;

parsing successful 

当我为像 int $i; 这样的输入运行我的代码时,java 代码打印出带有解析成功"的错误消息,因为 getNumberofSyntaxErrors() 返回 0;

When I run my code for a input like int $i;, java code prints out error message with "parsing successful" because getNumberofSyntaxErrors() returns 0;

line 1:4 no viable alternative at character '$' /*this is what I expect to see*/
parsing successful /*this is not what i expect to see*/

推荐答案

可能词法分析器(或解析器)尝试从(小)错误中恢复并继续标记化或解析.如果您想在出现某些非法字符时终止,最简单的方法是创建某种失败"规则,该规则放置在所有词法分析器规则的末尾,如果上述词法分析器规则均不匹配,则该规则将匹配,并且让该规则抛出异常:

Possibly the lexer (or parser) tries to recover from (minor) errors and continues tokenizing or parsing. If you want to terminate whenever some illegal character occurs, the easiest is to create some sort of "fall-through" rule that is placed at the end of all your lexer rules which will match if none of the lexer rules above have matched, and let that rule throw an exception:

grammar T;

// parser rules

// lexer rules

/* last lexer rules */
FALL_THROUGH
  :  .  {throw new RuntimeException("Illegal character: " + getText());}
  ;

这篇关于ANTLR 异常处理与“$",Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆