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