
package jholtrop.gvsu.cs675.bottomup;

import jholtrop.gvsu.cs675.bottomup.analysis.*;
import jholtrop.gvsu.cs675.bottomup.node.*;
import jholtrop.gvsu.cs675.bottomup.lexer.Lexer;
import jholtrop.gvsu.cs675.bottomup.parser.Parser;
import java.io.*;
import java.util.Stack;

public class Evaluator extends DepthFirstAdapter
{
    public static void main(String[] args)
    {
        try
        {
            System.out.println("Enter an expression to evaluate");
            Parser p = new Parser(new Lexer(new PushbackReader(
                            new InputStreamReader(System.in), 1024)));

            Start tree = p.parse();

            Evaluator e = new Evaluator();
            tree.apply(e);
            System.out.println("Result: " + e.getResult());
        }
        catch (Exception e)
        {
            System.out.println("Error: " + e.getMessage());
        }
    }

    private Stack<Double> m_exprValues = new Stack<Double>();

    public double getResult()
    {
        return m_exprValues.peek();
    }

    public void outAAdditionExpr(AAdditionExpr e)
    {
        m_exprValues.push(m_exprValues.pop() + m_exprValues.pop());
    }

    public void outASubtractionExpr(ASubtractionExpr e)
    {
        double b = m_exprValues.pop();
        double a = m_exprValues.pop();
        m_exprValues.push(a - b);
    }

    public void outAMultiplicationTerm(AMultiplicationTerm e)
    {
        m_exprValues.push(m_exprValues.pop() * m_exprValues.pop());
    }

    public void outADivisionTerm(ADivisionTerm e)
    {
        double b = m_exprValues.pop();
        double a = m_exprValues.pop();
        m_exprValues.push(a / b);
    }

    public void caseTNumber(TNumber n)
    {
        m_exprValues.push(Double.parseDouble(n.getText()));
    }
}
