ANTLR: A Walk-through Example
While the ANTLR website provides example grammars, understanding the process of converting grammar to Java code can be elusive. For a clearer understanding, let's delve into a simple example.
Defining the Grammar
We'll create a grammar that evaluates expressions involving the four basic arithmetic operators ( , -, *, /) and parentheses. We define the grammar in a file named Exp.g.
Exp.g
grammar Exp; eval returns [double value] : exp=additionExp {$value = $exp.value;} ; additionExp returns [double value] : m1=multiplyExp {$value = $m1.value;} ( '+' m2=multiplyExp {$value += $m2.value;} | '-' m2=multiplyExp {$value -= $m2.value;} )* ; multiplyExp returns [double value] : a1=atomExp {$value = $a1.value;} ( '*' a2=atomExp {$value *= $a2.value;} | '/' a2=atomExp {$value /= $a2.value;} )* ; atomExp returns [double value] : n=Number {$value = Double.parseDouble($n.text);} | '(' exp=additionExp ')' {$value = $exp.value;} ; Number : ('0'..'9')+ ('.' ('0'..'9')+)? ;
Generating the Parser and Lexer
Using the ANTLR jar file, execute the following command in the directory containing Exp.g:
java -cp antlr-3.2.jar org.antlr.Tool Exp.g
This will create ExpLexer.java, ExpParser.java, and Exp.tokens.
Writing the Test Class
Create ANTLRDemo.java to test the grammar:
ANTLRDemo.java
import org.antlr.runtime.*; public class ANTLRDemo { public static void main(String[] args) throws Exception { ANTLRInputStream in = new ANTLRInputStream("12*(5-6)"); ExpLexer lexer = new ExpLexer(in); CommonTokenStream tokens = new CommonTokenStream(lexer); ExpParser parser = new ExpParser(tokens); System.out.println(parser.eval().value); } }
Running the Example
First, recompile the parser and lexer classes, then run ANTLRDemo:
// Recompile javac -cp .:antlr-3.2.jar ANTLRDemo.java // Run java -cp .:antlr-3.2.jar ANTLRDemo
The console should now output the result of the expression, which is -12.
The above is the detailed content of How to Parse Arithmetic Expressions with ANTLR: A Step-by-Step Guide?. For more information, please follow other related articles on the PHP Chinese website!