Last active
April 19, 2024 08:04
-
-
Save mattmcd/5425206 to your computer and use it in GitHub Desktop.
Simple ANTLR4 grammar example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// define a grammar called Hello | |
grammar Hello; | |
r : 'hello' ID; | |
ID : [a-z]+ ; | |
WS : [ \t\r\n]+ -> skip ; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.antlr.v4.runtime.*; | |
import org.antlr.v4.runtime.tree.*; | |
public class Hello { | |
public static void main( String[] args) throws Exception | |
{ | |
HelloLexer lexer = new HelloLexer( new ANTLRFileStream(args[0])); | |
CommonTokenStream tokens = new CommonTokenStream( lexer ); | |
HelloParser parser = new HelloParser( tokens ); | |
ParseTree tree = parser.r(); | |
ParseTreeWalker walker = new ParseTreeWalker(); | |
walker.walk( new HelloWalker(), tree ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HelloWalker extends HelloBaseListener { | |
public void enterR(HelloParser.RContext ctx ) { | |
System.out.println( "Entering R : " + ctx.ID().getText() ); | |
} | |
public void exitR(HelloParser.RContext ctx ) { | |
System.out.println( "Exiting R" ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
all: Hello.class | |
HelloParser.java: Hello.g4 | |
antlr4 Hello.g4 | |
Hello.class: HelloParser.java Hello.java HelloWalker.java | |
javac Hello*.java |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
hello world |
Finally an actual simple example - much appreciated
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@MarwanMedhat-97 check this out