Thursday, July 5, 2018

ANTLR Version 2.0

ANTLR Version 2.0


Installation


Step 1
Download antlr version 2 jar from maven repository. (e.g : antlr-2.7.7.jar)
Step 2
Create a antlr2 grammar file say vhdl.g
Step 3
Compile the vhdl.g file
Step 3a
java -cp  /usr/local/lib/antlr-2.7.7.jar antlr.Tool  vhdl.g
Step 3b
In step a, source code will be generated depending on target language.By default it would be java language if you have not explicitly given.
Step 4

Compile the source code from step 3
Step 4a
javac -cp /usr/local/lib/antlr-2.7.7.jar *.java

Step 5

Write java program to use the classes in step4 to parse grammar sample.



Source code generated after compiling grammar

Class files generated after compiling source code
Main program to read input from a file and print AST


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import antlr.CommonAST;
public class Main {
public static void main(String[] args) throws Exception {
String fname = "arith.vhdl";
System.out.println("Parsing: " + fname);
Reader reader = new BufferedReader(new FileReader(new File(fname)));
VhdlLexer lexer = new VhdlLexer(reader);
VhdlParser parser = new VhdlParser(lexer);
parser.design_file();
CommonAST ast = (CommonAST) parser.getAST();
System.out.println(ast.toStringList());
}
}


0 comments:

Post a Comment