1
我想要一個簡單的計算器,並在C#中使用ANTLR運行。我有一個簡單的語法。問題是我的令牌流總是空出來的,我不明白爲什麼。我已經摘錄了我認爲是下面的關鍵代碼。我錯過了什麼?ANTLR標記流爲空 - 爲什麼?
SimpleCalc.g4:
grammar SimpleCalc;
options {
language=CSharp2;
}
tokens {
PLUS,
MINUS,
TIMES,
DIV
}
@members {
}
expr : term ((PLUS|MINUS) term)* ;
term : factor ((TIMES|DIV) factor)* ;
factor : NUMBER ;
DIV : '/';
PLUS : '+';
TIMES: '*';
MINUS: '-';
NUMBER : (DIGIT)+ {System.Console.WriteLine("Found number"); };
WHITESPACE: ('\t' | ' ' | '\r' | '\n' | '\u000C')+ -> skip ;
fragment DIGIT : '0'..'9';
中的方法做實際工作,或嘗試:
class Program {
public static void Main(string[] args) {
Run();
}
public static void Run() {
try {
Console.WriteLine("START");
RunTestCalculator();
Console.Write("DONE. Hit RETURN to exit: ");
} catch (Exception ex) {
Console.WriteLine("ERROR: " + ex);
Console.Write("Hit RETURN to exit: ");
}
Console.ReadLine();
}
public static void RunTestCalculator() {
AntlrInputStream inputStream = new AntlrInputStream(@" 9 + 3 ");
SimpleCalcLexer lex = new SimpleCalcLexer(inputStream);
CommonTokenStream tokens = new CommonTokenStream(lex);
var t = tokens.Get(0);
Console.WriteLine("t = " + t.ToString());
SimpleCalcParser parser = new SimpleCalcParser(tokens);
try {
var theExpr = parser.expr();
Console.WriteLine("found expr " + theExpr.ToString());
} catch (RecognitionException e) {
System.Console.WriteLine("EXCEPTION:");
System.Console.WriteLine(e.StackTrace);
}
}
}
控制檯輸出證明了上述方法執行,但令牌不包含任何東西:
START
ERROR: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: token index 0 out of range 0..-1
at Antlr4.Runtime.BufferedTokenStream.Get(Int32 i)
at AntlerTest.Program.RunTestCalculator() in c:\Users\William\Documents\Visual Studio 2012\Projects\AntlerTest\AntlerTest\Program.cs:line 32
at AntlerTest.Program.Run() in c:\Users\William\Documents\Visual Studio 2012\
Projects\AntlerTest\AntlerTest\Program.cs:line 19
Hit RETURN to exit: