2003/06/16 06:24:31
[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     int get(int pos) { return op[pos]; }
94     void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
95     void set(int pos, Object arg_) { arg[pos] = arg_; }
96     void paste(CompiledFunction other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
97     CompiledFunction add(int line, int op_) { return add(line, op_, null); }
98     CompiledFunction add(int line, int op_, Object arg_) {
99         if (size == op.length - 1) {
100             int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
101             Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
102             int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
103         }
104         this.line[size] = line;
105         op[size] = op_;
106         arg[size] = arg_;
107         size++;
108         return this;
109     }
110
111
112     // Invoking the Bytecode ///////////////////////////////////////////////////////
113         
114     int pc = 0;
115     void eval(JS.Scope s) {
116         final Vec t = Context.getContextForThread(Thread.currentThread()).stack;
117         OUTER: for(pc=0; pc<size; pc++) {
118             String label = null;
119             switch(op[pc]) {
120             case LITERAL: t.push(arg[pc]); break;
121             case OBJECT: t.push(new JS.Obj()); break;
122             case ARRAY: t.push(new Array(JS.toNumber(arg[pc]).intValue())); break;
123             case DECLARE: s.declare((String)t.pop()); break;
124             case TOPSCOPE: t.push(s); break;
125             case JT: if (JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
126             case JF: if (!JS.toBoolean(t.pop())) pc += JS.toNumber(arg[pc]).intValue() - 1; break;
127             case JMP: pc += JS.toNumber(arg[pc]).intValue() - 1; break;
128             case POP: t.pop(); break;
129             case SWAP: { Object o1 = t.pop(); Object o2 = t.pop(); t.push(o1); t.push(o2); break; }
130             case DUP: t.push(t.peek()); break;
131             case NEWSCOPE: s = new JS.Scope(s); break;
132             case OLDSCOPE: s = s.getParentScope(); break;
133             case ASSERT: if (!JS.toBoolean(t.pop())) throw je("assertion failed"); break;
134             case BITNOT: t.push(new Long(~JS.toLong(t.pop()))); break;
135             case BANG: t.push(new Boolean(!JS.toBoolean(t.pop()))); break;
136
137             case TYPEOF: {
138                 Object o = t.pop();
139                 if (o == null) t.push(null);
140                 else if (o instanceof org.xwt.Box) t.push("Box");
141                 else if (o instanceof JS) t.push("Object");
142                 else if (o instanceof String) t.push("String");
143                 else if (o instanceof Number) t.push("Number");
144                 else if (o.getClass().getName().startsWith("org.xwt.js.")) t.push(o.getClass().getName().substring(11));
145                 else t.push("unknown");
146                 break;
147             }
148
149             case NEWFUNCTION: {
150                 CompiledFunction bytes = (CompiledFunction)arg[pc];
151                 try {
152                     t.push(bytes.cloneWithNewParentScope(s));
153                 } catch (IOException e) {
154                     throw new Error("this should never happen");
155                 }
156                 break;
157             }
158
159             case PUSHKEYS: {
160                 Object o = t.peek();
161                 Object[] keys = ((JS)o).keys();
162                 Array a = new Array();
163                 a.setSize(keys.length);
164                 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
165                 t.push(a);
166                 break;
167             }
168
169             case LABEL: break;
170             case LOOP: {
171                 t.push(s);
172                 t.push(new Context.LoopMarker(pc, pc > 0 && op[pc - 1] == LABEL ? (String)arg[pc - 1] : (String)null));
173                 t.push(Boolean.TRUE);
174                 break;
175             }
176
177             case BREAK:
178             case CONTINUE:
179                 while(t.size() > 0) {
180                     Object o = t.pop();
181                     if (o instanceof Context.CallMarker) ee("break or continue not within a loop");
182                     if (o != null && o instanceof Context.LoopMarker) {
183                         if (arg[pc] == null || arg[pc].equals(((Context.LoopMarker)o).label)) {
184                             int loopInstructionLocation = ((Context.LoopMarker)o).location;
185                             int endOfLoop = ((Integer)arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
186                             s = (JS.Scope)t.pop();
187                             if (op[pc] == CONTINUE) { t.push(s); t.push(o); t.push(Boolean.FALSE); }
188                             pc = op[pc] == BREAK ? endOfLoop - 1 : loopInstructionLocation;
189                             continue OUTER;
190                         }
191                     }
192                 }
193                 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + line);
194
195             case TRY: {
196                 t.push(new Context.TryMarker(pc + ((Integer)arg[pc]).intValue(), s));
197                 break;
198             }
199
200             case RETURN: {
201                 Object retval = t.pop();
202                 while(t.size() > 0) {
203                     Object o = t.pop();
204                     if (o != null && o instanceof Context.CallMarker) {
205                         t.push(retval);
206                         return;
207                     }
208                 }
209                 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
210             }
211
212             case PUT: {
213                 Object val = t.pop();
214                 Object key = t.pop();
215                 Object target = t.peek();
216                 if (target == null)
217                     throw je("tried to put a value to the " + key + " property on the null value");
218                 if (!(target instanceof JS))
219                     throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
220                 ((JS)target).put(key, val);
221                 t.push(val);
222                 break;
223             }
224
225             case GET:
226             case GET_PRESERVE: {
227                 Object o, v;
228                 if (op[pc] == GET) {
229                     v = t.pop();
230                     o = t.pop();
231                 } else {
232                     v = t.pop();
233                     o = t.peek();
234                     t.push(v);
235                 }
236                 Object ret = null;
237                 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
238                 if (v == null) throw je("tried to get the null key from " + v);
239                 if (o instanceof String) {
240                     ret = getFromString((String)o, v);
241                 } else if (o instanceof Boolean) {
242                     throw je("Not Implemented: properties on Boolean objects");
243                 } else if (o instanceof Number) {
244                     Log.log(this, "Not Implemented: properties on Number objects");
245                 } else if (o instanceof JS) {
246                     ret = ((JS)o).get(v);
247                 }
248                 t.push(ret);
249                 break;
250             }
251                     
252             case CALL: {
253                 Array arguments = new Array();
254                 int numArgs = JS.toNumber(arg[pc]).intValue();
255                 arguments.setSize(numArgs);
256                 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
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                         s = ((Context.TryMarker)o).scope;
275                         continue OUTER;
276                     }
277                 }
278                 throw new JS.Exn(exn);
279             }
280
281             case INC: case DEC: {
282                 boolean isPrefix = JS.toBoolean(arg[pc]);
283                 Object key = t.pop();
284                 JS obj = (JS)t.pop();
285                 Number num = JS.toNumber(obj.get(key));
286                 Number val = new Double(op[pc] == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
287                 obj.put(key, val);
288                 t.push(isPrefix ? val : num);
289                 break;
290             }
291
292             default: {
293                 Object right = t.pop();
294                 Object left = t.pop();
295                 switch(op[pc]) {
296
297                 case ADD: {
298                     Object l = left;
299                     Object r = right;
300                     if (l instanceof String || r instanceof String) {
301                         if (l == null) l = "null";
302                         if (r == null) r = "null";
303                         if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
304                             l = new Long(((Number)l).longValue());
305                         if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
306                             r = new Long(((Number)r).longValue());
307                         t.push(l.toString() + r.toString()); break;
308                     }
309                     t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
310                 }
311                         
312                 case BITOR: t.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
313                 case BITXOR: t.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
314                 case BITAND: t.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
315
316                 case SUB: t.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
317                 case MUL: t.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
318                 case DIV: t.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
319                 case MOD: t.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
320                         
321                 case LSH: t.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
322                 case RSH: t.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
323                 case URSH: t.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
324                         
325                 case LT: case LE: case GT: case GE: {
326                     if (left == null) left = new Integer(0);
327                     if (right == null) right = new Integer(0);
328                     int result = 0;
329                     if (left instanceof String || right instanceof String) {
330                         result = left.toString().compareTo(right.toString());
331                     } else {
332                         result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
333                     }
334                     t.push(new Boolean((op[pc] == LT && result < 0) || (op[pc] == LE && result <= 0) ||
335                                        (op[pc] == GT && result > 0) || (op[pc] == GE && result >= 0)));
336                     break;
337                 }
338                     
339                 case EQ:
340                 case NE: {
341                     Object l = left;
342                     Object r = right;
343                     boolean ret;
344                     if (l == null) { Object tmp = r; r = l; l = tmp; }
345                     if (l == null && r == null) ret = true;
346                     else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
347                     else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
348                     else if (l instanceof String) ret = r != null && l.equals(r.toString());
349                     else ret = l.equals(r);
350                     t.push(new Boolean(op[pc] == EQ ? ret : !ret)); break;
351                 }
352
353                 default: throw new Error("unknown opcode " + op[pc]);
354                 } }
355             }
356         }
357     }
358
359
360     // Helpers for Number, String, and Boolean ////////////////////////////////////////
361
362     private Object getFromString(final String o, final Object v) {
363         if (v.equals("length")) return new Integer(((String)o).length());
364         else if (v.equals("substring")) return new JS.Callable() {
365                 public Object call(Array args) {
366                     if (args.length() == 1) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue());
367                     else if (args.length() == 2) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue(),
368                                                                               JS.toNumber(args.elementAt(1)).intValue());
369                     else throw je("String.substring() can only take one or two arguments");
370                 }
371             };
372         else if (v.equals("toLowerCase")) return new JS.Callable() {
373                 public Object call(Array args) {
374                     return ((String)o).toLowerCase();
375                 } };
376         else if (v.equals("toUpperCase")) return new JS.Callable() {
377                 public Object call(Array args) {
378                     return ((String)o).toString().toUpperCase();
379                 } };
380         else if (v.equals("charAt")) return new JS.Callable() {
381                 public Object call(Array args) {
382                     return ((String)o).charAt(JS.toNumber(args.elementAt(0)).intValue()) + "";
383                 } };
384         else if (v.equals("lastIndexOf")) return new JS.Callable() {
385                 public Object call(Array args) {
386                     if (args.length() != 1) return null;
387                     return new Integer(((String)o).lastIndexOf(args.elementAt(0).toString()));
388                 } };
389         else if (v.equals("indexOf")) return new JS.Callable() {
390                 public Object call(Array args) {
391                     if (args.length() != 1) return null;
392                     return new Integer(((String)o).indexOf(args.elementAt(0).toString()));
393                 } };
394         throw je("Not Implemented: propery " + v + " on String objects");
395     }
396
397
398     // Exception Stuff ////////////////////////////////////////////////////////////////
399
400     static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
401     EvaluatorException ee(String s) { throw new EvaluatorException(sourceName + ":" + line[pc] + " " + s); }
402     JS.Exn je(String s) { throw new JS.Exn(sourceName + ":" + line[pc] + " " + s); }
403
404
405     // FunctionScope /////////////////////////////////////////////////////////////////
406
407     private class FunctionScope extends JS.Scope {
408         String sourceName;
409         public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
410         public String getSourceName() { return sourceName; }
411         public Object get(Object key) throws JS.Exn {
412             if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
413             else if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
414             return super.get(key);
415         }
416     }
417 }