more new js api fixes and cleanup
[org.ibex.core.git] / src / org / ibex / js / JSExn.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL] 
2 package org.ibex.js; 
3
4 import org.ibex.util.*; 
5 import java.io.*;
6
7 /** An exception which can be thrown and caught by JavaScript code */
8 public class JSExn extends Exception { 
9     private Vec backtrace = new Vec();
10     private JS js = null; 
11     public JSExn(String s) { this(JS.S(s)); }
12     public JSExn(JS js) {
13         this.js = js;
14         if (Interpreter.current() != null)
15             fill(Interpreter.current().stack, Interpreter.current().f, Interpreter.current().pc, Interpreter.current().scope);
16     }
17     public JSExn(JS js, Interpreter.Stack stack, JSFunction f, int pc, JSScope scope) { this.js = js; fill(stack, f, pc, scope); }
18     private void fill(Interpreter.Stack stack, JSFunction f, int pc, JSScope scope) {
19         addBacktrace(f.sourceName + ":" + f.line[pc]);
20         for(int i=stack.size()-1; i>=0; i--) {
21             JS element = stack.elementAt(i);
22             if (element instanceof Interpreter.CallMarker) {
23                 Interpreter.CallMarker cm = (Interpreter.CallMarker)element;
24                 if(cm.f == null) break;
25                 String s = cm.f.sourceName + ":" + cm.f.line[cm.pc-1];
26                 if(cm instanceof Interpreter.TrapMarker) 
27                     s += " (trap on " + JS.debugToString(((Interpreter.TrapMarker)cm).key) + ")";
28                 addBacktrace(s);
29             }
30         }
31     }
32     public void printStackTrace() { printStackTrace(System.err); }
33     public void printStackTrace(PrintWriter pw) {
34         for(int i=0; i<backtrace.size(); i++) pw.println("    at " + (String) backtrace.elementAt(i));
35         super.printStackTrace(pw);
36     }
37     public void printStackTrace(PrintStream ps) {
38         for(int i=0; i<backtrace.size(); i++) ps.println("    at " + (String) backtrace.elementAt(i));
39         super.printStackTrace(ps);
40     }
41     public String toString() { return "JSExn: " + JS.debugToString(js); }
42     public String getMessage() { return toString(); }
43     public JS getObject() { return js; } 
44     public void addBacktrace(String line) { backtrace.addElement(line); }
45
46
47     public static class IO extends JSExn {
48         public IO(java.io.IOException ioe) {
49             super("ibex.io: " + ioe.toString());
50             JS.warn(ioe);
51         }
52     }
53