Home > Java > javaTutorial > How Can I Create a Simple Arithmetic Expression Parser Using ANTLR?

How Can I Create a Simple Arithmetic Expression Parser Using ANTLR?

DDD
Release: 2024-12-06 13:51:16
Original
815 people have browsed it

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

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

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

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template