fixed heinous breakage, added backtrace support
[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 Object js = null; 
11     public JSExn(Object js) {
12         this.js = js;
13         if (Interpreter.current() != null)
14             fill(Interpreter.current().stack, Interpreter.current().f, Interpreter.current().pc, Interpreter.current().scope);
15     }
16     public JSExn(Object js, Vec stack, JSFunction f, int pc, JSScope scope) { this.js = js; fill(stack, f, pc, scope); }
17     private void fill(Vec stack, JSFunction f, int pc, JSScope scope) {
18         addBacktrace(f.sourceName + ":" + f.line[pc]);
19         if (scope != null && scope instanceof Trap.TrapScope)
20             addBacktrace("trap on property \"" + ((Trap.TrapScope)scope).t.name + "\"");
21         for(int i=stack.size()-1; i>=0; i--) {
22             Object element = stack.elementAt(i);
23             if (element instanceof Interpreter.CallMarker) {
24                 Interpreter.CallMarker cm = (Interpreter.CallMarker)element;
25                 if (cm.f != null)
26                     addBacktrace(cm.f.sourceName + ":" + cm.f.line[cm.pc]);
27                 if (cm.scope != null && cm.scope instanceof Trap.TrapScope)
28                     addBacktrace("trap on property \"" + ((Trap.TrapScope)cm.scope).t.name + "\"");
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; }
42     public String getMessage() { return toString(); }
43     public Object getObject() { return js; } 
44     public void addBacktrace(String line) { backtrace.addElement(line); }
45
46
47 /** should only be used for failed coercions */
48 class JSRuntimeExn extends RuntimeException {
49     private Object js = null; 
50     public JSRuntimeExn(Object js) { this.js = js; } 
51     public String toString() { return "JSRuntimeExn: " + js; }
52     public String getMessage() { return toString(); }
53     public Object getObject() { return js; } 
54 }
55