e8fa95fe9222f1ae49ee627aa9b6e50816138a2e
[org.ibex.core.git] / src / org / xwt / js / CompiledFunctionImpl.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 // FIXME: could use some cleaning up
8 /** a JavaScript function, compiled into bytecode */
9 class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
10
11     // Fields and Accessors ///////////////////////////////////////////////
12
13     /** the source code file that this block was drawn from */
14     private String sourceName;
15     public String getSourceName() throws JS.Exn { return sourceName; }
16     
17     /** the line numbers */
18     private int[] line = new int[10];
19
20     /** the first line of this script */
21     private int firstLine = -1;
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; by default this function is called in a fresh subscope of the parentScope */
34     private JS.Scope parentScope;
35
36     // Constructors ////////////////////////////////////////////////////////
37
38     private CompiledFunctionImpl cloneWithNewParentScope(JS.Scope s) throws IOException {
39         CompiledFunctionImpl ret = new JS.CompiledFunction(sourceName, firstLine, null, s);
40         ret.paste(this);
41         return ret;
42     }
43
44     protected CompiledFunctionImpl(String sourceName, int firstLine, Reader sourceCode, JS.Scope parentScope) throws IOException {
45         this.sourceName = sourceName;
46         this.firstLine = firstLine;
47         this.parentScope = parentScope;
48         if (sourceCode == null) return;
49         Parser p = new Parser(sourceCode, sourceName, firstLine);
50         while(true) {
51             int s = size();
52             p.parseStatement(this, null);
53             if (s == size()) break;
54         }
55         add(-1, LITERAL, null); 
56         add(-1, RETURN);
57     }
58     
59     public Object call(JS.Array args) throws JS.Exn { return call(args, new FunctionScope(sourceName, parentScope)); }
60     public Object call(JS.Array args, JS.Scope scope) throws JS.Exn {
61         JS.Thread cx = JS.Thread.fromJavaThread(java.lang.Thread.currentThread());
62         CompiledFunction saved = cx.currentCompiledFunction;
63         try {
64             cx.currentCompiledFunction = (CompiledFunction)this;
65             int size = cx.stack.size();
66             cx.stack.push(new CallMarker());
67             cx.stack.push(args);
68             eval(scope);
69             Object ret = cx.stack.pop();
70             // FIXME: if we catch an exception in Java, JS won't notice and the stack will be messed up
71             if (cx.stack.size() > size)
72                 // this should never happen
73                 throw new Error("ERROR: stack grew by " + (cx.stack.size() - size) + " elements during call");
74             return ret;
75         } finally {
76             cx.currentCompiledFunction = saved;
77         }
78     }
79
80
81     // Adding and Altering Bytecodes ///////////////////////////////////////////////////
82
83     int get(int pos) { return op[pos]; }
84     void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
85     void set(int pos, Object arg_) { arg[pos] = arg_; }
86     void paste(CompiledFunctionImpl other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
87     CompiledFunctionImpl add(int line, int op_) { return add(line, op_, null); }
88     CompiledFunctionImpl add(int line, int op_, Object arg_) {
89         if (size == op.length - 1) {
90             int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
91             Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
92             int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
93         }
94         this.line[size] = line;
95         op[size] = op_;
96         arg[size] = arg_;
97         size++;
98         return this;
99     }
100     
101     public int getLine(int pc) {
102         if(pc < 0 || pc >= size) return -1;
103         return line[pc];
104     }
105
106
107     // Invoking the Bytecode ///////////////////////////////////////////////////////
108         
109     void eval(JS.Scope s) {
110         final JS.Thread cx = JS.Thread.fromJavaThread(java.lang.Thread.currentThread());
111         final Vec t = cx.stack;
112         int pc;
113         int lastPC = -1;
114         OUTER: for(pc=0; pc<size; pc++) {
115             String label = null;
116             cx.pc = lastPC = pc;
117             int curOP = op[pc];
118             Object curArg = arg[pc];
119             if(curOP == FINALLY_DONE) {
120                 FinallyData fd = (FinallyData) t.pop();
121                 if(fd == null) continue OUTER; // NOP
122                 curOP = fd.op;
123                 curArg = fd.arg;
124             }
125             switch(curOP) {
126             case LITERAL: t.push(arg[pc]); break;
127             case OBJECT: t.push(new JS.Obj()); break;
128             case ARRAY: t.push(new JS.Array(JS.toNumber(arg[pc]).intValue())); break;
129             case DECLARE: s.declare((String)t.pop()); break;
130             case TOPSCOPE: t.push(s); break;
131             case JT: if (JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
132             case JF: if (!JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
133             case JMP: pc += JS.toNumber(arg[pc]).intValue() - 1; break;
134             case POP: t.pop(); break;
135             case SWAP: { Object o1 = t.pop(); Object o2 = t.pop(); t.push(o1); t.push(o2); break; }
136             case DUP: t.push(t.peek()); break;
137             case NEWSCOPE: s = new JS.Scope(s); break;
138             case OLDSCOPE: s = s.getParentScope(); break;
139             case ASSERT: if (!JS.toBoolean(t.pop())) throw je("assertion failed"); break;
140             case BITNOT: t.push(new Long(~JS.toLong(t.pop()))); break;
141             case BANG: t.push(new Boolean(!JS.toBoolean(t.pop()))); break;
142
143             case TYPEOF: {
144                 Object o = t.pop();
145                 if (o == null) t.push(null);
146                 else if (o instanceof JS) t.push(((JS)o).typeName());
147                 else if (o instanceof String) t.push("string");
148                 else if (o instanceof Number) t.push("number");
149                 else if (o instanceof Boolean) t.push("boolean");
150                 else t.push("unknown");
151                 break;
152             }
153
154             case NEWFUNCTION: {
155                 try {
156                     t.push(((CompiledFunctionImpl)arg[pc]).cloneWithNewParentScope(s));
157                 } catch (IOException e) {
158                     throw new Error("this should never happen");
159                 }
160                 break;
161             }
162
163             case PUSHKEYS: {
164                 Object o = t.peek();
165                 Object[] keys = ((JS)o).keys();
166                 JS.Array a = new JS.Array();
167                 a.setSize(keys.length);
168                 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
169                 t.push(a);
170                 break;
171             }
172
173             case LABEL: break;
174             case LOOP: {
175                 t.push(new LoopMarker(pc, pc > 0 && op[pc - 1] == LABEL ? (String)arg[pc - 1] : (String)null,s));
176                 t.push(Boolean.TRUE);
177                 break;
178             }
179
180             case BREAK:
181             case CONTINUE:
182                 while(t.size() > 0) {
183                     Object o = t.pop();
184                     if (o instanceof CallMarker) ee("break or continue not within a loop");
185                     if (o instanceof TryMarker) {
186                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
187                         t.push(new FinallyData(curOP, curArg));
188                         s = ((TryMarker)o).scope;
189                         pc = ((TryMarker)o).finallyLoc - 1;
190                         continue OUTER;
191                     }
192                     if (o instanceof LoopMarker) {
193                         if (curArg == null || curArg.equals(((LoopMarker)o).label)) {
194                             int loopInstructionLocation = ((LoopMarker)o).location;
195                             int endOfLoop = ((Integer)arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
196                             s = ((LoopMarker)o).scope;
197                             if (curOP == CONTINUE) { t.push(o); t.push(Boolean.FALSE); }
198                             pc = curOP == BREAK ? endOfLoop - 1 : loopInstructionLocation;
199                             continue OUTER;
200                         }
201                     }
202                 }
203                 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + getLine(pc));
204
205             case TRY: {
206                 int[] jmps = (int[]) arg[pc];
207                 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
208                 // each can be < 0 if the specified block does not exist
209                 t.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1],s));
210                 break;
211             }
212
213             case RETURN: {
214                 Object retval = t.pop();
215                 while(t.size() > 0) {
216                     Object o = t.pop();
217                     if (o instanceof TryMarker) {
218                         if(((TryMarker)o).finallyLoc < 0) continue;
219                         t.push(retval); 
220                         t.push(new FinallyData(RETURN));
221                         s = ((TryMarker)o).scope;
222                         pc = ((TryMarker)o).finallyLoc - 1;
223                         continue OUTER;
224                     }
225                     if (o instanceof CallMarker) {
226                         t.push(retval);
227                         return;
228                     }
229                 }
230                 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
231             }
232
233             case PUT: {
234                 Object val = t.pop();
235                 Object key = t.pop();
236                 Object target = t.peek();
237                 if (target == null)
238                     throw je("tried to put a value to the " + key + " property on the null value");
239                 if (!(target instanceof JS))
240                     throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
241                 if (key == null)
242                     throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
243                 ((JS)target).put(key, val);
244                 t.push(val);
245                 break;
246             }
247
248             case GET:
249             case GET_PRESERVE: {
250                 Object o, v;
251                 if (op[pc] == GET) {
252                     v = t.pop();
253                     o = t.pop();
254                 } else {
255                     v = t.pop();
256                     o = t.peek();
257                     t.push(v);
258                 }
259                 Object ret = null;
260                 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
261                 if (v == null) throw je("tried to get the null key from " + o);
262                 if (o instanceof String || o instanceof Number || o instanceof Boolean)
263                     ret = Internal.getFromPrimitive(o,v);
264                 else if (o instanceof JS)
265                     ret = ((JS)o).get(v);
266                 else 
267                     throw je("tried to get property " + v + " from a " + o.getClass().getName());
268                 t.push(ret);
269                 break;
270             }
271             
272             case CALLMETHOD:
273             case CALL:
274             {
275                 JS.Array arguments = new JS.Array();
276                 int numArgs = JS.toNumber(arg[pc]).intValue();
277                 arguments.setSize(numArgs);
278                 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
279                 Object o = t.pop();
280                 if(o == null) throw je("attempted to call null");
281                 try {
282                     Object ret;
283                     if(op[pc] == CALLMETHOD) {
284                         Object method = o;
285                         o = t.pop();
286                         if(o instanceof String || o instanceof Number || o instanceof Boolean)
287                             ret = Internal.callMethodOnPrimitive(o,method,arguments);
288                         else if(o instanceof JS)
289                             ret = ((JS)o).callMethod(method,arguments,false);
290                         else
291                             throw new JS.Exn("Tried to call a method on an object that isn't a JS object");
292                     } else {                   
293                         ret = ((JS.Callable)o).call(arguments);
294                     }
295                     t.push(ret);
296                     break;
297                 } catch (JS.Exn e) {
298                     t.push(e);
299                 }
300             }
301             // fall through if exception was thrown
302             case THROW: {
303                 Object exn = t.pop();
304                 while(t.size() > 0) {
305                     Object o = t.pop();
306                     if (o instanceof CatchMarker || o instanceof TryMarker) {
307                         boolean inCatch = o instanceof CatchMarker;
308                         if(inCatch) {
309                             o = t.pop();
310                             if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
311                         }
312                         if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
313                             // run the catch block, this will implicitly run the finally block, if it exists
314                             t.push(o);
315                             t.push(catchMarker);
316                             t.push((exn instanceof JS.Exn) ? ((JS.Exn)exn).getObject() : exn);
317                             s = ((TryMarker)o).scope;
318                             pc = ((TryMarker)o).catchLoc - 1;
319                             continue OUTER;
320                         } else {
321                             t.push(exn);
322                             t.push(new FinallyData(THROW));
323                             s = ((TryMarker)o).scope;
324                             pc = ((TryMarker)o).finallyLoc - 1;
325                             continue OUTER;
326                         }
327                     }
328                     // no handler found within this func
329                     if(o instanceof CallMarker) {
330                         if(exn instanceof JS.Exn)
331                             throw (JS.Exn)exn;
332                         else
333                             throw new JS.Exn(exn);
334                     }
335                 }
336                 throw new Error("error: THROW invoked but couldn't find a Try or Call Marker!");
337             }
338
339             case INC: case DEC: {
340                 boolean isPrefix = JS.toBoolean(arg[pc]);
341                 Object key = t.pop();
342                 JS obj = (JS)t.pop();
343                 Number num = JS.toNumber(obj.get(key));
344                 Number val = new Double(op[pc] == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
345                 obj.put(key, val);
346                 t.push(isPrefix ? val : num);
347                 break;
348             }
349
350             default: {
351                 Object right = t.pop();
352                 Object left = t.pop();
353                 switch(op[pc]) {
354
355                 case ADD: {
356                     Object l = left;
357                     Object r = right;
358                     if (l instanceof String || r instanceof String) {
359                         if (l == null) l = "null";
360                         if (r == null) r = "null";
361                         if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
362                             l = new Long(((Number)l).longValue());
363                         if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
364                             r = new Long(((Number)r).longValue());
365                         t.push(l.toString() + r.toString()); break;
366                     }
367                     t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
368                 }
369                         
370                 case BITOR: t.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
371                 case BITXOR: t.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
372                 case BITAND: t.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
373
374                 case SUB: t.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
375                 case MUL: t.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
376                 case DIV: t.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
377                 case MOD: t.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
378                         
379                 case LSH: t.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
380                 case RSH: t.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
381                 case URSH: t.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
382                         
383                 case LT: case LE: case GT: case GE: {
384                     if (left == null) left = new Integer(0);
385                     if (right == null) right = new Integer(0);
386                     int result = 0;
387                     if (left instanceof String || right instanceof String) {
388                         result = left.toString().compareTo(right.toString());
389                     } else {
390                         result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
391                     }
392                     t.push(new Boolean((op[pc] == LT && result < 0) || (op[pc] == LE && result <= 0) ||
393                                        (op[pc] == GT && result > 0) || (op[pc] == GE && result >= 0)));
394                     break;
395                 }
396                     
397                 case EQ:
398                 case NE: {
399                     Object l = left;
400                     Object r = right;
401                     boolean ret;
402                     if (l == null) { Object tmp = r; r = l; l = tmp; }
403                     if (l == null && r == null) ret = true;
404                     else if (r == null) ret = false; // l != null, so its false
405                     else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
406                     else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
407                     else if (l instanceof String) ret = r != null && l.equals(r.toString());
408                     else ret = l.equals(r);
409                     t.push(new Boolean(op[pc] == EQ ? ret : !ret)); break;
410                 }
411
412                 default: throw new Error("unknown opcode " + op[pc]);
413                 } }
414             }
415         }
416         // this should never happen, we will ALWAYS have a RETURN at the end of the func
417         throw new Error("Just fell out of CompiledFunction::eval() loop. Last PC was " + lastPC);
418     }
419
420     // Debugging //////////////////////////////////////////////////////////////////////
421
422     public String toString() {
423         StringBuffer sb = new StringBuffer(1024);
424         sb.append("\n" + sourceName + ": " + firstLine + "\n");
425         for (int i=0; i < size; i++) {
426             sb.append(i);
427             sb.append(": ");
428             if (op[i] < 0)
429                 sb.append(bytecodeToString[-op[i]]);
430             else
431                 sb.append(codeToString[op[i]]);
432             sb.append(" ");
433             sb.append(arg[i] == null ? "(no arg)" : arg[i]);
434             if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
435                 sb.append(" jump to ").append(i+((Number) arg[i]).intValue());
436             } else  if(op[i] == TRY) {
437                 int[] jmps = (int[]) arg[i];
438                 sb.append(" catch: ").append(jmps[0] < 0 ? "No catch block" : ""+(i+jmps[0]));
439                 sb.append(" finally: ").append(jmps[1] < 0 ? "No finally block" : ""+(i+jmps[1]));
440             }
441             sb.append("\n");
442         }
443         return sb.toString();
444     } 
445
446     // Exception Stuff ////////////////////////////////////////////////////////////////
447
448     static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
449     EvaluatorException ee(String s) { throw new EvaluatorException(sourceName + ":" + JS.Thread.currentJSThread().getLine() + " " + s); }
450     JS.Exn je(String s) { throw new JS.Exn(sourceName + ":" + JS.Thread.currentJSThread().getLine() + " " + s); }
451
452
453     // FunctionScope /////////////////////////////////////////////////////////////////
454
455     private class FunctionScope extends JS.Scope {
456         String sourceName;
457         public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
458         public String getSourceName() { return sourceName; }
459     }
460
461
462     // Markers //////////////////////////////////////////////////////////////////////
463
464     public static class CallMarker { public CallMarker() { } }
465     
466     public static class CatchMarker { public CatchMarker() { } }
467     private static CatchMarker catchMarker = new CatchMarker();
468     
469     public static class LoopMarker {
470         public int location;
471         public String label;
472         public JS.Scope scope;
473         public LoopMarker(int location, String label, JS.Scope scope) {
474             this.location = location;
475             this.label = label;
476             this.scope = scope;
477         }
478     }
479     public static class TryMarker {
480         public int catchLoc;
481         public int finallyLoc;
482         public JS.Scope scope;
483         public TryMarker(int catchLoc, int finallyLoc, JS.Scope scope) {
484             this.catchLoc = catchLoc;
485             this.finallyLoc = finallyLoc;
486             this.scope = scope;
487         }
488     }
489     public static class FinallyData {
490         public int op;
491         public Object arg;
492         public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
493         public FinallyData(int op) { this(op,null); }
494     }
495 }
496
497 /** this class exists solely to work around a GCJ bug */
498 abstract class JSCallable extends JS.Callable {
499         public abstract Object call(JS.Array args) throws JS.Exn;
500 }