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