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