Home > Java > javaTutorial > How to Parse Arithmetic Expressions with ANTLR: A Step-by-Step Guide?

How to Parse Arithmetic Expressions with ANTLR: A Step-by-Step Guide?

Mary-Kate Olsen
Release: 2024-11-28 22:41:13
Original
592 people have browsed it

How to Parse Arithmetic Expressions with ANTLR: A Step-by-Step Guide?

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')+)?
    ;
Copy after login

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
Copy after login

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); 
    }
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template