1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
7 /** a JavaScript function, compiled into bytecode */
8 public final class CompiledFunction extends JS.Callable implements ByteCodes, Tokens {
10 // Fields and Accessors ///////////////////////////////////////////////
12 /** the source code file that this block was drawn from */
13 private String sourceName;
14 public String getSourceName() throws JS.Exn { return sourceName; }
16 /** the first line of this function */
17 private int firstLine;
18 public int getFirstLine() throws JS.Exn { return firstLine; }
20 /** the line numbers */
21 private int[] line = new int[10];
23 /** the instructions */
24 private int[] op = new int[10];
26 /** the arguments to the instructions */
27 private Object[] arg = new Object[10];
29 /** the number of instruction/argument pairs */
31 int size() { return size; }
33 /** the scope in which this function was declared */
34 private JS.Scope parentScope;
35 JS.Scope getParentScope() { return parentScope; }
38 // Constructors ////////////////////////////////////////////////////////
40 public CompiledFunction cloneWithNewParentScope(JS.Scope s) throws IOException {
41 CompiledFunction ret = new CompiledFunction(sourceName, firstLine, s);
46 CompiledFunction(String sourceName, int firstLine, JS.Scope parentScope) throws IOException {
47 this.sourceName = sourceName;
48 this.firstLine = firstLine;
49 this.parentScope = parentScope;
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);
58 p.parseStatement(false, this);
59 if (s == size()) break;
61 add(-1, Tokens.RETURN);
62 } catch (Exception e) {
63 if (Log.on) Log.log(Parser.class, e);
67 public Object call(Array args) throws JS.Exn {
68 CompiledFunction saved = (CompiledFunction)Context.currentFunction.get(Thread.currentThread());
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());
77 eval(args == null ? parentScope : new FunctionScope(sourceName, parentScope));
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());
85 if (saved == null) Context.currentFunction.remove(Thread.currentThread());
86 else Context.currentFunction.put(Thread.currentThread(), saved);
91 // Adding and Altering Bytecodes ///////////////////////////////////////////////////
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;
103 this.line[size] = line;
111 // Invoking the Bytecode ///////////////////////////////////////////////////////
114 void eval(JS.Scope s) {
115 final Vec t = Context.getContextForThread(Thread.currentThread()).stack;
116 OUTER: for(pc=0; pc<size; 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;
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");
149 CompiledFunction bytes = (CompiledFunction)arg[pc];
151 t.push(bytes.cloneWithNewParentScope(s));
152 } catch (IOException e) {
153 throw new Error("this should never happen");
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);
171 t.push(new Context.LoopMarker(pc, pc > 0 && op[pc - 1] == LABEL ? (String)arg[pc - 1] : (String)null));
172 t.push(Boolean.TRUE);
178 while(t.size() > 0) {
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;
192 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + line);
195 t.push(new Context.TryMarker(pc + ((Integer)arg[pc]).intValue()));
200 Object retval = t.pop();
201 while(t.size() > 0) {
203 if (o != null && o instanceof Context.CallMarker) {
208 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
212 Object val = t.pop();
213 Object key = t.pop();
214 Object target = t.peek();
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);
236 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
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);
251 Array arguments = new 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 // FIXME: we really need to distinguish between compiled functions and callables
256 JS.Callable f = (JS.Callable)t.pop();
257 if (f == null) throw je("attempted to call null");
259 t.push(f.call(arguments));
265 // fall through if exception was thrown
267 Object exn = t.pop();
268 while(t.size() > 0) {
270 if (o instanceof Context.TryMarker) {
272 pc = ((Context.TryMarker)o).location - 1;
276 throw new JS.Exn(exn);
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);
286 t.push(isPrefix ? val : num);
291 Object right = t.pop();
292 Object left = t.pop();
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;
307 t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
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;
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;
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;
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);
327 if (left instanceof String || right instanceof String) {
328 result = left.toString().compareTo(right.toString());
330 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
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)));
342 if (l == null) { Object tmp = r; r = l; l = tmp; }
343 if (l == null && r == null) ret = true;
344 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
345 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
346 else if (l instanceof String) ret = r != null && l.equals(r.toString());
347 else ret = l.equals(r);
348 t.push(new Boolean(op[pc] == EQ ? ret : !ret)); break;
351 default: throw new Error("unknown opcode " + op[pc]);
358 // Helpers for Number, String, and Boolean ////////////////////////////////////////
360 private Object getFromString(final String o, final Object v) {
361 if (v.equals("length")) return new Integer(((String)o).length());
362 else if (v.equals("substring")) return new JS.Callable() {
363 public Object call(Array args) {
364 if (args.length() == 1) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue());
365 else if (args.length() == 2) return ((String)o).substring(JS.toNumber(args.elementAt(0)).intValue(),
366 JS.toNumber(args.elementAt(1)).intValue());
367 else throw je("String.substring() can only take one or two arguments");
370 else if (v.equals("toLowerCase")) return new JS.Callable() {
371 public Object call(Array args) {
372 return ((String)o).toLowerCase();
374 else if (v.equals("toUpperCase")) return new JS.Callable() {
375 public Object call(Array args) {
376 return ((String)o).toString().toUpperCase();
378 else if (v.equals("charAt")) return new JS.Callable() {
379 public Object call(Array args) {
380 return ((String)o).charAt(JS.toNumber(args.elementAt(0)).intValue()) + "";
382 else if (v.equals("lastIndexOf")) return new JS.Callable() {
383 public Object call(Array args) {
384 if (args.length() != 1) return null;
385 return new Integer(((String)o).lastIndexOf(args.elementAt(0).toString()));
387 else if (v.equals("indexOf")) return new JS.Callable() {
388 public Object call(Array args) {
389 if (args.length() != 1) return null;
390 return new Integer(((String)o).indexOf(args.elementAt(0).toString()));
392 throw je("Not Implemented: propery " + v + " on String objects");
396 // Exception Stuff ////////////////////////////////////////////////////////////////
398 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
399 EvaluatorException ee(String s) { throw new EvaluatorException(sourceName + ":" + line[pc] + " " + s); }
400 JS.Exn je(String s) { throw new JS.Exn(sourceName + ":" + line[pc] + " " + s); }
403 // FunctionScope /////////////////////////////////////////////////////////////////
405 private class FunctionScope extends JS.Scope {
407 public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
408 public String getSourceName() { return sourceName; }
409 public Object get(Object key) throws JS.Exn {
410 if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
411 else if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
412 return super.get(key);