87c527c171006bf68e2f5caca687e5feefb82de7
[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 JS.Callable implements ByteCodes, Tokens {
10
11     // Fields and Accessors ///////////////////////////////////////////////
12
13     /** the number of formal arguments */
14     int numFormalArgs = 0;
15
16     /** the source code file that this block was drawn from */
17     private String sourceName;
18     public String getSourceName() throws JS.Exn { return sourceName; }
19     
20     /** the line numbers */
21     private int[] line = new int[10];
22
23     /** the first line of this script */
24     private int firstLine = -1;
25
26     /** the instructions */
27     private int[] op = new int[10];
28
29     /** the arguments to the instructions */
30     private Object[] arg = new Object[10];
31
32     /** the number of instruction/argument pairs */
33     private int size = 0;
34     int size() { return size; }
35
36     /** the scope in which this function was declared; by default this function is called in a fresh subscope of the parentScope */
37     private JS.Scope parentScope;
38
39     // Constructors ////////////////////////////////////////////////////////
40
41     private CompiledFunctionImpl cloneWithNewParentScope(JS.Scope s) throws IOException {
42         CompiledFunctionImpl ret = new JS.CompiledFunction(sourceName, firstLine, null, s);
43         // Reuse the same op, arg, line, and size variables for the new "instance" of the function
44         // NOTE: Neither *this* function nor the new function should be modified after this call
45         ret.op = this.op;
46         ret.arg = this.arg;
47         ret.line = this.line;
48         ret.size = this.size;
49         return ret;
50     }
51
52     protected CompiledFunctionImpl(String sourceName, int firstLine, Reader sourceCode, JS.Scope parentScope) throws IOException {
53         this.sourceName = sourceName;
54         this.firstLine = firstLine;
55         this.parentScope = parentScope;
56         if (sourceCode == null) return;
57         Parser p = new Parser(sourceCode, sourceName, firstLine);
58         while(true) {
59             int s = size();
60             p.parseStatement(this, null);
61             if (s == size()) break;
62         }
63         add(-1, LITERAL, null); 
64         add(-1, RETURN);
65     }
66     
67     public Object call(JS.Array args) throws JS.Exn { return call(args, new FunctionScope(sourceName, parentScope)); }
68     public Object call(JS.Array args, JS.Scope scope) throws JS.Exn {
69         JS.Thread cx = JS.Thread.fromJavaThread(java.lang.Thread.currentThread());
70         CompiledFunction saved = cx.currentCompiledFunction;
71         try {
72             cx.currentCompiledFunction = (CompiledFunction)this;
73             int size = cx.stack.size();
74             cx.stack.push(callMarker);
75             cx.stack.push(args);
76             eval(scope);
77             Object ret = cx.stack.pop();
78             if (cx.stack.size() > size)
79                 // this should never happen
80                 throw new Error("ERROR: stack grew by " + (cx.stack.size() - size) +
81                                 " elements during call at " + sourceName + ":" + firstLine);
82             return ret;
83         } catch(Error e) {
84             // Unwind the stack
85             while(cx.stack.size() > 0) if(cx.stack.pop() instanceof CallMarker) throw e;
86             throw new Error("CallMarker not found on the stack"); // should never happen
87         } finally {
88             cx.currentCompiledFunction = saved;
89         }
90     }
91
92
93     // Adding and Altering Bytecodes ///////////////////////////////////////////////////
94
95     int get(int pos) { return op[pos]; }
96     Object getArg(int pos) { return arg[pos]; }
97     void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
98     void set(int pos, Object arg_) { arg[pos] = arg_; }
99     int pop() { size--; arg[size] = null; return op[size]; }
100     void paste(CompiledFunctionImpl other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
101     CompiledFunctionImpl add(int line, int op_) { return add(line, op_, null); }
102     CompiledFunctionImpl add(int line, int op_, Object arg_) {
103         if (size == op.length - 1) {
104             int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
105             Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
106             int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
107         }
108         this.line[size] = line;
109         op[size] = op_;
110         arg[size] = arg_;
111         size++;
112         return this;
113     }
114     
115     public int getLine(int pc) {
116         if(pc < 0 || pc >= size) return -1;
117         return line[pc];
118     }
119
120
121     // Invoking the Bytecode ///////////////////////////////////////////////////////
122         
123     void eval(JS.Scope s) {
124         final JS.Thread cx = JS.Thread.fromJavaThread(java.lang.Thread.currentThread());
125         final Vec t = cx.stack;
126         int pc;
127         int lastPC = -1;
128         OUTER: for(pc=0; pc<size; pc++) {
129         try {
130             String label = null;
131             cx.pc = lastPC = pc;
132             int curOP = op[pc];
133             Object curArg = arg[pc];
134             if(curOP == FINALLY_DONE) {
135                 FinallyData fd = (FinallyData) t.pop();
136                 if(fd == null) continue OUTER; // NOP
137                 curOP = fd.op;
138                 curArg = fd.arg;
139             }
140             switch(curOP) {
141             case LITERAL: t.push(arg[pc]); break;
142             case OBJECT: t.push(new JS.Obj()); break;
143             case ARRAY: t.push(new JS.Array(JS.toNumber(arg[pc]).intValue())); break;
144             case DECLARE: s.declare((String)(arg[pc]==null ? t.peek() : arg[pc])); if(arg[pc] != null) t.push(arg[pc]); break;
145             case TOPSCOPE: t.push(s); break;
146             case JT: if (JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
147             case JF: if (!JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
148             case JMP: pc += JS.toNumber(arg[pc]).intValue() - 1; break;
149             case POP: t.pop(); break;
150             case SWAP: { Object o1 = t.pop(); Object o2 = t.pop(); t.push(o1); t.push(o2); break; }
151             case DUP: t.push(t.peek()); break;
152             case NEWSCOPE: s = new JS.Scope(s); break;
153             case OLDSCOPE: s = s.getParentScope(); break;
154             case ASSERT: if (!JS.toBoolean(t.pop())) throw je("assertion failed"); break;
155             case BITNOT: t.push(new Long(~JS.toLong(t.pop()))); break;
156             case BANG: t.push(new Boolean(!JS.toBoolean(t.pop()))); break;
157
158             case TYPEOF: {
159                 Object o = t.pop();
160                 if (o == null) t.push(null);
161                 else if (o instanceof JS) t.push(((JS)o).typeName());
162                 else if (o instanceof String) t.push("string");
163                 else if (o instanceof Number) t.push("number");
164                 else if (o instanceof Boolean) t.push("boolean");
165                 else t.push("unknown");
166                 break;
167             }
168
169             case NEWFUNCTION: {
170                 try {
171                     t.push(((CompiledFunctionImpl)arg[pc]).cloneWithNewParentScope(s));
172                 } catch (IOException e) {
173                     throw new Error("this should never happen");
174                 }
175                 break;
176             }
177
178             case PUSHKEYS: {
179                 Object o = t.peek();
180                 Object[] keys = ((JS)o).keys();
181                 JS.Array a = new JS.Array();
182                 a.setSize(keys.length);
183                 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
184                 t.push(a);
185                 break;
186             }
187
188             case LABEL: break;
189             case LOOP: {
190                 t.push(new LoopMarker(pc, pc > 0 && op[pc - 1] == LABEL ? (String)arg[pc - 1] : (String)null,s));
191                 t.push(Boolean.TRUE);
192                 break;
193             }
194
195             case BREAK:
196             case CONTINUE:
197                 while(t.size() > 0) {
198                     Object o = t.pop();
199                     if (o instanceof CallMarker) ee("break or continue not within a loop");
200                     if (o instanceof TryMarker) {
201                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
202                         t.push(new FinallyData(curOP, curArg));
203                         s = ((TryMarker)o).scope;
204                         pc = ((TryMarker)o).finallyLoc - 1;
205                         continue OUTER;
206                     }
207                     if (o instanceof LoopMarker) {
208                         if (curArg == null || curArg.equals(((LoopMarker)o).label)) {
209                             int loopInstructionLocation = ((LoopMarker)o).location;
210                             int endOfLoop = ((Integer)arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
211                             s = ((LoopMarker)o).scope;
212                             if (curOP == CONTINUE) { t.push(o); t.push(Boolean.FALSE); }
213                             pc = curOP == BREAK ? endOfLoop - 1 : loopInstructionLocation;
214                             continue OUTER;
215                         }
216                     }
217                 }
218                 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + getLine(pc));
219
220             case TRY: {
221                 int[] jmps = (int[]) arg[pc];
222                 // jmps[0] is how far away the catch block is, jmps[1] is how far away the finally block is
223                 // each can be < 0 if the specified block does not exist
224                 t.push(new TryMarker(jmps[0] < 0 ? -1 : pc + jmps[0], jmps[1] < 0 ? -1 : pc + jmps[1],s));
225                 break;
226             }
227
228             case RETURN: {
229                 Object retval = t.pop();
230                 while(t.size() > 0) {
231                     Object o = t.pop();
232                     if (o instanceof TryMarker) {
233                         if(((TryMarker)o).finallyLoc < 0) continue;
234                         t.push(retval); 
235                         t.push(new FinallyData(RETURN));
236                         s = ((TryMarker)o).scope;
237                         pc = ((TryMarker)o).finallyLoc - 1;
238                         continue OUTER;
239                     }
240                     if (o instanceof CallMarker) {
241                         t.push(retval);
242                         return;
243                     }
244                 }
245                 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
246             }
247
248             case PUT: {
249                 Object val = t.pop();
250                 Object key = t.pop();
251                 Object target = t.peek();
252                 if (target == null)
253                     throw je("tried to put a value to the " + key + " property on the null value");
254                 if (!(target instanceof JS))
255                     throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
256                 if (key == null)
257                     throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
258                 ((JS)target).put(key, val);
259                 t.push(val);
260                 break;
261             }
262
263             case GET:
264             case GET_PRESERVE: {
265                 Object o, v;
266                 if (op[pc] == GET) {
267                     v = arg[pc] == null ? t.pop() : arg[pc];
268                     o = t.pop();
269                 } else {
270                     v = t.pop();
271                     o = t.peek();
272                     t.push(v);
273                 }
274                 Object ret = null;
275                 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
276                 if (v == null) throw je("tried to get the null key from " + o);
277                 if (o instanceof String || o instanceof Number || o instanceof Boolean)
278                     ret = Internal.getFromPrimitive(o,v);
279                 else if (o instanceof JS)
280                     ret = ((JS)o).get(v);
281                 else 
282                     throw je("tried to get property " + v + " from a " + o.getClass().getName());
283                 t.push(ret);
284                 break;
285             }
286             
287             case CALLMETHOD:
288             case CALL:
289             {
290                 JS.Array arguments = new JS.Array();
291                 int numArgs = JS.toNumber(arg[pc]).intValue();
292                 arguments.setSize(numArgs);
293                 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
294                 Object o = t.pop();
295                 if(o == null) throw je("attempted to call null");
296                 Object ret;
297                 if(op[pc] == CALLMETHOD) {
298                     Object method = o;
299                     o = t.pop();
300                     if(o instanceof String || o instanceof Number || o instanceof Boolean)
301                         ret = Internal.callMethodOnPrimitive(o,method,arguments);
302                     else if(o instanceof JS)
303                         ret = ((JS)o).callMethod(method,arguments,false);
304                     else
305                         throw new JS.Exn("Tried to call a method on an object that isn't a JS object");
306                 } else {                   
307                     ret = ((JS.Callable)o).call(arguments);
308                 }
309                 t.push(ret);
310                 break;
311             }
312             // fall through if exception was thrown
313             case THROW: {
314                 Object o = t.pop();
315                 if(o instanceof JS.Exn) throw (JS.Exn)o;
316                 throw new JS.Exn(o);
317             }
318
319             case INC: case DEC: {
320                 boolean isPrefix = JS.toBoolean(arg[pc]);
321                 Object key = t.pop();
322                 JS obj = (JS)t.pop();
323                 Number num = JS.toNumber(obj.get(key));
324                 Number val = new Double(op[pc] == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
325                 obj.put(key, val);
326                 t.push(isPrefix ? val : num);
327                 break;
328             }
329             
330             case ASSIGN_SUB: case ASSIGN_ADD: {
331                 Object val = t.pop();
332                 Object old = t.pop();
333                 Object key = t.pop();
334                 Object obj = t.peek();
335                 if (val instanceof CompiledFunction) {
336                     if (obj instanceof JS.Scope) {
337                         JS.Scope parent = (JS.Scope)obj;
338                         while(parent.getParentScope() != null) parent = parent.getParentScope();
339                         if (parent instanceof org.xwt.Box) {
340                             if (curOP == ASSIGN_ADD) {
341                                 ((org.xwt.Box)parent).addTrap(key, val);
342                             } else {
343                                 ((org.xwt.Box)parent).delTrap(key, val);
344                             }
345                             // skip over the "normal" implementation of +=/-=
346                             pc += ((Integer)arg[pc]).intValue() - 1;
347                             break;
348                         }
349                     }
350                 }
351                 // use the "normal" implementation
352                 t.push(key);
353                 t.push(old);
354                 t.push(arg);
355                 break;
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                 } else {
368                     Object[] args = new Object[count];
369                     while(--count >= 0) args[count] = t.pop();
370                     if(args[0] instanceof String) {
371                         StringBuffer sb = new StringBuffer(64);
372                         for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
373                         t.push(sb.toString());
374                     } else {
375                         int numStrings = 0;
376                         for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
377                         if(numStrings == 0) {
378                             double d = 0.0;
379                             for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
380                             t.push(new Double(d));
381                         } else {
382                             double d=0.0;
383                             int i=0;
384                             do {
385                                 d += JS.toDouble(args[i++]);
386                             } while(!(args[i] instanceof String));
387                             StringBuffer sb = new StringBuffer(64);
388                             sb.append(JS.toString(new Double(d)));
389                             while(i < args.length) sb.append(JS.toString(args[i++]));
390                             t.push(sb.toString());
391                         }
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         } catch(JS.Exn e) {
448             while(t.size() > 0) {
449                 Object o = t.pop();
450                 if (o instanceof CatchMarker || o instanceof TryMarker) {
451                     boolean inCatch = o instanceof CatchMarker;
452                     if(inCatch) {
453                         o = t.pop();
454                         if(((TryMarker)o).finallyLoc < 0) continue; // no finally block, keep going
455                     }
456                     if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
457                         // run the catch block, this will implicitly run the finally block, if it exists
458                         t.push(o);
459                         t.push(catchMarker);
460                         t.push(e.getObject());
461                         s = ((TryMarker)o).scope;
462                         pc = ((TryMarker)o).catchLoc - 1;
463                         continue OUTER;
464                     } else {
465                         t.push(e);
466                         t.push(new FinallyData(THROW));
467                         s = ((TryMarker)o).scope;
468                         pc = ((TryMarker)o).finallyLoc - 1;
469                         continue OUTER;
470                     }
471                 }
472                 // no handler found within this func
473                 if(o instanceof CallMarker) throw e;
474             }
475             throw new Error("couldn't find a Try or Call Marker!");
476         } // end try/catch
477         } // end for
478         // this should never happen, we will ALWAYS have a RETURN at the end of the func
479         throw new Error("Just fell out of CompiledFunction::eval() loop. Last PC was " + lastPC);
480     }
481
482     // Debugging //////////////////////////////////////////////////////////////////////
483
484     public String toString() {
485         StringBuffer sb = new StringBuffer(1024);
486         sb.append("\n" + sourceName + ": " + firstLine + "\n");
487         for (int i=0; i < size; i++) {
488             sb.append(i);
489             sb.append(": ");
490             if (op[i] < 0)
491                 sb.append(bytecodeToString[-op[i]]);
492             else
493                 sb.append(codeToString[op[i]]);
494             sb.append(" ");
495             sb.append(arg[i] == null ? "(no arg)" : arg[i]);
496             if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
497                 sb.append(" jump to ").append(i+((Number) arg[i]).intValue());
498             } else  if(op[i] == TRY) {
499                 int[] jmps = (int[]) arg[i];
500                 sb.append(" catch: ").append(jmps[0] < 0 ? "No catch block" : ""+(i+jmps[0]));
501                 sb.append(" finally: ").append(jmps[1] < 0 ? "No finally block" : ""+(i+jmps[1]));
502             }
503             sb.append("\n");
504         }
505         return sb.toString();
506     } 
507
508     // Exception Stuff ////////////////////////////////////////////////////////////////
509
510     static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
511     EvaluatorException ee(String s) { throw new EvaluatorException(sourceName + ":" + JS.Thread.currentJSThread().getLine() + " " + s); }
512     JS.Exn je(String s) { throw new JS.Exn(sourceName + ":" + JS.Thread.currentJSThread().getLine() + " " + s); }
513
514
515     // FunctionScope /////////////////////////////////////////////////////////////////
516
517     private static class FunctionScope extends JS.Scope {
518         String sourceName;
519         public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
520         public String getSourceName() { return sourceName; }
521     }
522
523
524     // Markers //////////////////////////////////////////////////////////////////////
525
526     public static class CallMarker { public CallMarker() { } }
527     private static CallMarker callMarker = new CallMarker();
528     
529     public static class CatchMarker { public CatchMarker() { } }
530     private static CatchMarker catchMarker = new CatchMarker();
531     
532     public static class LoopMarker {
533         public int location;
534         public String label;
535         public JS.Scope scope;
536         public LoopMarker(int location, String label, JS.Scope scope) {
537             this.location = location;
538             this.label = label;
539             this.scope = scope;
540         }
541     }
542     public static class TryMarker {
543         public int catchLoc;
544         public int finallyLoc;
545         public JS.Scope scope;
546         public TryMarker(int catchLoc, int finallyLoc, JS.Scope scope) {
547             this.catchLoc = catchLoc;
548             this.finallyLoc = finallyLoc;
549             this.scope = scope;
550         }
551     }
552     public static class FinallyData {
553         public int op;
554         public Object arg;
555         public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
556         public FinallyData(int op) { this(op,null); }
557     }
558 }
559
560 /** this class exists solely to work around a GCJ bug */
561 abstract class JSCallable extends JS.Callable {
562         public abstract Object call(JS.Array args) throws JS.Exn;
563 }