2003/06/09 01:46:11
[org.ibex.core.git] / src / org / xwt / js / ByteCodeBlock.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt.js;
3
4 import org.xwt.util.*;
5 import java.io.*;
6
7 /** A block of JavaScript bytecode run on a very simple stack machine. */
8 public class ByteCodeBlock implements ByteCodes, Tokens {
9
10     // FIXME: this should be line-by-line
11     private int line;
12     private String sourceName;
13
14     /** the instructions */
15     private int[] op = new int[10];
16
17     /** the arguments to the instructions */
18     private Object[] arg = new Object[10];
19
20     /** the number of instruction/argument pairs */
21     private int size = 0;
22
23     public ByteCodeBlock(int line, String sourceName) { this.line = line; this.sourceName = sourceName; }
24     public String getSourceName() { return sourceName; }
25
26     public int size() { return size; }
27     public void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
28     public void set(int pos, Object arg_) { arg[pos] = arg_; }
29     public void paste(ByteCodeBlock other) { for(int i=0; i<other.size; i++) add(other.op[i], other.arg[i]); }
30     public ByteCodeBlock add(int op_) { return add(op_, null); }
31     public ByteCodeBlock add(int op_, Object arg_) {
32         if (size == op.length - 1) {
33             int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
34             Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
35         }
36         op[size] = op_;
37         arg[size] = arg_;
38         size++;
39         return this;
40     }
41         
42     public Object eval(final JS.Scope s, Vec t) throws ControlTransferException {
43         for(int i=0; i<size; i++) switch(op[i]) {
44             case LABEL: break;
45             case LITERAL: t.push(arg[i]); break;
46             case OBJECT: t.push(new JS.Obj()); break;
47             case ARRAY: t.push(new JS.Array(JS.toNumber(arg[i]).intValue())); break;
48             case DECLARE: s.declare((String)t.pop()); break;
49             case TOPSCOPE: t.push(s); break;
50             case JT: if (JS.toBoolean(t.pop())) i += JS.toNumber(arg[i]).intValue() - 1; break;
51             case JF: if (!JS.toBoolean(t.pop())) i += JS.toNumber(arg[i]).intValue() - 1; break;
52             case JMP: i += JS.toNumber(arg[i]).intValue() - 1; break;
53             case POP: t.pop(); break;
54             case SWAP: { Object o1 = t.pop(); Object o2 = t.pop(); t.push(o1); t.push(o2); break; }
55             case DUP: t.push(t.peek()); break;
56
57                 // FIXME: shouldn't need its own stack
58             case SCOPE: t.push(((ByteCodeBlock)arg[i]).eval(new JS.Scope(s), new Vec())); break;
59
60             case ASSERT: if (!JS.toBoolean(t.pop())) throw new EvaluatorException(line, sourceName, "assertion failed"); break;
61             case RETURN: throw new ReturnException(t.pop());
62             case THROW: throw new JS.Exn(t.pop());
63             case TRY: break;
64
65                 // FIXME: implement
66             case TYPEOF: break;
67
68             case BREAK: return Boolean.FALSE;
69             case CONTINUE: return Boolean.TRUE;
70             case BITNOT: t.push(new Long(~JS.toLong(t.pop()))); break;
71             case BANG: t.push(new Boolean(!JS.toBoolean(t.pop()))); break;
72
73             case NEWFUNCTION: {
74                 ByteCodeBlock bytes = (ByteCodeBlock)arg[i];
75                 t.push(new JS.Function(bytes.line, bytes.sourceName, bytes, s));
76                 break;
77             }
78
79             case PUSHKEYS: {
80                 Object o = t.peek();
81                 Object[] keys = ((JS)o).keys();
82                 JS.Array a = new JS.Array();
83                 a.setSize(keys.length);
84                 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
85                 t.push(a);
86                 break;
87             }
88
89             case LOOP: {
90                 ByteCodeBlock loop = (ByteCodeBlock)arg[i];
91                 Vec stack2 = new Vec();
92                 stack2.push(Boolean.TRUE);
93                 while (true) {
94                     Boolean result;
95                     try { result = (Boolean)loop.eval(new JS.Scope(s), stack2);
96                     } catch (ContinueException c) { result = Boolean.TRUE;
97                     } catch (BreakException b) { result = Boolean.FALSE; }
98                     if (result == Boolean.FALSE) break;
99                     stack2 = new Vec();
100                     stack2.push(Boolean.FALSE);
101                 }
102                 break;
103             }
104
105             case PUT: {
106                 Object val = t.pop();
107                 Object key = t.pop();
108                 JS target = (JS)t.peek();
109                 if (target == null)
110                     throw new EvaluatorException(line, sourceName, "tried to put a value to the " + key + " property on the null value");
111                 target.put(key, val);
112                 t.push(val);
113                 break;
114             }
115
116             case GET: {
117                 Object v = t.pop();
118                 Object o = t.pop();
119                 t.push(doGet(o, v));
120                 break;
121             }
122
123             case GET_PRESERVE: {
124                 Object v = t.pop();
125                 Object o = t.peek();
126                 t.push(v);
127                 t.push(doGet(o, v));
128                 break;
129             }
130                     
131             case CALL: {
132                 JS.Array arguments = new JS.Array();
133                 int numArgs = JS.toNumber(arg[i]).intValue();
134                 arguments.setSize(numArgs);
135                 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
136                 JS.Function f = (JS.Function)t.pop();
137                 if (f == null) throw new JS.Exn(new EvaluatorException(line, sourceName, "attempted to call null"));
138                 t.push(f.call(arguments));
139                 break;
140             }
141
142             case INC: case DEC: {
143                 boolean isPrefix = JS.toBoolean(arg[i]);
144                 Object key = t.pop();
145                 JS obj = (JS)t.pop();
146                 Number num = JS.toNumber(obj.get(key));
147                 Number val = new Double(op[i] == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
148                 obj.put(key, val);
149                 t.push(isPrefix ? val : num);
150                 break;
151             }
152
153             default: {
154                 Object right = t.pop();
155                 Object left = t.pop();
156                 switch(op[i]) {
157
158                 case ADD: {
159                     Object l = left;
160                     Object r = right;
161                     if (l instanceof String || r instanceof String) {
162                         if (l == null) l = "null";
163                         if (r == null) r = "null";
164                         if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
165                             l = new Long(((Number)l).longValue());
166                         if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
167                             r = new Long(((Number)r).longValue());
168                         t.push(l.toString() + r.toString()); break;
169                     }
170                     t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
171                 }
172                         
173                 case BITOR: t.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
174                 case BITXOR: t.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
175                 case BITAND: t.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
176
177                 case SUB: t.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
178                 case MUL: t.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
179                 case DIV: t.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
180                 case MOD: t.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
181                         
182                 case LSH: t.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
183                 case RSH: t.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
184                 case URSH: t.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
185                         
186                 case LT: t.push(JS.toDouble(left) < JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
187                 case LE: t.push(JS.toDouble(left) <= JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
188                 case GT: t.push(JS.toDouble(left) > JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
189                 case GE: t.push(JS.toDouble(left) >= JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
190                     
191                 case EQ:
192                 case NE: {
193                     Object l = left;
194                     Object r = right;
195                     boolean ret;
196                     if (l == null) { Object tmp = r; r = l; l = tmp; }
197                     if (l == null && r == null) ret = true;
198                     else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
199                     else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
200                     else if (l instanceof String) ret = r != null && l.equals(r.toString());
201                     else ret = l.equals(r);
202                     t.push(new Boolean(op[i] == EQ ? ret : !ret)); break;
203                 }
204
205                 default: throw new Error("unknown opcode " + op[i]);
206                 } }
207             }
208         System.out.println("returning");
209         if (t.size() != 1) throw new Error("eval() terminated with " + t.size() + " elements on the stack; one expected");
210         return t.pop();
211     }
212
213     public Object doGet(final Object o, final Object v) {
214         if (o == null)
215             throw new EvaluatorException(line, sourceName, "tried to get property \"" + v + "\" from the null value");
216         if (o instanceof String) {
217             if (v.equals("length")) return new Integer(((String)o).length());
218             else if (v.equals("substring")) return new JS.Function() {
219                     public Object _call(JS.Array args) {
220                         if (args.length() == 1) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue());
221                         else if (args.length() == 2) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue(),
222                                                                                   JS.toNumber(args.elementAt(1)).intValue());
223                         else throw new Error("String.substring() can only take one or two arguments");
224                     }
225                 };
226             else if (v.equals("toLowerCase")) return new JS.Function() {
227                     public Object _call(JS.Array args) {
228                         return ((String)o).toLowerCase();
229                     } };
230             else if (v.equals("toUpperCase")) return new JS.Function() {
231                     public Object _call(JS.Array args) {
232                         return ((String)o).toString().toUpperCase();
233                     } };
234             else if (v.equals("charAt")) return new JS.Function() {
235                     public Object _call(JS.Array args) {
236                         return ((String)o).charAt(JS.toNumber(args.elementAt(0)).intValue()) + "";
237                     } };
238             else if (v.equals("lastIndexOf")) return new JS.Function() {
239                     public Object _call(JS.Array args) {
240                         if (args.length() != 1) return null;
241                         return new Integer(((String)o).lastIndexOf(args.elementAt(0).toString()));
242                     } };
243             else if (v.equals("indexOf")) return new JS.Function() {
244                     public Object _call(JS.Array args) {
245                         if (args.length() != 1) return null;
246                         return new Integer(((String)o).indexOf(args.elementAt(0).toString()));
247                     } };
248             throw new Error("Not Implemented: propery " + v + " on String objects");
249         } else if (o instanceof Boolean) {
250             throw new Error("Not Implemented: properties on Boolean objects");
251         } else if (o instanceof Number) {
252             Log.log(this, "Not Implemented: properties on Number objects");
253             return null;
254             //throw new Error("Not Implemented: properties on Number objects");
255         } else if (o instanceof JS) {
256             return ((JS)o).get(v);
257         }
258         return null;
259     }
260
261     static class EvaluatorException extends RuntimeException {
262         public EvaluatorException(int line, String sourceName, String s) {
263             super(sourceName + ":" + line + " " + s);
264         }
265     }
266
267     static abstract class ControlTransferException extends RuntimeException { }
268     static class BreakException extends ControlTransferException {
269         public String label;
270         BreakException(String label) { this.label = label; }
271     }
272     static class ContinueException extends ControlTransferException {
273         public String label;
274         ContinueException(String label) { this.label = label; }
275     }
276     public static class ReturnException extends ControlTransferException {
277         public Object retval;
278         ReturnException(Object retval) { this.retval = retval; }
279     }
280     
281 }