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