语法:
grammar qwe;
query
: COLUMN OPERATOR value EOF
;
COLUMN
: [a-z_]+
;
OPERATOR
: ('='|'>'|'<')
;
SCALAR
: [a-z_]+
;
value
: SCALAR
;
WS : [ \t\r\n]+ -> skip ;
有相同的规则
COLUMN
和SCALAR
。 这里 我被建议使用 grun
别名。
我为我的 Ubuntu 安装了它。对于文件夹结构:
从项目
learning_antlr4
级别运行此代码:
grun qwe tokens -tokens < qwe/qwe.tokens
输出为空。
我做错了什么?别名保存在哪里?
假设您已设置 grun 别名(如果没有,请参阅本页顶部的快速入门https://www.antlr.org):
您想要的是查看 Lexer 处理您的输入生成的令牌流(不是您的
qwe.tokens
文件)
qwe.txt:
total_sales>qwe
ANTLR on master [✘+?]
➜ antlr4 qwe.g4
ANTLR on master [✘+?]
➜ javac *.java
ANTLR on master [✘+?]
➜ grun qwe tokens -tokens < qwe.txt
[@0,0:10='total_sales',<COLUMN>,1:0]
[@1,11:11='>',<OPERATOR>,1:11]
[@2,12:14='qwe',<COLUMN>,1:12]
[@3,15:14='<EOF>',<EOF>,1:15]
如您所见...
total_sales
和 qwe
都被识别为 COLUMN
代币,
此代码适用于 Java Maven antlr4
import java.io.IOException;
import org.antlr.v4.gui.Trees;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
public class GrunGui {
public static void main(String[] args) throws IOException {
// input source (can be different in your case)
String inputfilepath = "<your file path>";
// your input type can be different, adjust code according to your input source
CharStream charStreamInput = CharStreams.fromFileName(inputfilepath);
// replace ExampleLexer and ExampleParser with your own lexer and parser
ExampleLexer lexer = new ExampleLexer(charStreamInput);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExampleParser parser = new ExampleParser(tokens);
// replace YourContext and .yourStartRuleMethod() method according to your own grammar file
ExampleParser.YourContext ctx = parser.yourStartRuleMethod();
Trees.inspect(ctx, parser);
}
}
此代码将打开 grun GUI。