簡體   English   中英

以編程方式使用 ANTLR4 創建 Java 8 AST

[英]Create Java 8 AST with ANTLR4 programmatically

我試圖弄清楚究竟如何使用 ANTLR,但我很難消化我發現的東西。 到目前為止,這是我的資源:

一點背景

我正在嘗試從JavaParse遷移到 ANTLR,因為我想處理除 Java 之外的其他語言的 AST。 我對 ANTLR 和預定義語法(上面鏈接)的理解是,這是可行的。

設置

我在 IntelliJ 中創建了一個非常簡單和標准的 gradle 項目,但我仍然遇到問題:

問題

我缺少Java8LexerJava8Parser類。 我不知道在哪里可以找到這些。

build.gradle

group 'com.antlr-demo'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.antlr:antlr4-master:4.5'
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

Test.java

即使在這個非常瑣碎的例子中,我需要的兩個類都沒有被導入。

public static void parseFile(String f) { // found in Test.java:257
    try {
        if ( !quiet ) System.err.println(f);
        // Create a scanner that reads from the input stream passed to us
        Lexer lexer = new Java8Lexer(new ANTLRFileStream(f)); // missing

        CommonTokenStream tokens = new CommonTokenStream(lexer);

        // Create a parser that reads from the scanner
        Java8Parser parser = new Java8Parser(tokens); // missing
        if ( diag ) parser.addErrorListener(new DiagnosticErrorListener());
        if ( bail ) parser.setErrorHandler(new BailErrorStrategy());
        if ( SLL ) parser.getInterpreter().setPredictionMode(PredictionMode.SLL);

        // start parsing at the compilationUnit rule
        ParserRuleContext t = parser.compilationUnit();
        if ( notree ) parser.setBuildParseTree(false);
        if ( gui ) t.inspect(parser);
        if ( printTree ) System.out.println(t.toStringTree(parser));
    }
    catch (Exception e) {
        System.err.println("parser exception: "+e);
        e.printStackTrace();   // so we can get stack trace
    }
}

pom文件中沒有描述...

我在 github 上創建了一個開源項目,它自動在內存中執行解析器/詞法分析器生成和 AST 創建。 您可以在 github https://github.com/julianthome/inmemantlr上找到它。

從 JAVA 程序獲取 AST 的代碼非常簡單:

// the ANTLR grammar
File f = new File("src/test/ressources/Java.g4");
// plug the ANTLR grammar in 
GenericParser gp = new GenericParser(f, "Java");
// load the file that we'd like to parse into a String variable
String s = FileUtils.loadFileContent("src/test/ressources/HelloWorld.java");
// this listener will create an AST from the java file    
gp.setListener(new DefaultTreeListener());
// compile Parser/Lexer
gp.compile();
ParserRuleContext ctx = ctx = gp.parse(s);
// get access to AST
Ast ast = dlist.getAst();
// print AST in dot format
System.out.println(ast.toDot());

如果您有興趣,可以仔細查看存儲庫中的測試用例。

有一個名為antlr的 gradle 插件可以將g4文件轉換為java文件。 您可以在https://docs.gradle.org/current/userguide/antlr_plugin.html獲取有關antlr插件的詳細信息

另外,使用gradle + antlr可以看到真實的項目: https://github.com/todylu/xcodeprojectParser : https://github.com/todylu/xcodeprojectParser

  • antlr 語法項目中的依賴項: antlr "org.antlr:antlr4:4.5.3"
  • 演示項目中的依賴: compile "org.antlr:antlr4-runtime:4.5.3"

順便說一句,Intellij Idea最好安裝ANTLR v4語法插件來幫助你編輯g4文件。

你少了一步。 您獲得了 java8 語法,但尚未從中創建解析器。 這通常涉及在語法文件(常見問題等)上運行 antlr4 jar,這非常簡單(示例取自入門頁面):

$ antlr4 Hello.g4
$ javac Hello*.java

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM