作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想在运行时生成一个 antlr 词法分析器——也就是说,生成语法并在运行时从语法生成词法分析器类及其支持位。我很高兴将它提供给 java 编译器,它可以在运行时访问。
最佳答案
这是一种快速而肮脏的方法:
.g
文件,给定一个字符串作为语法源,.g
文件创建一个解析器和词法分析器,.java
文件,import java.io.*;
import javax.tools.*;
import java.lang.reflect.*;
import org.antlr.runtime.*;
import org.antlr.Tool;
public class Main {
public static void main(String[] args) throws Exception {
// The grammar which echos the parsed characters to theconsole,
// skipping any white space chars.
final String grammar =
"grammar T; \n" +
" \n" +
"parse \n" +
" : (ANY {System.out.println(\"ANY=\" + $ANY.text);})* EOF \n" +
" ; \n" +
" \n" +
"SPACE \n" +
" : (' ' | '\\t' | '\\r' | '\\n') {skip();} \n" +
" ; \n" +
" \n" +
"ANY \n" +
" : . \n" +
" ; ";
final String grammarName = "T";
final String entryPoint = "parse";
// 1 - Write the `.g` grammar file to disk.
Writer out = new BufferedWriter(new FileWriter(new File(grammarName + ".g")));
out.write(grammar);
out.close();
// 2 - Generate the lexer and parser.
Tool tool = new Tool(new String[]{grammarName + ".g"});
tool.process();
// 3 - Compile the lexer and parser.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, System.out, System.err, "-sourcepath", "", grammarName + "Lexer.java");
compiler.run(null, System.out, System.err, "-sourcepath", "", grammarName + "Parser.java");
// 4 - Parse the command line parameter using the dynamically created lexer and
// parser with a bit of reflection Voodoo :)
Lexer lexer = (Lexer)Class.forName(grammarName + "Lexer").newInstance();
lexer.setCharStream(new ANTLRStringStream(args[0]));
CommonTokenStream tokens = new CommonTokenStream(lexer);
Class<?> parserClass = Class.forName(grammarName + "Parser");
Constructor parserCTor = parserClass.getConstructor(TokenStream.class);
Parser parser = (Parser)parserCTor.newInstance(tokens);
Method entryPointMethod = parserClass.getMethod(entryPoint);
entryPointMethod.invoke(parser);
}
}
在像这样编译和运行之后(在 *nix 上):
java -cp .:antlr-3.2.jar Main "a b c"
或在 Windows 上
java -cp .;antlr-3.2.jar Main "a b c"
,产生以下输出:
ANY=aANY=bANY=c
关于java - 在 ANTLR 3 中,如何在运行时而不是提前生成词法分析器(和解析器)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5762067/
我是一名优秀的程序员,十分优秀!