2003/06/12 17:57:37
[org.ibex.core.git] / src / org / xwt / js / CompiledFunction.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 JavaScript function, compiled into bytecode */
8 public final class CompiledFunction extends JS.Callable implements ByteCodes, Tokens {
9
10     // Fields and Accessors ///////////////////////////////////////////////
11
12     /** the source code file that this block was drawn from */
13     private String sourceName;
14     public String getSourceName() throws JS.Exn { return sourceName; }
15     
16     /** the first line of this function */
17     private int firstLine;
18     public int getFirstLine() throws JS.Exn { return firstLine; }
19         
20     /** the line numbers */
21     private int[] line = new int[10];
22
23     /** the instructions */
24     private int[] op = new int[10];
25
26     /** the arguments to the instructions */
27     private Object[] arg = new Object[10];
28
29     /** the number of instruction/argument pairs */
30     private int size = 0;
31     int size() { return size; }
32
33     /** the scope in which this function was declared */
34     private JS.Scope parentScope;
35     JS.Scope getParentScope() { return parentScope; }
36
37
38     // Constructors ////////////////////////////////////////////////////////
39
40     public CompiledFunction cloneWithNewParentScope(JS.Scope s) throws IOException {
41         CompiledFunction ret = new CompiledFunction(sourceName, firstLine, s);
42         ret.paste(this);
43         return ret;
44     }
45
46     CompiledFunction(String sourceName, int firstLine, JS.Scope parentScope) throws IOException {
47         this.sourceName = sourceName;
48         this.firstLine = firstLine;
49         this.parentScope = parentScope;
50     }
51
52     CompiledFunction(String sourceName, int firstLine, Reader sourceCode, JS.Scope parentScope) throws IOException {
53         this(sourceName, firstLine, parentScope);
54         Parser p = new Parser(sourceCode, sourceName, firstLine);
55         try {
56             while(true) {
57                 int s = size();
58                 p.parseStatement(false, this);
59                 if (s == size()) break;
60             }
61             add(-1, Tokens.RETURN);
62         } catch (Exception e) {
63             if (Log.on) Log.log(Parser.class, e);
64         }
65     }
66     
67     public Object call(Array args) throws JS.Exn {
68         CompiledFunction saved = (CompiledFunction)Context.currentFunction.get(Thread.currentThread());
69         try {
70             Context.currentFunction.put(Thread.currentThread(), this);
71             Context cx = Context.getContextForThread(Thread.currentThread());
72             int size = cx.stack.size();
73             cx.stack.push(new Context.CallMarker());
74             cx.stack.push(args);
75             
76             // FIXME, ugly
77             eval(args == null ? parentScope : new FunctionScope(sourceName, parentScope));
78             
79             Object ret = cx.stack.pop();
80             if (cx.stack.size() > size)
81                 Log.log(this, "warning, stack grew by " + (cx.stack.size() - size) +
82                         " elements during call to " + Context.getCurrentSourceNameAndLine());
83             return ret;
84         } finally {
85             if (saved == null) Context.currentFunction.remove(Thread.currentThread());
86             else Context.currentFunction.put(Thread.currentThread(), saved);
87         }
88     }
89
90
91     // Adding and Altering Bytecodes ///////////////////////////////////////////////////
92
93     void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
94     void set(int pos, Object arg_) { arg[pos] = arg_; }
95     void paste(CompiledFunction other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
96     CompiledFunction add(int line, int op_) { return add(line, op_, null); }
97     CompiledFunction add(int line, int op_, Object arg_) {
98         if (size == op.length - 1) {
99             int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
100             Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
101             int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
102         }
103         this.line[size] = line;
104         op[size] = op_;
105         arg[size] = arg_;
106         size++;
107         return this;
108     }
109
110
111     // Invoking the Bytecode ///////////////////////////////////////////////////////
112         
113     int pc = 0;
114     void eval(JS.Scope s) {
115         final Vec t = Context.getContextForThread(Thread.currentThread()).stack;
116         OUTER: for(pc=0; pc<size; pc++) {
117             String label = null;
118             switch(op[pc]) {
119             case LITERAL: t.push(arg[pc]); break;
120             case OBJECT: t.push(new JS.Obj()); break;
121             case ARRAY: t.push(new Array(JS.toNumber(arg[pc]).intValue())); break;
122             case DECLARE: s.declare((String)t.pop()); break;
123             case TOPSCOPE: t.push(s); break;
124             case JT: if (JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
125             case JF: if (!JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
126             case JMP: pc += JS.toNumber(arg[pc]).intValue() - 1; break;
127             case POP: t.pop(); break;
128             case SWAP: { Object o1 = t.pop(); Object o2 = t.pop(); t.push(o1); t.push(o2); break; }
129             case DUP: t.push(t.peek()); break;
130             case NEWSCOPE: s = new JS.Scope(s); break;
131             case OLDSCOPE: s = s.getParentScope(); break;
132             case ASSERT: if (!JS.toBoolean(t.pop())) throw je("assertion failed"); break;
133             case BITNOT: t.push(new Long(~JS.toLong(t.pop()))); break;
134             case BANG: t.push(new Boolean(!JS.toBoolean(t.pop()))); break;
135
136             case TYPEOF: {
137                 Object o = t.pop();
138                 if (o == null) t.push(null);
139                 else if (o instanceof org.xwt.Box) t.push("Box");
140                 else if (o instanceof JS) t.push("Object");
141                 else if (o instanceof String) t.push("String");
142                 else if (o instanceof Number) t.push("Number");
143                 else if (o.getClass().getName().startsWith("org.xwt.js.")) t.push(o.getClass().getName().substring(11));
144                 else t.push("unknown");
145                 break;
146             }
147
148             case NEWFUNCTION: {
149                 CompiledFunction bytes = (CompiledFunction)arg[pc];
150                 try {
151                     t.push(bytes.cloneWithNewParentScope(s));
152                 } catch (IOException e) {
153                     throw new Error("this should never happen");
154                 }
155                 break;
156             }
157
158             case PUSHKEYS: {
159                 Object o = t.peek();
160                 Object[] keys = ((JS)o).keys();
161                 Array a = new Array();
162                 a.setSize(keys.length);
163                 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
164                 t.push(a);
165                 break;
166             }
167
168             case LABEL: break;
169             case LOOP: {
170                 t.push(s);
171                 t.push(new Context.LoopMarker(pc, pc > 0 && op[pc - 1] == LABEL ? (String)arg[pc - 1] : (String)null));
172                 t.push(Boolean.TRUE);
173                 break;
174             }
175
176             case BREAK:
177             case CONTINUE:
178                 while(t.size() > 0) {
179                     Object o = t.pop();
180                     if (o instanceof Context.CallMarker) ee("break or continue not within a loop");
181                     if (o != null && o instanceof Context.LoopMarker) {
182                         if (arg[pc] == null || arg[pc].equals(((Context.LoopMarker)o).label)) {
183                             int loopInstructionLocation = ((Context.LoopMarker)o).location;
184                             int endOfLoop = ((Integer)arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
185                             s = (JS.Scope)t.pop();
186                             if (op[pc] == CONTINUE) { t.push(s); t.push(o); t.push(Boolean.FALSE); }
187                             pc = op[pc] == BREAK ? endOfLoop - 1 : loopInstructionLocation;
188                             continue OUTER;
189                         }
190                     }
191                 }
192                 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + line);
193
194             case TRY: {
195                 t.push(new Context.TryMarker(pc + ((Integer)arg[pc]).intValue()));
196                 break;
197             }
198
199             case RETURN: {
200                 Object retval = t.pop();
201                 while(t.size() > 0) {
202                     Object o = t.pop();
203                     if (o != null && o instanceof Context.CallMarker) {
204                         t.push(retval);
205                         return;
206                     }
207                 }
208                 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
209             }
210
211             case PUT: {
212                 Object val = t.pop();
213                 Object key = t.pop();
214                 Object target = t.peek();
215                 if (target == null)
216                     throw je("tried to put a value to the " + key + " property on the null value");
217                 if (!(target instanceof JS))
218                     throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
219                 ((JS)target).put(key, val);
220                 t.push(val);
221                 break;
222             }
223
224             case GET:
225             case GET_PRESERVE: {
226                 Object o, v;
227                 if (op[pc] == GET) {
228                     v = t.pop();
229                     o = t.pop();
230                 } else {
231                     v = t.pop();
232                     o = t.peek();
233                     t.push(v);
234                 }
235                 Object ret = null;
236                 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
237                 if (o instanceof String) {
238                     ret = getFromString((String)o, v);
239                 } else if (o instanceof Boolean) {
240                     throw je("Not Implemented: properties on Boolean objects");
241                 } else if (o instanceof Number) {
242                     Log.log(this, "Not Implemented: properties on Number objects");
243                 } else if (o instanceof JS) {
244                     ret = ((JS)o).get(v);
245                 }
246                 t.push(ret);
247                 break;
248             }
249                     
250             case CALL: {
251                 Array arguments = new Array();
252                 int numArgs = JS.toNumber(arg[pc]).intValue();
253                 arguments.setSize(numArgs);
254                 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
255                 // FIXME: we really need to distinguish between compiled functions and callables
256                 JS.Callable f = (JS.Callable)t.pop();
257                 if (f == null) throw je("attempted to call null");
258                 try {
259                     t.push(f.call(arguments));
260                     break;
261                 } catch (JS.Exn e) {
262                     t.push(e);
263                 }
264             }
265             // fall through if exception was thrown
266             case THROW: {
267                 Object exn = t.pop();
268                 while(t.size() > 0) {
269                     Object o = t.pop();
270                     if (o instanceof Context.TryMarker) {
271                         t.push(exn);
272                         pc = ((Context.TryMarker)o).location - 1;
273                         continue OUTER;
274                     }
275                 }
276                 throw new JS.Exn(exn);
277             }
278
279             case INC: case DEC: {
280                 boolean isPrefix = JS.toBoolean(arg[pc]);
281                 Object key = t.pop();
282                 JS obj = (JS)t.pop();
283                 Number num = JS.toNumber(obj.get(key));
284                 Number val = new Double(op[pc] == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
285                 obj.put(key, val);
286                 t.push(isPrefix ? val : num);
287                 break;
288             }
289
290             default: {
291                 Object right = t.pop();
292                 Object left = t.pop();
293                 switch(op[pc]) {
294
295                 case ADD: {
296                     Object l = left;
297                     Object r = right;
298                     if (l instanceof String || r instanceof String) {
299                         if (l == null) l = "null";
300                         if (r == null) r = "null";
301                         if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
302                             l = new Long(((Number)l).longValue());
303                         if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
304                             r = new Long(((Number)r).longValue());
305                         t.push(l.toString() + r.toString()); break;
306                     }
307                     t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
308                 }
309                         
310                 case BITOR: t.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
311                 case BITXOR: t.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
312                 case BITAND: t.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
313
314                 case SUB: t.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
315                 case MUL: t.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
316                 case DIV: t.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
317                 case MOD: t.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
318                         
319                 case LSH: t.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
320                 case RSH: t.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
321                 case URSH: t.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
322                         
323                 case LT: case LE: case GT: case GE: {
324                     if (left == null) left = new Integer(0);
325                     if (right == null) right = new Integer(0);
326                     int result = 0;
327                     if (left instanceof String || right instanceof String) {
328                         result = left.toString().compareTo(right.toString());
329                     } else {
330                         result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
331                     }
332                     t.push(new Boolean((op[pc] == LT && result < 0) || (op[pc] == LE && result <= 0) ||
333                                        (op[pc] == GT && result > 0) || (op[pc] == GE && result >= 0)));
334                     break;
335                 }
336                     
337                 case EQ:
338                 case NE: {
339                     Object l = left;
340                     Object r = right;
341                     boolean ret;
342                     if (l == null) { Object tmp = r; r = l; l = tmp; }
343                     if (l == null && r == null) ret = true;
344                     else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
345                     else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
346                     else if (l instanceof String) ret = r != null && l.equals(r.toString());
347                     else ret = l.equals(r);
348                     t.push(new Boolean(op[pc] == EQ ? ret : !ret)); break;
349                 }
350
351                 default: throw new Error("unknown opcode " + op[pc]);
352                 } }
353             }
354         }
355     }
356
357
358     // Helpers for Number, String, and Boolean ////////////////////////////////////////
359
360     private Object getFromString(final String o, final Object v) {
361         if (v.equals("length")) return new Integer(((String)o).length());
362         else if (v.equals("substring")) return new JS.Callable() {
363                 public Object call(Array args) {
364                     if (args.length() == 1) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue());
365                     else if (args.length() == 2) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue(),
366                                                                               JS.toNumber(args.elementAt(1)).intValue());
367                     else throw je("String.substring() can only take one or two arguments");
368                 }
369             };
370         else if (v.equals("toLowerCase")) return new JS.Callable() {
371                 public Object call(Array args) {
372                     return ((String)o).toLowerCase();
373                 } };
374         else if (v.equals("toUpperCase")) return new JS.Callable() {
375                 public Object call(Array args) {
376                     return ((String)o).toString().toUpperCase();
377                 } };
378         else if (v.equals("charAt")) return new JS.Callable() {
379                 public Object call(Array args) {
380                     return ((String)o).charAt(JS.toNumber(args.elementAt(0)).intValue()) + "";
381                 } };
382         else if (v.equals("lastIndexOf")) return new JS.Callable() {
383                 public Object call(Array args) {
384                     if (args.length() != 1) return null;
385                     return new Integer(((String)o).lastIndexOf(args.elementAt(0).toString()));
386                 } };
387         else if (v.equals("indexOf")) return new JS.Callable() {
388                 public Object call(Array args) {
389                     if (args.length() != 1) return null;
390                     return new Integer(((String)o).indexOf(args.elementAt(0).toString()));
391                 } };
392         throw je("Not Implemented: propery " + v + " on String objects");
393     }
394
395
396     // Exception Stuff ////////////////////////////////////////////////////////////////
397
398     static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
399     EvaluatorException ee(String s) { throw new EvaluatorException(sourceName + ":" + line[pc] + " " + s); }
400     JS.Exn je(String s) { throw new JS.Exn(sourceName + ":" + line[pc] + " " + s); }
401
402
403     // FunctionScope /////////////////////////////////////////////////////////////////
404
405     private class FunctionScope extends JS.Scope {
406         String sourceName;
407         public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
408         public String getSourceName() { return sourceName; }
409         public Object get(Object key) throws JS.Exn {
410             if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
411             else if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
412             return super.get(key);
413         }
414     }
415 }