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