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