KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > nfunk > jep > function > Assign


1 /* @author rich
2  * Created on 18-Nov-2003
3  *
4  * This code is covered by a Creative Commons
5  * Attribution, Non Commercial, Share Alike license
6  * <a HREF="http://creativecommons.org/licenses/by-nc-sa/1.0">License</a>
7  */

8 package org.nfunk.jep.function;
9
10 import org.nfunk.jep.*;
11 import java.util.Stack JavaDoc;
12 /**
13  * An assignment operator so we can do
14  * x=3+4.
15  * This function implements the SpecialEvaluationI interface
16  * so that it handles seting the value of a variable.
17  * @author Rich Morris
18  * Created on 18-Nov-2003
19  */

20 public class Assign extends PostfixMathCommand implements SpecialEvaluationI {
21
22     public Assign() {
23         super();
24         numberOfParameters = 2;
25     }
26
27     /** For assignment set the value of the variable on the lhs to value returned by evaluating the righthand side.
28      *
29      */

30     public Object JavaDoc evaluate(Node node,Object JavaDoc data,ParserVisitor pv,Stack JavaDoc inStack/*,SymbolTable symTab*/) throws ParseException
31     {
32         if(node.jjtGetNumChildren()!=2)
33             throw new ParseException("Assignment opperator must have 2 operators.");
34
35         // evaluate the value of the righthand side. Left on top of stack
36
node.jjtGetChild(1).jjtAccept(pv,data);
37         checkStack(inStack); // check the stack
38
Object JavaDoc rhsVal = inStack.peek();
39
40         // Set the value of the variable on the lhs.
41
Node lhsNode = node.jjtGetChild(0);
42         if(lhsNode instanceof ASTVarNode)
43         {
44             ASTVarNode vn = (ASTVarNode) lhsNode;
45             Variable var = vn.getVar();
46             var.setValue(rhsVal);
47             return rhsVal;
48         }
49         throw new ParseException("Assignment should have a variable for the lhs.");
50     }
51 }
52
Popular Tags