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