pytorch/torch/csrc/jit/source_location.h
Elias Ellison 59f8e8ada7 First step at adding exceptions (#12789)
Summary:
This is a first step towards adding exceptions. We need minimal support in order to begin converting the torch library to weak script mode (which is the main goal here).

Some limitations (that are documented in the tests & compiler):
1. Cannot assign exceptions to variables
2. Any name after raise is being treated as a valid Exception
3. No control flow analysis yet. Below a will be undefined:

if True:
     a = 1
else:
     raise Exception("Hi")
return a
Pull Request resolved: https://github.com/pytorch/pytorch/pull/12789

Differential Revision: D12848936

Pulled By: eellison

fbshipit-source-id: 1f60ceef2381040486123ec797e97d65b074862d
2018-10-30 20:25:50 -07:00

51 lines
1.3 KiB
C++

#pragma once
#include <ostream>
#include <sstream>
#include <stdexcept>
#include <string>
namespace torch { namespace jit {
// SourceLocation represents source code-level debug information for a node.
// It contains information about where a node got generated.
// In the case of tracing this will be a python stack trace.
// In the case of using the scripting frontend this will be backed
// by a SourceRange object
struct SourceLocation {
virtual ~SourceLocation() = default;
virtual void highlight(std::ostream & out) const = 0;
std::string wrapException(const std::exception & e, const std::string & additional = "") {
std::stringstream msg;
msg << "\n" << e.what() << ":\n";
if(!additional.empty()) {
msg << additional << ":\n";
}
highlight(msg);
return msg.str();
}
void wrapAndRethrowException(const std::exception & e, const std::string & additional = "") {
throw std::runtime_error(wrapException(e, additional));
}
};
inline std::ostream& operator<<(std::ostream& out, const SourceLocation& sl) {
sl.highlight(out);
return out;
}
// normally a python stack trace
struct StringSourceLocation : public SourceLocation {
StringSourceLocation(std::string context)
: context(std::move(context)) {}
void highlight(std::ostream & out) const override {
out << context;
}
private:
std::string context;
};
}}