KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lsmp > djep > xjep > XEvaluatorVisitor


1 /*****************************************************************************
2
3 JEP - Java Math Expression Parser 2.24
4       December 30 2002
5       (c) Copyright 2002, Nathan Funk
6       See LICENSE.txt for license information.
7
8 *****************************************************************************/

9
10 package org.lsmp.djep.xjep;
11
12 import org.nfunk.jep.*;
13
14 /**
15  * This class is used for the evaluation of an expression. It uses the Visitor
16  * design pattern to traverse the function tree and evaluate the expression
17  * using a stack.
18  * <p>
19  * Function nodes are evaluated by first evaluating all the children nodes,
20  * then applying the function class associated with the node. Variable and
21  * constant nodes are evaluated by pushing their value onto the stack.
22
23  * <p>
24  * Some changes implemented by rjm. Nov 03.
25  * Added hook to SpecialEvaluationI.
26  * Clears stack before evaluation.
27  * Simplifies error handeling by making visit methods throw ParseException.
28  * Changed visit(ASTVarNode node) so messages not calculated every time.
29  */

30 public class XEvaluatorVisitor extends EvaluatorVisitor {
31
32     /** Constructor. Initialize the stack member */
33     public XEvaluatorVisitor() {
34 // errorList = null;
35
// symTab = null;
36
// stack = new Stack();
37
}
38
39     /**
40      * Visit a variable node. The value of the variable is obtained from the
41      * symbol table (symTab) and pushed onto the stack.
42      */

43     public Object JavaDoc visit(ASTVarNode node, Object JavaDoc data) throws ParseException {
44
45         Variable var = node.getVar();
46         if (var == null) {
47             String JavaDoc message = "Could not evaluate " + node.getName() + ": ";
48             throw new ParseException(message + " variable not set");
49         }
50         
51         if(var.hasValidValue())
52         {
53             stack.push(var.getValue());
54         }
55         else if(var instanceof XVariable)
56         {
57             Node equation = ((XVariable) var).getEquation();
58             if(equation==null)
59                 throw new ParseException("Cannot find value of "+var.getName()+" no equation.");
60             equation.jjtAccept(this,data);
61             var.setValue(stack.peek());
62         }
63         else
64         {
65             throw new ParseException("Could not evaluate " + node.getName() + ": value not set");
66         }
67
68         return data;
69     }
70 }
71
Popular Tags