new js api
[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         // FIXME: "trap on property"
21         /*if (scope != null && scope instanceof Trap.TrapScope)
22             addBacktrace("trap on property \"" + ((Trap.TrapScope)scope).t.name + "\"");*/
23         for(int i=stack.size()-1; i>=0; i--) {
24             JS element = stack.elementAt(i);
25             if (element instanceof Interpreter.CallMarker) {
26                 Interpreter.CallMarker cm = (Interpreter.CallMarker)element;
27                 if (cm.f != null)
28                     addBacktrace(cm.f.sourceName + ":" + cm.f.line[cm.pc-1]);
29                 /*if (cm.scope != null && cm.scope instanceof Trap.TrapScope)
30                     addBacktrace("trap on property \"" + ((Trap.TrapScope)cm.scope).t.name + "\"");*/
31             }
32         }
33     }
34     public void printStackTrace() { printStackTrace(System.err); }
35     public void printStackTrace(PrintWriter pw) {
36         for(int i=0; i<backtrace.size(); i++) pw.println("    at " + (String) backtrace.elementAt(i));
37         super.printStackTrace(pw);
38     }
39     public void printStackTrace(PrintStream ps) {
40         for(int i=0; i<backtrace.size(); i++) ps.println("    at " + (String) backtrace.elementAt(i));
41         super.printStackTrace(ps);
42     }
43     public String toString() { return "JSExn: " + JS.debugToString(js); }
44     public String getMessage() { return toString(); }
45     public JS getObject() { return js; } 
46     public void addBacktrace(String line) { backtrace.addElement(line); }
47
48
49     public static class IO extends JSExn {
50         public IO(java.io.IOException ioe) {
51             super("ibex.io: " + ioe.toString());
52             JS.warn(ioe);
53         }
54     }
55