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