package org.jruby;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.Exception;
import org.jruby.exceptions.JumpException.FlowControlException;
import org.jruby.exceptions.RaiseException;
import org.jruby.java.proxies.ConcreteJavaProxy;
import org.jruby.runtime.*;
import org.jruby.runtime.backtrace.BacktraceData;
import org.jruby.runtime.backtrace.RubyStackTraceElement;
import org.jruby.runtime.backtrace.TraceType;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.RubyStringBuilder;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import static org.jruby.runtime.Visibility.PRIVATE;
import static org.jruby.util.RubyStringBuilder.str;
@JRubyClass(name="Exception")
public class RubyException extends RubyObject {
private static class Backtrace {
private BacktraceData backtraceData;
private IRubyObject backtraceObject;
private IRubyObject backtraceLocations;
public void copy(Backtrace clone) {
this.backtraceData = clone.backtraceData;
this.backtraceObject = clone.backtraceObject;
this.backtraceLocations = clone.backtraceLocations;
}
public final IRubyObject getBacktraceObject(Ruby runtime) {
IRubyObject backtraceObject = this.backtraceObject;
if (backtraceObject != null) return backtraceObject;
if (backtraceData == null || backtraceData == BacktraceData.EMPTY) return runtime.getNil();
return this.backtraceObject = TraceType.generateMRIBacktrace(runtime, backtraceData.getBacktrace(runtime));
}
public IRubyObject getBacktraceLocations(ThreadContext context) {
if (backtraceLocations != null) return backtraceLocations;
if (backtraceData == null) {
backtraceLocations = context.nil;
} else {
Ruby runtime = context.runtime;
backtraceLocations = RubyThread.Location.newLocationArray(runtime, backtraceData.getBacktrace(runtime));
}
return backtraceLocations;
}
}
public static final int TRACE_HEAD = 8;
public static final int TRACE_TAIL = 4;
public static final int TRACE_MAX = RubyException.TRACE_HEAD + RubyException.TRACE_TAIL + 6;
private final Backtrace backtrace = new Backtrace();
IRubyObject message;
private IRubyObject cause = null;
private RaiseException throwable;
protected RubyException(Ruby runtime, RubyClass rubyClass) {
super(runtime, rubyClass);
}
public RubyException(Ruby runtime, RubyClass rubyClass, String message) {
super(runtime, rubyClass);
this.setMessage(message == null ? runtime.getNil() : runtime.newString(message));
}
@JRubyMethod(name = "exception", optional = 1, rest = true, meta = true)
public static IRubyObject exception(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return ((RubyClass) recv).newInstance(context, args, block);
}
@JRubyMethod(name = "===", meta = true)
public static IRubyObject op_eqq(ThreadContext context, IRubyObject recv, IRubyObject other) {
Ruby runtime = context.runtime;
if (other instanceof ConcreteJavaProxy &&
(recv == runtime.getException() || recv == runtime.getStandardError())) {
Object object = ((ConcreteJavaProxy)other).getObject();
if (object instanceof Throwable && !(object instanceof FlowControlException)) {
if (recv == runtime.getException() || object instanceof java.lang.Exception) {
return context.tru;
}
}
}
return ((RubyClass)recv).op_eqq(context, other);
}
protected RaiseException constructThrowable(String message) {
return new Exception(message, this);
}
public static RubyClass createExceptionClass(Ruby runtime) {
RubyClass exceptionClass = runtime.defineClass("Exception", runtime.getObject(), EXCEPTION_ALLOCATOR);
runtime.setException(exceptionClass);
exceptionClass.setClassIndex(ClassIndex.EXCEPTION);
exceptionClass.setReifiedClass(RubyException.class);
exceptionClass.setMarshal(EXCEPTION_MARSHAL);
exceptionClass.defineAnnotatedMethods(RubyException.class);
return exceptionClass;
}
public static ObjectAllocator EXCEPTION_ALLOCATOR = (runtime, klass) -> new RubyException(runtime, klass);
private static final ObjectMarshal<RubyException> EXCEPTION_MARSHAL = new ObjectMarshal<RubyException>() {
@Override
public void marshalTo(Ruby runtime, RubyException exc, RubyClass type,
MarshalStream marshalStream) throws IOException {
marshalStream.registerLinkTarget(exc);
List<Variable<Object>> attrs = exc.getVariableList();
attrs.add(new VariableEntry<>("mesg", exc.getMessage()));
attrs.add(new VariableEntry<>("bt", exc.getBacktrace()));
marshalStream.dumpVariables(attrs);
}
@Override
public RubyException unmarshalFrom(Ruby runtime, RubyClass type,
UnmarshalStream unmarshalStream) throws IOException {
RubyException exc = (RubyException) type.allocate();
unmarshalStream.registerLinkTarget(exc);
unmarshalStream.defaultVariablesUnmarshal(exc);
exc.setMessage((IRubyObject) exc.removeInternalVariable("mesg"));
exc.set_backtrace((IRubyObject) exc.removeInternalVariable("bt"));
return exc;
}
};
public static RubyException newException(Ruby runtime, RubyClass excptnClass, String msg) {
if (msg == null) {
msg = "No message available";
}
return (RubyException) excptnClass.newInstance(runtime.getCurrentContext(), RubyString.newString(runtime, msg), Block.NULL_BLOCK);
}
@Deprecated
public static IRubyObject newException(ThreadContext context, RubyClass exceptionClass, IRubyObject message) {
return exceptionClass.callMethod(context, "new", message.convertToString());
}
@JRubyMethod
public IRubyObject full_message(ThreadContext context) {
return full_message(context, null);
}
@JRubyMethod
public IRubyObject full_message(ThreadContext context, IRubyObject opts) {
return RubyString.newString(context.runtime, TraceType.printFullMessage(context, this, opts));
}
@JRubyMethod(optional = 2, visibility = PRIVATE)
public IRubyObject initialize(IRubyObject[] args, Block block) {
if ( args.length == 1 ) setMessage(args[0]);
return this;
}
@JRubyMethod
public IRubyObject backtrace() {
return getBacktrace();
}
@JRubyMethod(required = 1)
public IRubyObject set_backtrace(IRubyObject obj) {
setBacktrace(obj);
return backtrace();
}
public void setBacktrace(IRubyObject obj) {
if (obj.isNil() || isArrayOfStrings(obj)) {
backtrace.backtraceObject = obj;
} else if (obj instanceof RubyString) {
backtrace.backtraceObject = RubyArray.newArray(getRuntime(), obj);
} else {
throw getRuntime().newTypeError("backtrace must be Array of String");
}
}
@JRubyMethod(omit = true)
public IRubyObject backtrace_locations(ThreadContext context) {
return backtrace.getBacktraceLocations(context);
}
@JRubyMethod(optional = 1)
public RubyException exception(IRubyObject[] args) {
switch (args.length) {
case 0 :
return this;
case 1 :
if (args[0] == this) return this;
RubyException ret = (RubyException) rbClone();
ret.initialize(args, Block.NULL_BLOCK);
return ret;
default :
throw getRuntime().newArgumentError("Wrong argument count");
}
}
@JRubyMethod(name = "to_s")
public IRubyObject to_s(ThreadContext context) {
final IRubyObject msg = getMessage();
if ( ! msg.isNil() ) return msg.asString();
return context.runtime.newString(getMetaClass().getRealClass().getName());
}
@Deprecated
public IRubyObject to_s19(ThreadContext context) { return to_s(context); }
@JRubyMethod(name = "message")
public IRubyObject message(ThreadContext context) {
return callMethod(context, "to_s");
}
@JRubyMethod(name = "inspect")
public RubyString inspect(ThreadContext context) {
RubyString rubyClass = getMetaClass().getRealClass().rubyName();
RubyString exception = RubyString.objAsString(context, this);
if (exception.isEmpty()) return rubyClass;
return RubyString.newString(context.runtime, str(context.runtime, "#<", rubyClass, ": ", exception, ">"));
}
@Override
@JRubyMethod(name = "==")
public RubyBoolean op_equal(ThreadContext context, IRubyObject other) {
if (this == other) return context.tru;
boolean equal = context.runtime.getException().isInstance(other) &&
getMetaClass().getRealClass() == other.getMetaClass().getRealClass() &&
callMethod(context, "message").equals(other.callMethod(context, "message")) &&
callMethod(context, "backtrace").equals(other.callMethod(context, "backtrace"));
return context.runtime.newBoolean(equal);
}
@JRubyMethod(name = "cause")
public IRubyObject cause(ThreadContext context) {
return cause == null ? context.nil : cause;
}
@Override
public <T> T toJava(Class<T> target) {
if (target != Object.class && target.isAssignableFrom(RaiseException.class)) {
return target.cast(toThrowable());
}
return super.toJava(target);
}
public RaiseException toThrowable() {
if (throwable == null) {
return throwable = constructThrowable(getMessageAsJavaString());
}
return throwable;
}
public void setCause(IRubyObject cause) {
this.cause = cause;
}
public Object getCause() {
return cause;
}
public RubyStackTraceElement[] getBacktraceElements() {
if (backtrace.backtraceData == null) {
return RubyStackTraceElement.EMPTY_ARRAY;
}
return backtrace.backtraceData.getBacktrace(getRuntime());
}
public void captureBacktrace(ThreadContext context) {
backtrace.backtraceData = context.runtime.getInstanceConfig().getTraceType().getBacktrace(context);
}
public IRubyObject getBacktrace() {
IRubyObject backtraceObject = backtrace.backtraceObject;
if (backtraceObject != null) {
return backtrace.backtraceObject;
}
Ruby runtime = getRuntime();
return backtrace.getBacktraceObject(runtime);
}
@Override
public void copySpecialInstanceVariables(IRubyObject clone) {
RubyException exception = (RubyException)clone;
exception.backtrace.copy(backtrace);
exception.message = message;
}
public void printBacktrace(PrintStream errorStream) {
printBacktrace(errorStream, 0);
}
public void printBacktrace(PrintStream errorStream, int skip) {
IRubyObject trace = callMethod(getRuntime().getCurrentContext(), "backtrace");
TraceType.printBacktraceToStream(trace, errorStream, skip);
}
private boolean isArrayOfStrings(IRubyObject backtrace) {
if (!(backtrace instanceof RubyArray)) return false;
final RubyArray rTrace = ((RubyArray) backtrace);
for (int i = 0 ; i < rTrace.getLength() ; i++) {
if (!(rTrace.eltInternal(i) instanceof RubyString)) return false;
}
return true;
}
public IRubyObject getMessage() {
return message == null ? getRuntime().getNil() : message;
}
public void setMessage(IRubyObject message) {
this.message = message;
}
public String getMessageAsJavaString() {
final IRubyObject msg = getMessage();
return msg.isNil() ? null : msg.toString();
}
@Override
public List<Variable<Object>> getVariableList() {
List<Variable<Object>> attrs = super.getVariableList();
attrs.add(new VariableEntry<>("mesg", getMessage()));
IRubyObject backtrace = getBacktrace();
attrs.add(new VariableEntry<>("bt", backtrace));
return attrs;
}
@Override
public List<String> getVariableNameList() {
List<String> names = super.getVariableNameList();
names.add("mesg");
names.add("bt");
return names;
}
@Deprecated
public void prepareIntegratedBacktrace(ThreadContext context, StackTraceElement[] javaTrace) {
if (backtrace.backtraceData == null) {
backtrace.backtraceData = context.runtime.getInstanceConfig().getTraceType().getIntegratedBacktrace(context, javaTrace);
}
}
}