2011-10-09 156 views
1

對於我在ANTLR中的語法,我的java代碼可以捕獲並打印包含「$」的輸入的錯誤。在我的實施中,我需要打印出成功輸入的「成功」。所以,我按照我的Java代碼,大於0爲我的情況下,輸入錯誤

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回報數字。對於「int i;」,輸出只是;

parsing successful 

當我運行我的代碼,如int $一個輸入我;, java代碼打印出錯誤消息「解析成功」,因爲getNumberofSyntaxErrors()返回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*/ 

回答

1

詞法分析器(或分析器)可能試圖從(輕微)錯誤中恢復並繼續進行標記或解析。如果你想在發生某些非法字符時終止,最簡單的方法是創建某種「貫通」規則,放在所有詞法分析器規則的末尾,如果沒有上面的詞法分析器規則匹配,這些規則將匹配,並且讓這個規則拋出一個例外:

grammar T; 

// parser rules 

// lexer rules 

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

巴特,非常感謝。 –

+0

不客氣John。 –