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