Working examples how to use Antlr in Java

219 views
Skip to first unread message

Stjepan Vukadin

unread,
Feb 19, 2018, 7:58:39 AM2/19/18
to antlr-discussion
Hi!

Every example page that I have found on the web (google) is using deprecated API. Where can I find up to date example how to load generated classes?

Thanks and kind regards,
Stjepan

alex;

unread,
Feb 19, 2018, 8:44:52 AM2/19/18
to antlr-discussion
Hi, Stjepan.

What mean to load?

example parsing
import org.antlr.v4.runtime.//<editor-fold defaultstate="collapsed" desc="/*comment*/">
       
ANTLRInputStream
//</editor-fold>
;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.ParserRuleContext;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;


public class MyGrammarCL {

   
/**
     * @param args the command line arguments
     * @throws java.io.FileNotFoundException
     */

   
public static void main(String[] args) throws FileNotFoundException, IOException {
       
InputStream inputStream = new FileInputStream("c:\\dev\\MyGrammar\\utils\\hbmk2\\hbmk2_full.txt");
       
ANTLRInputStream input = new ANTLRInputStream(inputStream);
       
MyGrammarLexer lexer = new MyGrammarLexer(input);
       
CommonTokenStream tokens = new CommonTokenStream(lexer);
       
MyGrammarParser parser = new MyGrammarParser(tokens);
       
System.out.println(new Date());
// Specify our entry point
       
MyGrammarParser.FileProgramContext MyGrammar_fileContext1 = parser.fileProgram();
       
System.out.println(new Date());
       
ParseTreeWalker walker = new ParseTreeWalker();              
       
AntlrMyGrammaristener listener = new AntlrMyGrammaristener();
        walker
.walk(listener, MyGrammar_fileContext1);

   
}

   
private static class AntlrMyGrammaristener extends MyGrammarParserBaseListener {

       
public AntlrMyGrammaristener() {
       
}
       
@Override
   
public void enterEveryRule(ParserRuleContext ctx)
       
{
           
System.out.println(ctx.getClass().getName());
//            if (ctx.getClass().getName() != "MyGrammarParser+FileProgramContext" && ctx.GetType().ToString() != "MyGrammarParser+StatementsContext")
//                System.out.println(ctx.GetText());
       
}
   
}
   
}

example View AST by TestRig
java -cp c:\dev\antlr4\grammars-v4-master\MyGrammar\build\classes;c:\dev\antlr4\tool\target\antlr4-4.7.1-complete.jar org.antlr.v4.gui.TestRig MyGrammar statements -tree -gui c:\dev\antlr4\grammars-v4-master\MyGrammar\test\test.prg
rem
-trace -diagnostics


Stjepan Vukadin

unread,
Feb 19, 2018, 10:53:21 AM2/19/18
to antlr-discussion
You provided a perfect example. By load I meant exactly what you provided (using them in a context to e.g. print AST or something similar).
Reply all
Reply to author
Forward
0 new messages