2003/06/13 09:19:10
[org.ibex.core.git] / src / org / xwt / js / CompiledFunction.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 public final class CompiledFunction extends JS.Callable implements ByteCodes, Tokens {
9
10     // Fields and Accessors ///////////////////////////////////////////////
11
12     /** the source code file that this block was drawn from */
13     private String sourceName;
14     public String getSourceName() throws JS.Exn { return sourceName; }
15     
16     /** the first line of this function */
17     private int firstLine;
18     public int getFirstLine() throws JS.Exn { return firstLine; }
19         
20     /** the line numbers */
21     private int[] line = new int[10];
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 */
34     private JS.Scope parentScope;
35     JS.Scope getParentScope() { return parentScope; }
36
37
38     // Constructors ////////////////////////////////////////////////////////
39
40     public CompiledFunction cloneWithNewParentScope(JS.Scope s) throws IOException {
41         CompiledFunction ret = new CompiledFunction(sourceName, firstLine, s);
42         ret.paste(this);
43         return ret;
44     }
45
46     CompiledFunction(String sourceName, int firstLine, JS.Scope parentScope) throws IOException {
47         this.sourceName = sourceName;
48         this.firstLine = firstLine;
49         this.parentScope = parentScope;
50     }
51
52     CompiledFunction(String sourceName, int firstLine, Reader sourceCode, JS.Scope parentScope) throws IOException {
53         this(sourceName, firstLine, parentScope);
54         Parser p = new Parser(sourceCode, sourceName, firstLine);
55         try {
56             while(true) {
57                 int s = size();
58                 p.parseStatement(this, null);
59                 if (s == size()) break;
60             }
61             add(-1, Tokens.RETURN);
62         } catch (Exception e) {
63             if (Log.on) Log.log(Parser.class, e);
64         }
65     }
66     
67     public Object call(Array args) throws JS.Exn {
68         CompiledFunction saved = (CompiledFunction)Context.currentFunction.get(Thread.currentThread());
69         try {
70             Context.currentFunction.put(Thread.currentThread(), this);
71             Context cx = Context.getContextForThread(Thread.currentThread());
72             int size = cx.stack.size();
73             cx.stack.push(new Context.CallMarker());
74             cx.stack.push(args);
75             
76             // FIXME, ugly
77             eval(args == null ? parentScope : new FunctionScope(sourceName, parentScope));
78             
79             Object ret = cx.stack.pop();
80             if (cx.stack.size() > size)
81                 Log.log(this, "warning, stack grew by " + (cx.stack.size() - size) +
82                         " elements during call to " + Context.getCurrentSourceNameAndLine());
83             return ret;
84         } finally {
85             if (saved == null) Context.currentFunction.remove(Thread.currentThread());
86             else Context.currentFunction.put(Thread.currentThread(), saved);
87         }
88     }
89
90
91     // Adding and Altering Bytecodes ///////////////////////////////////////////////////
92
93     void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
94     void set(int pos, Object arg_) { arg[pos] = arg_; }
95     void paste(CompiledFunction other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
96     CompiledFunction add(int line, int op_) { return add(line, op_, null); }
97     CompiledFunction add(int line, int op_, Object arg_) {
98         if (size == op.length - 1) {
99             int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
100             Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
101             int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
102         }
103         this.line[size] = line;
104         op[size] = op_;
105         arg[size] = arg_;
106         size++;
107         return this;
108     }
109
110
111     // Invoking the Bytecode ///////////////////////////////////////////////////////
112         
113     int pc = 0;
114     void eval(JS.Scope s) {
115         final Vec t = Context.getContextForThread(Thread.currentThread()).stack;
116         OUTER: for(pc=0; pc<size; pc++) {
117             String label = null;
118             switch(op[pc]) {
119             case LITERAL: t.push(arg[pc]); break;
120             case OBJECT: t.push(new JS.Obj()); break;
121             case ARRAY: t.push(new Array(JS.toNumber(arg[pc]).intValue())); break;
122             case DECLARE: s.declare((String)t.pop()); break;
123             case TOPSCOPE: t.push(s); break;
124             case JT: if (JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
125             case JF: if (!JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
126             case JMP: pc += JS.toNumber(arg[pc]).intValue() - 1; break;
127             case POP: t.pop(); break;
128             case SWAP: { Object o1 = t.pop(); Object o2 = t.pop(); t.push(o1); t.push(o2); break; }
129             case DUP: t.push(t.peek()); break;
130             case NEWSCOPE: s = new JS.Scope(s); break;
131             case OLDSCOPE: s = s.getParentScope(); break;
132             case ASSERT: if (!JS.toBoolean(t.pop())) throw je("assertion failed"); break;
133             case BITNOT: t.push(new Long(~JS.toLong(t.pop()))); break;
134             case BANG: t.push(new Boolean(!JS.toBoolean(t.pop()))); break;
135
136             case TYPEOF: {
137                 Object o = t.pop();
138                 if (o == null) t.push(null);
139                 else if (o instanceof org.xwt.Box) t.push("Box");
140                 else if (o instanceof JS) t.push("Object");
141                 else if (o instanceof String) t.push("String");
142                 else if (o instanceof Number) t.push("Number");
143                 else if (o.getClass().getName().startsWith("org.xwt.js.")) t.push(o.getClass().getName().substring(11));
144                 else t.push("unknown");
145                 break;
146             }
147
148             case NEWFUNCTION: {
149                 CompiledFunction bytes = (CompiledFunction)arg[pc];
150                 try {
151                     t.push(bytes.cloneWithNewParentScope(s));
152                 } catch (IOException e) {
153                     throw new Error("this should never happen");
154                 }
155                 break;
156             }
157
158             case PUSHKEYS: {
159                 Object o = t.peek();
160                 Object[] keys = ((JS)o).keys();
161                 Array a = new Array();
162                 a.setSize(keys.length);
163                 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
164                 t.push(a);
165                 break;
166             }
167
168             case LABEL: break;
169             case LOOP: {
170                 t.push(s);
171                 t.push(new Context.LoopMarker(pc, pc > 0 && op[pc - 1] == LABEL ? (String)arg[pc - 1] : (String)null));
172                 t.push(Boolean.TRUE);
173                 break;
174             }
175
176             case BREAK:
177             case CONTINUE:
178                 while(t.size() > 0) {
179                     Object o = t.pop();
180                     if (o instanceof Context.CallMarker) ee("break or continue not within a loop");
181                     if (o != null && o instanceof Context.LoopMarker) {
182                         if (arg[pc] == null || arg[pc].equals(((Context.LoopMarker)o).label)) {
183                             int loopInstructionLocation = ((Context.LoopMarker)o).location;
184                             int endOfLoop = ((Integer)arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
185                             s = (JS.Scope)t.pop();
186                             if (op[pc] == CONTINUE) { t.push(s); t.push(o); t.push(Boolean.FALSE); }
187                             pc = op[pc] == BREAK ? endOfLoop - 1 : loopInstructionLocation;
188                             continue OUTER;
189                         }
190                     }
191                 }
192                 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + line);
193
194             case TRY: {
195                 t.push(new Context.TryMarker(pc + ((Integer)arg[pc]).intValue()));
196                 break;
197             }
198
199             case RETURN: {
200                 Object retval = t.pop();
201                 while(t.size() > 0) {
202                     Object o = t.pop();
203                     if (o != null && o instanceof Context.CallMarker) {
204                         t.push(retval);
205                         return;
206                     }
207                 }
208                 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
209             }
210
211             case PUT: {
212                 Object val = t.pop();
213                 Object key = t.pop();
214                 Object target = t.peek();
215                 if (target == null)
216                     throw je("tried to put a value to the " + key + " property on the null value");
217                 if (!(target instanceof JS))
218                     throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
219                 ((JS)target).put(key, val);
220                 t.push(val);
221                 break;
222             }
223
224             case GET:
225             case GET_PRESERVE: {
226                 Object o, v;
227                 if (op[pc] == GET) {
228                     v = t.pop();
229                     o = t.pop();
230                 } else {
231                     v = t.pop();
232                     o = t.peek();
233                     t.push(v);
234                 }
235                 Object ret = null;
236                 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
237                 if (v == null) throw je("tried to get the null key from " + v);
238                 if (o instanceof String) {
239                     ret = getFromString((String)o, v);
240                 } else if (o instanceof Boolean) {
241                     throw je("Not Implemented: properties on Boolean objects");
242                 } else if (o instanceof Number) {
243                     Log.log(this, "Not Implemented: properties on Number objects");
244                 } else if (o instanceof JS) {
245                     ret = ((JS)o).get(v);
246                 }
247                 t.push(ret);
248                 break;
249             }
250                     
251             case CALL: {
252                 Array arguments = new Array();
253                 int numArgs = JS.toNumber(arg[pc]).intValue();
254                 arguments.setSize(numArgs);
255                 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
256                 // FIXME: we really need to distinguish between compiled functions and callables
257                 JS.Callable f = (JS.Callable)t.pop();
258                 if (f == null) throw je("attempted to call null");
259                 try {
260                     t.push(f.call(arguments));
261                     break;
262                 } catch (JS.Exn e) {
263                     t.push(e);
264                 }
265             }
266             // fall through if exception was thrown
267             case THROW: {
268                 Object exn = t.pop();
269                 while(t.size() > 0) {
270                     Object o = t.pop();
271                     if (o instanceof Context.TryMarker) {
272                         t.push(exn);
273                         pc = ((Context.TryMarker)o).location - 1;
274                         continue OUTER;
275                     }
276                 }
277                 throw new JS.Exn(exn);
278             }
279
280             case INC: case DEC: {
281                 boolean isPrefix = JS.toBoolean(arg[pc]);
282                 Object key = t.pop();
283                 JS obj = (JS)t.pop();
284                 Number num = JS.toNumber(obj.get(key));
285                 Number val = new Double(op[pc] == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
286                 obj.put(key, val);
287                 t.push(isPrefix ? val : num);
288                 break;
289             }
290
291             default: {
292                 Object right = t.pop();
293                 Object left = t.pop();
294                 switch(op[pc]) {
295
296                 case ADD: {
297                     Object l = left;
298                     Object r = right;
299                     if (l instanceof String || r instanceof String) {
300                         if (l == null) l = "null";
301                         if (r == null) r = "null";
302                         if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
303                             l = new Long(((Number)l).longValue());
304                         if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
305                             r = new Long(((Number)r).longValue());
306                         t.push(l.toString() + r.toString()); break;
307                     }
308                     t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
309                 }
310                         
311                 case BITOR: t.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
312                 case BITXOR: t.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
313                 case BITAND: t.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
314
315                 case SUB: t.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
316                 case MUL: t.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
317                 case DIV: t.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
318                 case MOD: t.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
319                         
320                 case LSH: t.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
321                 case RSH: t.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
322                 case URSH: t.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
323                         
324                 case LT: case LE: case GT: case GE: {
325                     if (left == null) left = new Integer(0);
326                     if (right == null) right = new Integer(0);
327                     int result = 0;
328                     if (left instanceof String || right instanceof String) {
329                         result = left.toString().compareTo(right.toString());
330                     } else {
331                         result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
332                     }
333                     t.push(new Boolean((op[pc] == LT && result < 0) || (op[pc] == LE && result <= 0) ||
334                                        (op[pc] == GT && result > 0) || (op[pc] == GE && result >= 0)));
335                     break;
336                 }
337                     
338                 case EQ:
339                 case NE: {
340                     Object l = left;
341                     Object r = right;
342                     boolean ret;
343                     if (l == null) { Object tmp = r; r = l; l = tmp; }
344                     if (l == null && r == null) ret = true;
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     }
357
358
359     // Helpers for Number, String, and Boolean ////////////////////////////////////////
360
361     private Object getFromString(final String o, final Object v) {
362         if (v.equals("length")) return new Integer(((String)o).length());
363         else if (v.equals("substring")) return new JS.Callable() {
364                 public Object call(Array args) {
365                     if (args.length() == 1) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue());
366                     else if (args.length() == 2) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue(),
367                                                                               JS.toNumber(args.elementAt(1)).intValue());
368                     else throw je("String.substring() can only take one or two arguments");
369                 }
370             };
371         else if (v.equals("toLowerCase")) return new JS.Callable() {
372                 public Object call(Array args) {
373                     return ((String)o).toLowerCase();
374                 } };
375         else if (v.equals("toUpperCase")) return new JS.Callable() {
376                 public Object call(Array args) {
377                     return ((String)o).toString().toUpperCase();
378                 } };
379         else if (v.equals("charAt")) return new JS.Callable() {
380                 public Object call(Array args) {
381                     return ((String)o).charAt(JS.toNumber(args.elementAt(0)).intValue()) + "";
382                 } };
383         else if (v.equals("lastIndexOf")) return new JS.Callable() {
384                 public Object call(Array args) {
385                     if (args.length() != 1) return null;
386                     return new Integer(((String)o).lastIndexOf(args.elementAt(0).toString()));
387                 } };
388         else if (v.equals("indexOf")) return new JS.Callable() {
389                 public Object call(Array args) {
390                     if (args.length() != 1) return null;
391                     return new Integer(((String)o).indexOf(args.elementAt(0).toString()));
392                 } };
393         throw je("Not Implemented: propery " + v + " on String objects");
394     }
395
396
397     // Exception Stuff ////////////////////////////////////////////////////////////////
398
399     static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
400     EvaluatorException ee(String s) { throw new EvaluatorException(sourceName + ":" + line[pc] + " " + s); }
401     JS.Exn je(String s) { throw new JS.Exn(sourceName + ":" + line[pc] + " " + s); }
402
403
404     // FunctionScope /////////////////////////////////////////////////////////////////
405
406     private class FunctionScope extends JS.Scope {
407         String sourceName;
408         public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
409         public String getSourceName() { return sourceName; }
410         public Object get(Object key) throws JS.Exn {
411             if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
412             else if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
413             return super.get(key);
414         }
415     }
416 }