Installations for generating java src AST using antlr4:
- Install antlr4, you can use this link for this.
- After installation, download the JAVA grammar here .
Now create Java8Lexer and Java8Parser using the command:
antlr4 -visitor Java8.g4
This will lead to the creation of several files such as Java8BaseListener.java
Java8BaseVisitor.java
Java8Lexer.java
Java8Lexer.tokens
Java8Listener.java
Java8Parser.java
Java8.tokens
Java8Visitor.java
Use this code to generate the AST:
import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.tree.ParseTree; public class ASTGenerator { public static String readFile() throws IOException { File file = new File("path/to/the/test/file.java"); byte[] encoded = Files.readAllBytes(file.toPath()); return new String(encoded, Charset.forName("UTF-8")); } public static void main(String args[]) throws IOException { String inputString = readFile(); ANTLRInputStream input = new ANTLRInputStream(inputString); Java8Lexer lexer = new Java8Lexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); Java8Parser parser = new Java8Parser(tokens); ParserRuleContext ctx = parser.classDeclaration(); printAST(ctx, false, 0); } private static void printAST(RuleContext ctx, boolean verbose, int indentation) { boolean toBeIgnored = !verbose && ctx.getChildCount() == 1 && ctx.getChild(0) instanceof ParserRuleContext; if (!toBeIgnored) { String ruleName = Java8Parser.ruleNames[ctx.getRuleIndex()]; for (int i = 0; i < indentation; i++) { System.out.print(" "); } System.out.println(ruleName + " -> " + ctx.getText()); } for (int i = 0; i < ctx.getChildCount(); i++) { ParseTree element = ctx.getChild(i); if (element instanceof RuleContext) { printAST((RuleContext) element, verbose, indentation + (toBeIgnored ? 0 : 1)); } } } }
After you finish coding, you can use gradle to create your project, or you can download antlr-4.7.1-complete.jar to the project directory and start compiling.
If you want to get the result in a DOT file so that u can render the AST, you can refer to this QnA post or directly access this repository in which I used gradle to create the project.
Hope this helps. :)
source share