2003/06/09 06:38:36
[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(sourceName + ":" + line + ": tried to put a value to the " + key +
113                                      " property on the null value");
114                 target.put(key, val);
115                 t.push(val);
116                 break;
117             }
118
119             case GET: {
120                 Object v = t.pop();
121                 Object o = t.pop();
122                 t.push(doGet(o, v));
123                 break;
124             }
125
126             case GET_PRESERVE: {
127                 Object v = t.pop();
128                 Object o = t.peek();
129                 t.push(v);
130                 t.push(doGet(o, v));
131                 break;
132             }
133                     
134             case CALL: {
135                 JS.Array arguments = new JS.Array();
136                 int numArgs = JS.toNumber(arg[i]).intValue();
137                 arguments.setSize(numArgs);
138                 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
139                 JS.Function f = (JS.Function)t.pop();
140                 if (f == null) throw new JS.Exn(sourceName + ":" + line + ": attempted to call null");
141                 t.push(f.call(arguments));
142                 break;
143             }
144
145             case INC: case DEC: {
146                 boolean isPrefix = JS.toBoolean(arg[i]);
147                 Object key = t.pop();
148                 JS obj = (JS)t.pop();
149                 Number num = JS.toNumber(obj.get(key));
150                 Number val = new Double(op[i] == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
151                 obj.put(key, val);
152                 t.push(isPrefix ? val : num);
153                 break;
154             }
155
156             default: {
157                 Object right = t.pop();
158                 Object left = t.pop();
159                 switch(op[i]) {
160
161                 case ADD: {
162                     Object l = left;
163                     Object r = right;
164                     if (l instanceof String || r instanceof String) {
165                         if (l == null) l = "null";
166                         if (r == null) r = "null";
167                         if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
168                             l = new Long(((Number)l).longValue());
169                         if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
170                             r = new Long(((Number)r).longValue());
171                         t.push(l.toString() + r.toString()); break;
172                     }
173                     t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
174                 }
175                         
176                 case BITOR: t.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
177                 case BITXOR: t.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
178                 case BITAND: t.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
179
180                 case SUB: t.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
181                 case MUL: t.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
182                 case DIV: t.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
183                 case MOD: t.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
184                         
185                 case LSH: t.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
186                 case RSH: t.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
187                 case URSH: t.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
188                         
189                 case LT: t.push(JS.toDouble(left) < JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
190                 case LE: t.push(JS.toDouble(left) <= JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
191                 case GT: t.push(JS.toDouble(left) > JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
192                 case GE: t.push(JS.toDouble(left) >= JS.toDouble(right) ? Boolean.TRUE : Boolean.FALSE); break;
193                     
194                 case EQ:
195                 case NE: {
196                     Object l = left;
197                     Object r = right;
198                     boolean ret;
199                     if (l == null) { Object tmp = r; r = l; l = tmp; }
200                     if (l == null && r == null) ret = true;
201                     else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
202                     else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
203                     else if (l instanceof String) ret = r != null && l.equals(r.toString());
204                     else ret = l.equals(r);
205                     t.push(new Boolean(op[i] == EQ ? ret : !ret)); break;
206                 }
207
208                 default: throw new Error("unknown opcode " + op[i]);
209                 } }
210             }
211         }
212         if (t.size() != 1) throw new Error("eval() terminated with " + t.size() + " elements on the stack; one expected");
213         return t.pop();
214     }
215
216     public Object doGet(final Object o, final Object v) {
217         if (o == null)
218             throw new JS.Exn(sourceName + ":" + line + ": tried to get property \"" + v + "\" from the null value");
219         if (o instanceof String) {
220             if (v.equals("length")) return new Integer(((String)o).length());
221             else if (v.equals("substring")) return new JS.Function(-1, "java", null, null) {
222                     public Object _call(JS.Array args) {
223                         if (args.length() == 1) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue());
224                         else if (args.length() == 2) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue(),
225                                                                                   JS.toNumber(args.elementAt(1)).intValue());
226                         else throw new Error("String.substring() can only take one or two arguments");
227                     }
228                 };
229             else if (v.equals("toLowerCase")) return new JS.Function(-1, "java", null, null) {
230                     public Object _call(JS.Array args) {
231                         return ((String)o).toLowerCase();
232                     } };
233             else if (v.equals("toUpperCase")) return new JS.Function(-1, "java", null, null) {
234                     public Object _call(JS.Array args) {
235                         return ((String)o).toString().toUpperCase();
236                     } };
237             else if (v.equals("charAt")) return new JS.Function(-1, "java", null, null) {
238                     public Object _call(JS.Array args) {
239                         return ((String)o).charAt(JS.toNumber(args.elementAt(0)).intValue()) + "";
240                     } };
241             else if (v.equals("lastIndexOf")) return new JS.Function(-1, "java", null, null) {
242                     public Object _call(JS.Array args) {
243                         if (args.length() != 1) return null;
244                         return new Integer(((String)o).lastIndexOf(args.elementAt(0).toString()));
245                     } };
246             else if (v.equals("indexOf")) return new JS.Function(-1, "java", null, null) {
247                     public Object _call(JS.Array args) {
248                         if (args.length() != 1) return null;
249                         return new Integer(((String)o).indexOf(args.elementAt(0).toString()));
250                     } };
251             throw new Error("Not Implemented: propery " + v + " on String objects");
252         } else if (o instanceof Boolean) {
253             throw new Error("Not Implemented: properties on Boolean objects");
254         } else if (o instanceof Number) {
255             Log.log(this, "Not Implemented: properties on Number objects");
256             return null;
257             //throw new Error("Not Implemented: properties on Number objects");
258         } else if (o instanceof JS) {
259             return ((JS)o).get(v);
260         }
261         return null;
262     }
263
264     static class EvaluatorException extends RuntimeException {
265         public EvaluatorException(int line, String sourceName, String s) {
266             super(sourceName + ":" + line + " " + s);
267         }
268     }
269
270     static abstract class ControlTransferException extends RuntimeException { }
271     static class BreakException extends ControlTransferException {
272         public String label;
273         BreakException(String label) { this.label = label; }
274     }
275     static class ContinueException extends ControlTransferException {
276         public String label;
277         ContinueException(String label) { this.label = label; }
278     }
279     public static class ReturnException extends ControlTransferException {
280         public Object retval;
281         ReturnException(Object retval) { this.retval = retval; }
282     }
283     
284 }