1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
7 // FIXME: could use some cleaning up
8 /** a JavaScript function, compiled into bytecode */
9 class CompiledFunctionImpl extends JSCallable implements ByteCodes, Tokens {
11 // Fields and Accessors ///////////////////////////////////////////////
13 /** the source code file that this block was drawn from */
14 private String sourceName;
15 public String getSourceName() throws JS.Exn { return sourceName; }
17 /** the line numbers */
18 private int[] line = new int[10];
20 /** the first line of this script */
21 private int firstLine = -1;
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; by default this function is called in a fresh subscope of the parentScope */
34 private JS.Scope parentScope;
36 // Constructors ////////////////////////////////////////////////////////
38 private CompiledFunctionImpl cloneWithNewParentScope(JS.Scope s) throws IOException {
39 CompiledFunctionImpl ret = new JS.CompiledFunction(sourceName, firstLine, null, s);
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);
52 p.parseStatement(this, null);
53 if (s == size()) break;
55 add(-1, LITERAL, null);
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;
64 cx.currentCompiledFunction = (CompiledFunction)this;
65 int size = cx.stack.size();
66 cx.stack.push(new CallMarker());
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");
76 cx.currentCompiledFunction = saved;
81 // Adding and Altering Bytecodes ///////////////////////////////////////////////////
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;
94 this.line[size] = line;
101 public int getLine(int pc) {
102 if(pc < 0 || pc >= size) return -1;
107 // Invoking the Bytecode ///////////////////////////////////////////////////////
109 void eval(JS.Scope s) {
110 final JS.Thread cx = JS.Thread.fromJavaThread(java.lang.Thread.currentThread());
111 final Vec t = cx.stack;
114 OUTER: for(pc=0; pc<size; 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;
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");
148 t.push(((CompiledFunctionImpl)arg[pc]).cloneWithNewParentScope(s));
149 } catch (IOException e) {
150 throw new Error("this should never happen");
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);
168 t.push(new LoopMarker(pc, pc > 0 && op[pc - 1] == LABEL ? (String)arg[pc - 1] : (String)null));
169 t.push(Boolean.TRUE);
175 while(t.size() > 0) {
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;
189 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + sourceName + ":" + line);
192 t.push(new TryMarker(pc + ((Integer)arg[pc]).intValue(), s));
197 Object retval = t.pop();
198 while(t.size() > 0) {
200 if (o != null && o instanceof CallMarker) {
205 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
209 Object val = t.pop();
210 Object key = t.pop();
211 Object target = t.peek();
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());
217 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
218 ((JS)target).put(key, val);
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 || o instanceof Number || o instanceof Boolean)
238 ret = Internal.getFromPrimitive(o,v);
239 else if (o instanceof JS)
240 ret = ((JS)o).get(v);
242 throw je("tried to get property " + v + " from a " + o.getClass().getName());
250 JS.Array arguments = new JS.Array();
251 int numArgs = JS.toNumber(arg[pc]).intValue();
252 arguments.setSize(numArgs);
253 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(t.pop(), j);
255 if(o == null) throw je("attempted to call null");
258 if(op[pc] == CALLMETHOD) {
261 if(o instanceof String || o instanceof Number || o instanceof Boolean)
262 ret = Internal.callMethodOnPrimitive(o,method,arguments);
263 else if(o instanceof JS)
264 ret = ((JS)o).callMethod(method,arguments,false);
266 throw new JS.Exn("Tried to call a method on an object that isn't a JS object");
268 ret = ((JS.Callable)o).call(arguments);
276 // fall through if exception was thrown
278 Object exn = t.pop();
279 while(t.size() > 0) {
281 if (o instanceof TryMarker) {
283 pc = ((TryMarker)o).location - 1;
284 s = ((TryMarker)o).scope;
288 throw new JS.Exn(exn);
291 case INC: case DEC: {
292 boolean isPrefix = JS.toBoolean(arg[pc]);
293 Object key = t.pop();
294 JS obj = (JS)t.pop();
295 Number num = JS.toNumber(obj.get(key));
296 Number val = new Double(op[pc] == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
298 t.push(isPrefix ? val : num);
303 Object right = t.pop();
304 Object left = t.pop();
310 if (l instanceof String || r instanceof String) {
311 if (l == null) l = "null";
312 if (r == null) r = "null";
313 if (l instanceof Number && ((Number)l).doubleValue() == ((Number)l).longValue())
314 l = new Long(((Number)l).longValue());
315 if (r instanceof Number && ((Number)r).doubleValue() == ((Number)r).longValue())
316 r = new Long(((Number)r).longValue());
317 t.push(l.toString() + r.toString()); break;
319 t.push(new Double(JS.toDouble(l) + JS.toDouble(r))); break;
322 case BITOR: t.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
323 case BITXOR: t.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
324 case BITAND: t.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
326 case SUB: t.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
327 case MUL: t.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
328 case DIV: t.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
329 case MOD: t.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
331 case LSH: t.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
332 case RSH: t.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
333 case URSH: t.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
335 case LT: case LE: case GT: case GE: {
336 if (left == null) left = new Integer(0);
337 if (right == null) right = new Integer(0);
339 if (left instanceof String || right instanceof String) {
340 result = left.toString().compareTo(right.toString());
342 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
344 t.push(new Boolean((op[pc] == LT && result < 0) || (op[pc] == LE && result <= 0) ||
345 (op[pc] == GT && result > 0) || (op[pc] == GE && result >= 0)));
354 if (l == null) { Object tmp = r; r = l; l = tmp; }
355 if (l == null && r == null) ret = true;
356 else if (r == null) ret = false; // l != null, so its false
357 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
358 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
359 else if (l instanceof String) ret = r != null && l.equals(r.toString());
360 else ret = l.equals(r);
361 t.push(new Boolean(op[pc] == EQ ? ret : !ret)); break;
364 default: throw new Error("unknown opcode " + op[pc]);
368 // this should never happen, we will ALWAYS have a RETURN at the end of the func
369 throw new Error("Just fell out of CompiledFunction::eval() loop. Last PC was " + lastPC);
372 // Debugging //////////////////////////////////////////////////////////////////////
374 public String toString() {
375 StringBuffer sb = new StringBuffer(1024);
376 sb.append("\n" + sourceName + ": " + firstLine + "\n");
377 for (int i=0; i < size; i++) {
381 sb.append(bytecodeToString[-op[i]]);
383 sb.append(codeToString[op[i]]);
385 sb.append(arg[i] == null ? "(no arg)" : arg[i]);
386 if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
387 sb.append(" jump to ");
388 sb.append(i+((Number) arg[i]).intValue());
392 return sb.toString();
395 // Exception Stuff ////////////////////////////////////////////////////////////////
397 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
398 EvaluatorException ee(String s) { throw new EvaluatorException(sourceName + ":" + JS.Thread.currentJSThread().getLine() + " " + s); }
399 JS.Exn je(String s) { throw new JS.Exn(sourceName + ":" + JS.Thread.currentJSThread().getLine() + " " + s); }
402 // FunctionScope /////////////////////////////////////////////////////////////////
404 private class FunctionScope extends JS.Scope {
406 public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
407 public String getSourceName() { return sourceName; }
411 // Markers //////////////////////////////////////////////////////////////////////
413 public static class CallMarker { public CallMarker() { } }
414 public static class LoopMarker {
417 public LoopMarker(int location, String label) {
418 this.location = location;
422 public static class TryMarker {
424 public JS.Scope scope;
425 public TryMarker(int location, JS.Scope scope) {
426 this.location = location;
433 /** this class exists solely to work around a GCJ bug */
434 abstract class JSCallable extends JS.Callable {
435 public abstract Object call(JS.Array args) throws JS.Exn;