9cd3f0e46c9ecf222cc66b2e557f699a24894898
[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 void eval(JS.Scope s) throws ControlTransferException {
43         Vec t = Context.getContextForCurrentThread().stack;
44         OUTER: for(int i=0; i<size; i++) {
45             switch(op[i]) {
46             case LABEL: break;
47             case LITERAL: t.push(arg[i]); break;
48             case OBJECT: t.push(new JS.Obj()); break;
49             case ARRAY: t.push(new JS.Array(JS.toNumber(arg[i]).intValue())); break;
50             case DECLARE: s.declare((String)t.pop()); break;
51             case TOPSCOPE: t.push(s); break;
52             case JT: if (JS.toBoolean(t.pop())) i += JS.toNumber(arg[i]).intValue() - 1; break;
53             case JF: if (!JS.toBoolean(t.pop())) i += JS.toNumber(arg[i]).intValue() - 1; break;
54             case JMP: i += JS.toNumber(arg[i]).intValue() - 1; break;
55             case POP: t.pop(); break;
56             case SWAP: { Object o1 = t.pop(); Object o2 = t.pop(); t.push(o1); t.push(o2); break; }
57             case DUP: t.push(t.peek()); break;
58
59             case PUSHSCOPE: s = new JS.Scope(s); break;
60             case POPSCOPE: s = s.getParentScope(); break;
61
62             case ASSERT: if (!JS.toBoolean(t.pop())) throw new EvaluatorException(line, sourceName, "assertion failed"); break;
63             case RETURN: {
64                 Object retval = t.pop();
65                 while(t.size() > 0) {
66                     Object o = t.pop();
67                     if (o != null && o instanceof Context.CallMarker) {
68                         t.push(retval);
69                         return;
70                     }
71                 }
72                 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
73             }
74
75             case THROW: throw new JS.Exn(t.pop());
76             case TRY: break;
77             case TYPEOF: break;   // FIXME: implement
78
79             case BITNOT: t.push(new Long(~JS.toLong(t.pop()))); break;
80             case BANG: t.push(new Boolean(!JS.toBoolean(t.pop()))); break;
81
82             case NEWFUNCTION: {
83                 ByteCodeBlock bytes = (ByteCodeBlock)arg[i];
84                 t.push(new JS.Function(bytes.line, bytes.sourceName, bytes, s));
85                 break;
86             }
87
88             case PUSHKEYS: {
89                 Object o = t.peek();
90                 Object[] keys = ((JS)o).keys();
91                 JS.Array a = new JS.Array();
92                 a.setSize(keys.length);
93                 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
94                 t.push(a);
95                 break;
96             }
97
98             case LOOP: {
99                 t.push(s);
100                 t.push(new Context.LoopMarker(i));
101                 t.push(Boolean.TRUE);
102                 break;
103             }
104
105             case BREAK:
106             case CONTINUE:
107                 while(t.size() > 0) {
108                     Object o = t.pop();
109                     if (o != null && o instanceof Context.LoopMarker) {
110                         int loopInstructionLocation = ((Context.LoopMarker)o).location;
111                         int endOfLoop = ((Integer)arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
112                         s = (JS.Scope)t.pop();
113                         if (op[i] == CONTINUE) { t.push(s); t.push(o); t.push(Boolean.FALSE); }
114                         i = op[i] == BREAK ? endOfLoop - 1 : loopInstructionLocation;
115                         continue OUTER;
116                     }
117                 }
118                 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + line);
119
120                 /*
121                 ByteCodeBlock loop = (ByteCodeBlock)arg[i];
122                 Vec stack2 = new Vec();
123                 Context cur = Context.getContextForCurrentThread();
124                 boolean first = true;
125                 try {
126                     while (true) {
127                         Boolean result;
128                         try {
129                             Context cx = new Context();
130                             cx.bindToCurrentThread();
131                             cx.stack.push(new Boolean(first));
132                             loop.eval(new JS.Scope(s));
133                             result = (Boolean)cx.stack.pop();
134                         } catch (ContinueException c) { result = Boolean.TRUE;
135                         } catch (BreakException b) { result = Boolean.FALSE;
136                         }
137                         first = false;
138                         if (result == Boolean.FALSE) break;
139                     }
140                 } finally {
141                     cur.bindToCurrentThread();
142                 }
143                 break;
144             }
145                 */
146
147             case PUT: {
148                 Object val = t.pop();
149                 Object key = t.pop();
150                 Object target = t.peek();
151                 if (target == null)
152                     throw new JS.Exn(sourceName + ":" + line + ": tried to put a value to the " + key +
153                                      " property on the null value");
154                 if (!(target instanceof JS))
155                     throw new JS.Exn(sourceName + ":" + line + ": tried to put a value to the " + key +
156                                      " property on a " + target.getClass().getName());
157                 ((JS)target).put(key, val);
158                 t.push(val);
159                 break;
160             }
161
162             case GET: {
163                 Object v = t.pop();
164                 Object o = t.pop();
165                 t.push(doGet(o, v));
166                 break;
167             }
168
169             case GET_PRESERVE: {
170                 Object v = t.pop();
171                 Object o = t.peek();
172                 t.push(v);
173                 t.push(doGet(o, v));
174                 break;
175             }
176                     
177             case CALL: {
178                 JS.Array arguments = new JS.Array();
179                 int numArgs = JS.toNumber(arg[i]).intValue();
180                 arguments.setSize(numArgs);
181                 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
182                 JS.Function f = (JS.Function)t.pop();
183                 if (f == null) throw new JS.Exn(sourceName + ":" + line + ": attempted to call null");
184                 t.push(f.call(arguments));
185                 break;
186             }
187
188             case INC: case DEC: {
189                 boolean isPrefix = JS.toBoolean(arg[i]);
190                 Object key = t.pop();
191                 JS obj = (JS)t.pop();
192                 Number num = JS.toNumber(obj.get(key));
193                 Number val = new Double(op[i] == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
194                 obj.put(key, val);
195                 t.push(isPrefix ? val : num);
196                 break;
197             }
198
199             default: {
200                 Object right = t.pop();
201                 Object left = t.pop();
202                 switch(op[i]) {
203
204                 case ADD: {
205                     Object l = left;
206                     Object r = right;
207                     if (l instanceof String || r instanceof String) {
208                         if (l == null) l = "null";
209                         if (r == null) r = "null";
210                         if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
211                             l = new Long(((Number)l).longValue());
212                         if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
213                             r = new Long(((Number)r).longValue());
214                         t.push(l.toString() + r.toString()); break;
215                     }
216                     t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
217                 }
218                         
219                 case BITOR: t.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
220                 case BITXOR: t.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
221                 case BITAND: t.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
222
223                 case SUB: t.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
224                 case MUL: t.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
225                 case DIV: t.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
226                 case MOD: t.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
227                         
228                 case LSH: t.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
229                 case RSH: t.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
230                 case URSH: t.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
231                         
232                 case LT: t.push(JS.toDouble(left) < JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
233                 case LE: t.push(JS.toDouble(left) <= JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
234                 case GT: t.push(JS.toDouble(left) > JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
235                 case GE: t.push(JS.toDouble(left) >= JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
236                     
237                 case EQ:
238                 case NE: {
239                     Object l = left;
240                     Object r = right;
241                     boolean ret;
242                     if (l == null) { Object tmp = r; r = l; l = tmp; }
243                     if (l == null && r == null) ret = true;
244                     else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
245                     else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
246                     else if (l instanceof String) ret = r != null && l.equals(r.toString());
247                     else ret = l.equals(r);
248                     t.push(new Boolean(op[i] == EQ ? ret : !ret)); break;
249                 }
250
251                 default: throw new Error("unknown opcode " + op[i]);
252                 } }
253             }
254         }
255     }
256
257     public Object doGet(final Object o, final Object v) {
258         if (o == null)
259             throw new JS.Exn(sourceName + ":" + line + ": tried to get property \"" + v + "\" from the null value");
260         if (o instanceof String) {
261             if (v.equals("length")) return new Integer(((String)o).length());
262             else if (v.equals("substring")) return new JS.Function(-1, "java", null, null) {
263                     public Object _call(JS.Array args) {
264                         if (args.length() == 1) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue());
265                         else if (args.length() == 2) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue(),
266                                                                                   JS.toNumber(args.elementAt(1)).intValue());
267                         else throw new Error("String.substring() can only take one or two arguments");
268                     }
269                 };
270             else if (v.equals("toLowerCase")) return new JS.Function(-1, "java", null, null) {
271                     public Object _call(JS.Array args) {
272                         return ((String)o).toLowerCase();
273                     } };
274             else if (v.equals("toUpperCase")) return new JS.Function(-1, "java", null, null) {
275                     public Object _call(JS.Array args) {
276                         return ((String)o).toString().toUpperCase();
277                     } };
278             else if (v.equals("charAt")) return new JS.Function(-1, "java", null, null) {
279                     public Object _call(JS.Array args) {
280                         return ((String)o).charAt(JS.toNumber(args.elementAt(0)).intValue()) + "";
281                     } };
282             else if (v.equals("lastIndexOf")) return new JS.Function(-1, "java", null, null) {
283                     public Object _call(JS.Array args) {
284                         if (args.length() != 1) return null;
285                         return new Integer(((String)o).lastIndexOf(args.elementAt(0).toString()));
286                     } };
287             else if (v.equals("indexOf")) return new JS.Function(-1, "java", null, null) {
288                     public Object _call(JS.Array args) {
289                         if (args.length() != 1) return null;
290                         return new Integer(((String)o).indexOf(args.elementAt(0).toString()));
291                     } };
292             throw new Error("Not Implemented: propery " + v + " on String objects");
293         } else if (o instanceof Boolean) {
294             throw new Error("Not Implemented: properties on Boolean objects");
295         } else if (o instanceof Number) {
296             Log.log(this, "Not Implemented: properties on Number objects");
297             return null;
298             //throw new Error("Not Implemented: properties on Number objects");
299         } else if (o instanceof JS) {
300             return ((JS)o).get(v);
301         }
302         return null;
303     }
304
305     static class EvaluatorException extends RuntimeException {
306         public EvaluatorException(int line, String sourceName, String s) {
307             super(sourceName + ":" + line + " " + s);
308         }
309     }
310
311     static abstract class ControlTransferException extends RuntimeException { }
312     static class BreakException extends ControlTransferException {
313         public String label;
314         BreakException(String label) { this.label = label; }
315     }
316     static class ContinueException extends ControlTransferException {
317         public String label;
318         ContinueException(String label) { this.label = label; }
319     }
320     public static class ReturnException extends ControlTransferException {
321         public Object retval;
322         ReturnException(Object retval) { this.retval = retval; }
323     }
324     
325 }