Home >Java >javaTutorial >How Can I Create a Simple Arithmetic Expression Parser Using ANTLR?
ANTLR: A Simple Example
ANTLR is a powerful tool for parsing text data, but getting started can be intimidating. For those seeking a simple example to grasp the fundamentals of ANTLR, here's a comprehensive demonstration.
Creating the Grammar
First, let's define a simple grammar in a file called Exp.g:
grammar Exp; eval : additionExp EOF ; additionExp : multiplyExp ( '+' multiplyExp | '-' multiplyExp )* ; multiplyExp : atomExp ( '*' atomExp | '/' atomExp )* ; atomExp : Number | '(' additionExp ')' ; Number : ('0'..'9')+ ('.' ('0'..'9')+)? ;
Generating the Parser and Lexer
Once the grammar is created, download the ANTLR jar and run the following command to generate the parser and lexer:
java -cp antlr-3.2.jar org.antlr.Tool Exp.g
This will create the ExpLexer.java, ExpParser.java, and Exp.tokens files.
Creating the Test Class
Let's create a test class called ANTLRDemo.java:
import org.antlr.runtime.*; public class ANTLRDemo { public static void main(String[] args) throws Exception { ANTLRStringStream in = new ANTLRStringStream("12*(5-6)"); ExpLexer lexer = new ExpLexer(in); CommonTokenStream tokens = new CommonTokenStream(lexer); ExpParser parser = new ExpParser(tokens); System.out.println(parser.eval()); } }
Understanding the Parser Execution
Compile and run ANTLRDemo.java. If the expression evaluates correctly, no output will be printed. Otherwise, an error message will be displayed.
Adding Java Code to the Grammar
To make the parser more functional, add Java code to the grammar inside {...} blocks:
eval : additionExp { /* plain code block! */ System.out.println("value equals: " + $value); } ;
This example prints the result of the expression.
Returning a Double Value from the Rule
Add returns [double value] to each rule in the grammar to indicate that they return a double:
eval returns [double value] : additionExp { /* plain code block! */ System.out.println("value equals: " + $value); } ;
Modifying the ANTLRDemo class
Update the ANTLRDemo.java class to retrieve the returned value:
import org.antlr.runtime.*; public class ANTLRDemo { public static void main(String[] args) throws Exception { ANTLRStringStream in = new ANTLRStringStream("12*(5-6)"); ExpLexer lexer = new ExpLexer(in); CommonTokenStream tokens = new CommonTokenStream(lexer); ExpParser parser = new ExpParser(tokens); System.out.println(parser.eval()); } }
Run ANTLRDemo.java again to see the result printed to the console.
The above is the detailed content of How Can I Create a Simple Arithmetic Expression Parser Using ANTLR?. For more information, please follow other related articles on the PHP Chinese website!