ANTLR学习笔记(2)

书籍名称:The definitive ANTLR 4 Reference 章节:Chapter4 A quick tour ANTLR解析的模版 g4文件中这样定义可以在生成的java文件中创造出常量MUL 使用vistor手动遍历 使用Listener 还可以深度自定义 public static void main(String[] args) throws IOException { String inputFile = null; if (args.length > 0){ inputFile = args[0]; } InputStream is = System.in; if(inputFile!=null){ is = new FileInputStream(inputFile); } ANTLRInputStream input = new ANTLRInputStream(is); ExprLexer lexer = new ExprLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); ExprParser parser = new ExprParser(tokens); ParseTree tree = parser.prog(); System.out.println(tree.toStringTree(parser)); } 词法解析和语法解析可以拆分成两个文件,使用idea插件生成只需要先生成词法再生成语法就可以。...

March 8, 2023 · 1 min

ANTLR学习日志

阅读的是作者自己写的**The Definitive ANTLR 4 Reference** 使用方式: 要装有jdk cd /usr/local/lib # 找一个想安装的目录就行 curl -O https://www.antlr.org/download/antlr-4.0-complete.jar# 这里必须使用https的链接,https://github.com/antlr/antlr4/issues/2422 # 一个jar包就可以跑了,下面都是为了省事 export CLASSPATH=".:/usr/local/lib/antlr-4.0-complete.jar:$CLASSPATH" alias antlr4='java -jar /usr/local/lib/antlr-4.0-complete.jar' helloword grammar Hello; // Define a grammar called Hello r : 'hello' ID ; // match keyword hello followed by an identifier ID : [a-z]+ ; // match lower-case identifiers WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines, \r (Windows) antlr4 Hello.g4 javac *....

February 28, 2023 · 2 min