Package jmathexpr.util.parser

Source Code of jmathexpr.util.parser.ExpressionParser

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package jmathexpr.util.parser;

import jmathexpr.Expression;
import jmathexpr.util.context.Statement;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

/**
* ANTLR expression parser.
*
* @author Elemér Furka
*/
public class ExpressionParser {
   
    /**
     * Parses the given input string.
     *
     * @param input a mathematical expression
     * @return an Expression instance representing the parsed input string
     */
    public Expression parse(String input) {
        return parseInput(input).getExpression();
    }
   
    /**
     * Parses the given input string and returns a Statement instance as the result.
     *
     * @param input a statement
     * @return a Statement instance
     */
    public Statement parseStatement(String input) {
        return parseInput(input).getStatement();
    }
   
    private AntlrExpressionListener parseInput(String input) {
        // Create the lexer from the input string
        ExpressionsLexer lexer = new ExpressionsLexer(new ANTLRInputStream(input));
       
        // Get a list of matched tokens
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        // Pass the tokens to the parser
        ExpressionsParser parser = new ExpressionsParser(tokens);

        // Specify our entry point
        ExpressionsParser.StatementContext context = parser.statement();

        // Walk it and attach our listener
        ParseTreeWalker walker = new ParseTreeWalker();
        AntlrExpressionListener listener = new AntlrExpressionListener();
       
        walker.walk(listener, context);

        return listener;
    }
}
TOP

Related Classes of jmathexpr.util.parser.ExpressionParser

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.