1
2 package org.xwt.js;
3
4 import org.xwt.util.*;
5 import java.io.*;
6
7
8 class CompiledFunctionImpl extends JS.Obj implements ByteCodes, Tokens {
9
10
11
12
13 int numFormalArgs = 20;
14
15
16 String sourceName;
17 public String getSourceName() throws JS.Exn { return sourceName; }
18
19
20 int[] line = new int[10];
21
22
23 private int firstLine = -1;
24
25
26 int[] op = new int[10];
27
28
29 Object[] arg = new Object[10];
30
31
32 int size = 0;
33 int size() { return size; }
34
35
36 JS.Scope parentScope;
37
38
39
40 private CompiledFunctionImpl cloneWithNewParentScope(JS.Scope s) throws IOException {
41 CompiledFunctionImpl ret = new JS.CompiledFunction(sourceName, firstLine, null, s);
42
43
44 ret.op = this.op;
45 ret.arg = this.arg;
46 ret.line = this.line;
47 ret.size = this.size;
48 ret.numFormalArgs = this.numFormalArgs;
49 return ret;
50 }
51
52 protected CompiledFunctionImpl(String sourceName, int firstLine, Reader sourceCode, JS.Scope parentScope) throws IOException {
53 this.sourceName = sourceName;
54 this.firstLine = firstLine;
55 this.parentScope = parentScope;
56 if (sourceCode == null) return;
57 Parser p = new Parser(sourceCode, sourceName, firstLine);
58 while(true) {
59 int s = size();
60 p.parseStatement(this, null);
61 if (s == size()) break;
62 }
63 add(-1, LITERAL, null);
64 add(-1, RETURN);
65 }
66
67
68
69
70
71 int get(int pos) { return op[pos]; }
72 Object getArg(int pos) { return arg[pos]; }
73 void set(int pos, int op_, Object arg_) { op[pos] = op_; arg[pos] = arg_; }
74 void set(int pos, Object arg_) { arg[pos] = arg_; }
75 int pop() { size--; arg[size] = null; return op[size]; }
76 void paste(CompiledFunctionImpl other) { for(int i=0; i<other.size; i++) add(other.line[i], other.op[i], other.arg[i]); }
77 CompiledFunctionImpl add(int line, int op_) { return add(line, op_, null); }
78 CompiledFunctionImpl add(int line, int op_, Object arg_) {
79 if (size == op.length - 1) {
80 int[] line2 = new int[op.length * 2]; System.arraycopy(this.line, 0, line2, 0, op.length); this.line = line2;
81 Object[] arg2 = new Object[op.length * 2]; System.arraycopy(arg, 0, arg2, 0, arg.length); arg = arg2;
82 int[] op2 = new int[op.length * 2]; System.arraycopy(op, 0, op2, 0, op.length); op = op2;
83 }
84 this.line[size] = line;
85 op[size] = op_;
86 arg[size] = arg_;
87 size++;
88 return this;
89 }
90
91 public static int getLine(JS.Thread cx) {
92 if(cx.pc < 0 || cx.pc >= ((CompiledFunctionImpl)cx.currentCompiledFunction).size) return -1;
93 return ((CompiledFunctionImpl)cx.currentCompiledFunction).line[cx.pc];
94 }
95
96
97
98
99
100 static Object eval(final JS.Thread cx) throws JS.Exn {
101 OUTER: for(;; cx.pc++) {
102 try {
103 if (cx.paused) return null;
104 cx.bind();
105 if (cx.tailCallFunction != null) {
106 cx.stack.pop();
107 cx.pc -= 2;
108 cx.stack.push(new CallMarker(cx));
109 cx.stack.push(cx.tailCallArgs);
110 cx.currentCompiledFunction = cx.tailCallFunction;
111 cx.tailCallFunction = null;
112 cx.tailCallArgs = null;
113 cx.scope = new FunctionScope("unknown", cx.currentCompiledFunction.parentScope);
114 cx.pc = 0;
115 }
116 if (cx.currentCompiledFunction == null) return cx.stack.pop();
117 if (cx.pc >= ((CompiledFunctionImpl)cx.currentCompiledFunction).size) return cx.stack.pop();
118 String label = null;
119 int curOP = cx.currentCompiledFunction.op[cx.pc];
120 Object curArg = cx.currentCompiledFunction.arg[cx.pc];
121 if(curOP == FINALLY_DONE) {
122 FinallyData fd = (FinallyData) cx.stack.pop();
123 if(fd == null) continue OUTER;
124 curOP = fd.op;
125 curArg = fd.arg;
126 }
127 switch(curOP) {
128 case LITERAL: cx.stack.push(curArg); break;
129 case OBJECT: cx.stack.push(new JS.Obj()); break;
130 case ARRAY: cx.stack.push(new JS.Array(JS.toNumber(curArg).intValue())); break;
131 case DECLARE: cx.scope.declare((String)(curArg==null ? cx.stack.peek() : curArg)); if(curArg != null) cx.stack.push(curArg); break;
132 case TOPSCOPE: cx.stack.push(cx.scope); break;
133 case JT: if (JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(curArg).intValue() - 1; break;
134 case JF: if (!JS.toBoolean(cx.stack.pop())) cx.pc += JS.toNumber(curArg).intValue() - 1; break;
135 case JMP: cx.pc += JS.toNumber(curArg).intValue() - 1; break;
136 case POP: cx.stack.pop(); break;
137 case SWAP: { Object o1 = cx.stack.pop(); Object o2 = cx.stack.pop(); cx.stack.push(o1); cx.stack.push(o2); break; }
138 case DUP: cx.stack.push(cx.stack.peek()); break;
139 case NEWSCOPE: cx.scope = new JS.Scope(cx.scope); break;
140 case OLDSCOPE: cx.scope = cx.scope.getParentScope(); break;
141 case ASSERT: if (!JS.toBoolean(cx.stack.pop())) throw je("assertion failed"); break;
142 case BITNOT: cx.stack.push(new Long(~JS.toLong(cx.stack.pop()))); break;
143 case BANG: cx.stack.push(new Boolean(!JS.toBoolean(cx.stack.pop()))); break;
144
145 case TYPEOF: {
146 Object o = cx.stack.pop();
147 if (o == null) cx.stack.push(null);
148 else if (o instanceof JS) cx.stack.push(((JS)o).typeName());
149 else if (o instanceof String) cx.stack.push("string");
150 else if (o instanceof Number) cx.stack.push("number");
151 else if (o instanceof Boolean) cx.stack.push("boolean");
152 else cx.stack.push("unknown");
153 break;
154 }
155
156 case NEWFUNCTION: {
157 try {
158 cx.stack.push(((CompiledFunctionImpl)curArg).cloneWithNewParentScope(cx.scope));
159 } catch (IOException e) {
160 throw new Error("this should never happen");
161 }
162 break;
163 }
164
165 case PUSHKEYS: {
166 Object o = cx.stack.peek();
167 Object[] keys = ((JS)o).keys();
168 JS.Array a = new JS.Array();
169 a.setSize(keys.length);
170 for(int j=0; j<keys.length; j++) a.setElementAt(keys[j], j);
171 cx.stack.push(a);
172 break;
173 }
174
175 case LABEL: break;
176 case LOOP: {
177 cx.stack.push(new LoopMarker(cx.pc, cx.pc > 0 && cx.currentCompiledFunction.op[cx.pc - 1] == LABEL ? (String)cx.currentCompiledFunction.arg[cx.pc - 1] : (String)null, cx.scope));
178 cx.stack.push(Boolean.TRUE);
179 break;
180 }
181
182 case BREAK:
183 case CONTINUE:
184 while(cx.stack.size() > 0) {
185 Object o = cx.stack.pop();
186 if (o instanceof CallMarker) ee("break or continue not within a loop");
187 if (o instanceof TryMarker) {
188 if(((TryMarker)o).finallyLoc < 0) continue;
189 cx.stack.push(new FinallyData(curOP, curArg));
190 cx.scope = ((TryMarker)o).scope;
191 cx.pc = ((TryMarker)o).finallyLoc - 1;
192 continue OUTER;
193 }
194 if (o instanceof LoopMarker) {
195 if (curArg == null || curArg.equals(((LoopMarker)o).label)) {
196 int loopInstructionLocation = ((LoopMarker)o).location;
197 int endOfLoop = ((Integer)cx.currentCompiledFunction.arg[loopInstructionLocation]).intValue() + loopInstructionLocation;
198 cx.scope = ((LoopMarker)o).scope;
199 if (curOP == CONTINUE) { cx.stack.push(o); cx.stack.push(Boolean.FALSE); }
200 cx.pc = curOP == BREAK ? endOfLoop - 1 : loopInstructionLocation;
201 continue OUTER;
202 }
203 }
204 }
205 throw new Error("CONTINUE/BREAK invoked but couldn't find a LoopMarker at " + ((CompiledFunctionImpl)cx.currentCompiledFunction).sourceName + ":" + getLine(cx));
206
207 case TRY: {
208 int[] jmps = (int[]) curArg;
209
210
211 cx.stack.push(new TryMarker(jmps[0] < 0 ? -1 : cx.pc + jmps[0], jmps[1] < 0 ? -1 : cx.pc + jmps[1], cx.scope));
212 break;
213 }
214
215 case RETURN: {
216 Object retval = cx.stack.pop();
217 while(cx.stack.size() > 0) {
218 Object o = cx.stack.pop();
219 if (o instanceof TryMarker) {
220 if(((TryMarker)o).finallyLoc < 0) continue;
221 cx.stack.push(retval);
222 cx.stack.push(new FinallyData(RETURN));
223 cx.scope = ((TryMarker)o).scope;
224 cx.pc = ((TryMarker)o).finallyLoc - 1;
225 continue OUTER;
226 }
227 if (o instanceof CallMarker) {
228 cx.scope = ((CallMarker)o).scope;
229 cx.pc = ((CallMarker)o).pc;
230 cx.currentCompiledFunction = (CompiledFunction)((CallMarker)o).currentCompiledFunction;
231 cx.stack.push(retval);
232 continue OUTER;
233 }
234 }
235 throw new Error("error: RETURN invoked but couldn't find a CallMarker!");
236 }
237
238 case PUT: {
239 Object val = cx.stack.pop();
240 Object key = cx.stack.pop();
241 Object target = cx.stack.peek();
242 if (target == null)
243 throw je("tried to put a value to the " + key + " property on the null value");
244 if (!(target instanceof JS))
245 throw je("tried to put a value to the " + key + " property on a " + target.getClass().getName());
246 if (key == null)
247 throw je("tried to assign \"" + (val==null?"(null)":val.toString()) + "\" to the null key");
248 ((JS)target).put(key, val);
249 cx.stack.push(val);
250 break;
251 }
252
253 case GET:
254 case GET_PRESERVE: {
255 ObjectObject
256 if (curOP == GET) {
257 v = curArg == null ? cx.stack.pop() : curArg;
258 o = cx.stack.pop();
259 } else {
260 v = cx.stack.pop();
261 o = cx.stack.peek();
262 cx.stack.push(v);
263 }
264 Object ret = null;
265 if (o == null) throw je("tried to get property \"" + v + "\" from the null value");
266 if (v == null) throw je("tried to get the null key from " + o);
267 if (o instanceof String || o instanceof Number || o instanceof Boolean)
268 ret = Internal.getFromPrimitive(o,v);
269 else if (o instanceof JS) {
270 ret = ((JS)o).get(v);
271 } else
272 throw je("tried to get property " + v + " from a " + o.getClass().getName());
273 cx.stack.push(ret);
274 break;
275 }
276
277 case CALLMETHOD:
278 case CALL:
279 {
280 JS.Array arguments = new JS.Array();
281 int numArgs = JS.toNumber(curArg).intValue();
282 arguments.setSize(numArgs);
283 for(int j=numArgs - 1; j >= 0; j--) arguments.setElementAt(cx.stack.pop(), j);
284 Object o = cx.stack.pop();
285 if(o == null) throw je("attempted to call null");
286 Object ret;
287 if(curOP == CALLMETHOD) {
288 Object method = o;
289 o = cx.stack.pop();
290 if(o instanceof String || o instanceof Number || o instanceof Boolean) {
291 ret = Internal.callMethodOnPrimitive(o,method,arguments);
292 cx.stack.push(ret);
293 break;
294 } else if (o instanceof JS) {
295 if (((JS)o).callMethod(method, arguments, true) == Boolean.TRUE) {
296 ret = ((JS)o).callMethod(method,arguments,false);
297 cx.stack.push(ret);
298 break;
299 } else {
300 o = ((JS)o).get(method);
301 }
302 } else {
303 throw new JS.Exn("Tried to call a method on an object that isn't a JS object: " + o);
304 }
305 }
306
307 if (o instanceof CompiledFunctionImpl) {
308 cx.stack.push(new CallMarker(cx));
309 cx.stack.push(arguments);
310 cx.currentCompiledFunction = (CompiledFunction)o;
311 cx.scope = new FunctionScope("unknown", cx.currentCompiledFunction.parentScope);
312 cx.pc = -1;
313 break;
314
315 } else {
316 ret = ((JS.Callable)o).call(arguments);
317 }
318 cx.stack.push(ret);
319 break;
320 }
321
322 case THROW: {
323 Object o = cx.stack.pop();
324 if(o instanceof JS.Exn) throw (JS.Exn)o;
325 throw new JS.Exn(o);
326 }
327
328 case INC: case DEC: {
329 boolean isPrefix = JS.toBoolean(curArg);
330 Object key = cx.stack.pop();
331 JS obj = (JS)cx.stack.pop();
332 Number num = JS.toNumber(obj.get(key));
333 Number val = new Double(curOP == INC ? num.doubleValue() + 1.0 : num.doubleValue() - 1.0);
334 obj.put(key, val);
335 cx.stack.push(isPrefix ? val : num);
336 break;
337 }
338
339 case ASSIGN_SUB: case ASSIGN_ADD: {
340 Object val = cx.stack.pop();
341 Object old = cx.stack.pop();
342 Object key = cx.stack.pop();
343 Object obj = cx.stack.peek();
344 if (val instanceof CompiledFunction) {
345 if (obj instanceof JS.Scope) {
346 JS.Scope parent = (JS.Scope)obj;
347 while(parent.getParentScope() != null) parent = parent.getParentScope();
348 if (parent instanceof org.xwt.Box) {
349 if (curOP == ASSIGN_ADD) {
350 ((org.xwt.Box)parent).addTrap(key, val);
351 } else {
352 ((org.xwt.Box)parent).delTrap(key, val);
353 }
354
355 cx.pc += ((Integer)curArg).intValue() - 1;
356 break;
357 }
358 }
359 }
360
361 cx.stack.push(key);
362 cx.stack.push(old);
363 cx.stack.push(val);
364 break;
365 }
366
367 case ADD: {
368 int count = ((Number)curArg).intValue();
369 if(count < 2) throw new Error("this should never happen");
370 if(count == 2) {
371
372 Object right = cx.stack.pop();
373 Object left = cx.stack.pop();
374 if(left instanceof String || right instanceof String) cx.stack.push(JS.toString(left).concat(JS.toString(right)));
375 else cx.stack.push(new Double(JS.toDouble(left) + JS.toDouble(right)));
376 } else {
377 Object[] args = new Object[count];
378 while(--count >= 0) args[count] = cx.stack.pop();
379 if(args[0] instanceof String) {
380 StringBuffer sb = new StringBuffer(64);
381 for(int i=0;i<args.length;i++) sb.append(JS.toString(args[i]));
382 cx.stack.push(sb.toString());
383 } else {
384 int numStrings = 0;
385 for(int i=0;i<args.length;i++) if(args[i] instanceof String) numStrings++;
386 if(numStrings == 0) {
387 double d = 0.0;
388 for(int i=0;i<args.length;i++) d += JS.toDouble(args[i]);
389 cx.stack.push(new Double(d));
390 } else {
391 int i=0;
392 StringBuffer sb = new StringBuffer(64);
393 if(!(args[0] instanceof String || args[1] instanceof String)) {
394 double d=0.0;
395 do {
396 d += JS.toDouble(args[i++]);
397 } while(!(args[i] instanceof String));
398 sb.append(JS.toString(new Double(d)));
399 }
400 while(i < args.length) sb.append(JS.toString(args[i++]));
401 cx.stack.push(sb.toString());
402 }
403 }
404 }
405 break;
406 }
407
408 default: {
409 Object right = cx.stack.pop();
410 Object left = cx.stack.pop();
411 switch(curOP) {
412
413 case BITOR: cx.stack.push(new Long(JS.toLong(left) | JS.toLong(right))); break;
414 case BITXOR: cx.stack.push(new Long(JS.toLong(left) ^ JS.toLong(right))); break;
415 case BITAND: cx.stack.push(new Long(JS.toLong(left) & JS.toLong(right))); break;
416
417 case SUB: cx.stack.push(new Double(JS.toDouble(left) - JS.toDouble(right))); break;
418 case MUL: cx.stack.push(new Double(JS.toDouble(left) * JS.toDouble(right))); break;
419 case DIV: cx.stack.push(new Double(JS.toDouble(left) / JS.toDouble(right))); break;
420 case MOD: cx.stack.push(new Double(JS.toDouble(left) % JS.toDouble(right))); break;
421
422 case LSH: cx.stack.push(new Long(JS.toLong(left) << JS.toLong(right))); break;
423 case RSH: cx.stack.push(new Long(JS.toLong(left) >> JS.toLong(right))); break;
424 case URSH: cx.stack.push(new Long(JS.toLong(left) >>> JS.toLong(right))); break;
425
426 case LT: case LE: case GT: case GE: {
427 if (left == null) left = new Integer(0);
428 if (right == null) right = new Integer(0);
429 int result = 0;
430 if (left instanceof String || right instanceof String) {
431 result = left.toString().compareTo(right.toString());
432 } else {
433 result = (int)java.lang.Math.ceil(JS.toDouble(left) - JS.toDouble(right));
434 }
435 cx.stack.push(new Boolean((curOP == LT && result < 0) || (curOP == LE && result <= 0) ||
436 (curOP == GT && result > 0) || (curOP == GE && result >= 0)));
437 break;
438 }
439
440 case EQ:
441 case NE: {
442 Object l = left;
443 Object r = right;
444 boolean ret;
445 if (l == null) { Object tmp = r; r = l; l = tmp; }
446 if (l == null && r == null) ret = true;
447 else if (r == null) ret = false;
448 else if (l instanceof Boolean) ret = new Boolean(JS.toBoolean(r)).equals(l);
449 else if (l instanceof Number) ret = JS.toNumber(r).doubleValue() == JS.toNumber(l).doubleValue();
450 else if (l instanceof String) ret = r != null && l.equals(r.toString());
451 else ret = l.equals(r);
452 cx.stack.push(new Boolean(curOP == EQ ? ret : !ret)); break;
453 }
454
455 default: throw new Error("unknown opcode " + curOP);
456 } }
457 }
458 } catch(JS.Exn e) {
459 while(cx.stack.size() > 0) {
460 Object o = cx.stack.pop();
461 if (o instanceof CatchMarker || o instanceof TryMarker) {
462 boolean inCatch = o instanceof CatchMarker;
463 if(inCatch) {
464 o = cx.stack.pop();
465 if(((TryMarker)o).finallyLoc < 0) continue;
466 }
467 if(!inCatch && ((TryMarker)o).catchLoc >= 0) {
468
469 cx.stack.push(o);
470 cx.stack.push(catchMarker);
471 cx.stack.push(e.getObject());
472 cx.scope = ((TryMarker)o).scope;
473 cx.pc = ((TryMarker)o).catchLoc - 1;
474 continue OUTER;
475 } else {
476 cx.stack.push(e);
477 cx.stack.push(new FinallyData(THROW));
478 cx.scope = ((TryMarker)o).scope;
479 cx.pc = ((TryMarker)o).finallyLoc - 1;
480 continue OUTER;
481 }
482 }
483
484 if(o instanceof CallMarker) throw e;
485 }
486 throw e;
487 }
488 }
489 }
490
491
492
493 public String toString() {
494 StringBuffer sb = new StringBuffer(1024);
495 sb.append("\n" + sourceName + ": " + firstLine + "\n");
496 for (int i=0; i < size; i++) {
497 sb.append(i);
498 sb.append(": ");
499 if (op[i] < 0)
500 sb.append(bytecodeToString[-op[i]]);
501 else
502 sb.append(codeToString[op[i]]);
503 sb.append(" ");
504 sb.append(arg[i] == null ? "(no arg)" : arg[i]);
505 if((op[i] == JF || op[i] == JT || op[i] == JMP) && arg[i] != null && arg[i] instanceof Number) {
506 sb.append(" jump to ").append(i+((Number) arg[i]).intValue());
507 } else if(op[i] == TRY) {
508 int[] jmps = (int[]) arg[i];
509 sb.append(" catch: ").append(jmps[0] < 0 ? "No catch block" : ""+(i+jmps[0]));
510 sb.append(" finally: ").append(jmps[1] < 0 ? "No finally block" : ""+(i+jmps[1]));
511 }
512 sb.append("\n");
513 }
514 return sb.toString();
515 }
516
517
518
519 static class EvaluatorException extends RuntimeException { public EvaluatorException(String s) { super(s); } }
520 static EvaluatorException ee(String s) { throw new EvaluatorException(((CompiledFunctionImpl)(JS.Thread.current()).currentCompiledFunction).sourceName + ":" + JS.Thread.current().getLine() + " " + s); }
521 static JS.Exn je(String s) { throw new JS.Exn(((CompiledFunctionImpl)(JS.Thread.current()).currentCompiledFunction).sourceName + ":" + JS.Thread.current().getLine() + " " + s); }
522
523
524
525
526 static class FunctionScope extends JS.Scope {
527 String sourceName;
528 public FunctionScope(String sourceName, Scope parentScope) { super(parentScope); this.sourceName = sourceName; }
529 public String getSourceName() { return sourceName; }
530 }
531
532
533
534
535 public static class CallMarker {
536 int pc;
537 Scope scope;
538 CompiledFunctionImpl currentCompiledFunction;
539 public CallMarker(JS.Thread cx) { pc = cx.pc + 1; scope = cx.scope; currentCompiledFunction = cx.currentCompiledFunction; }
540 }
541
542 public static class CatchMarker { public CatchMarker() { } }
543 private static CatchMarker catchMarker = new CatchMarker();
544
545 public static class LoopMarker {
546 public int location;
547 public String label;
548 public JS.Scope scope;
549 public LoopMarker(int location, String label, JS.Scope scope) {
550 this.location = location;
551 this.label = label;
552 this.scope = scope;
553 }
554 }
555 public static class TryMarker {
556 public int catchLoc;
557 public int finallyLoc;
558 public JS.Scope scope;
559 public TryMarker(int catchLoc, int finallyLoc, JS.Scope scope) {
560 this.catchLoc = catchLoc;
561 this.finallyLoc = finallyLoc;
562 this.scope = scope;
563 }
564 }
565 public static class FinallyData {
566 public int op;
567 public Object arg;
568 public FinallyData(int op, Object arg) { this.op = op; this.arg = arg; }
569 public FinallyData(int op) { this(op,null); }
570 }
571 }
572
573
574 abstract class JSCallable extends JS.Callable {
575 public abstract Object call(JS.Array args) throws JS.Exn;
576 }
577