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