根据“The Definitive ANTLR 4 Reference”一书,我尝试在 Eclipse 中运行 ArrayInit.g4 示例。我已经成功生成了必要的 java 文件和其他文件,但是当我运行示例并向控制台输入值并按 Enter 键时,什么也没有发生(第 29 和 30 页)。
ArrayInit.g4
/** Grammars always start with a grammar header. This grammar is called
* ArrayInit and must match the filename: ArrayInit.g4
*/
grammar ArrayInit;
@header
{
package com.foo.bar;
}
/** A rule called init that matches comma-separated values between {...}. */
init : '{' value (',' value)* '}' ; // must match at least one value
/** A value can be either a nested array/struct or a simple integer (INT) */
value : init
| INT
;
// parser rules start with lowercase letters, lexer rules with uppercase
INT : [0-9]+ ; // Define token INT as one or more digits
WS : [ \t\r\n]+ -> skip ;
Main.java
package com.foo.bar;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
public class Main
{
public static void main(String[] args) throws Exception
{
// create a CharStream that reads from standard input
ANTLRInputStream input = new ANTLRInputStream(System.in);
// create a lexer that feeds off of input CharStream
ArrayInitLexer lexer = new ArrayInitLexer(input);
// create a buffer of tokens pulled from the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);
// create a parser that feeds off the tokens buffer
ArrayInitParser parser = new ArrayInitParser(tokens);
ParseTree tree = parser.init(); // begin parsing at init rule
// Create a generic parse tree walker that can trigger callbacks
ParseTreeWalker walker = new ParseTreeWalker();
// Walk the tree created during the parse, trigger callbacks
walker.walk(new ShortToUnicodeString(), tree);
System.out.println(); // print a \n after translation
}
}
进入控制台: {99, 3, 451}
预期输出: “\u0063\u0003\u01c3”
最佳答案
输入 {99, 3, 451} 后,按 Enter 键换行,然后按 ctrl + Z(至少在 Windows 上)表示您已完成输入,然后就可以了。 最终,在本书中,您将看到“10.1 使用语法操作构建计算器”和副标题“构建交互式计算器”,在那里您将找到一些提供键盘输入的更好方法。
关于java - ANTLR4 项目不会在 Eclipse 中显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193144/