Skip to content

Commit

Permalink
Refactor error messages (#577)
Browse files Browse the repository at this point in the history
* Refactor error messages

* Fix build error

* Fix build error
  • Loading branch information
roastduck authored Jan 10, 2024
1 parent 07e5c59 commit c23e6c6
Show file tree
Hide file tree
Showing 49 changed files with 281 additions and 253 deletions.
5 changes: 3 additions & 2 deletions ffi/pass.cc
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,9 @@ void init_ffi_pass(py::module_ &m) {
#else
#define GPU_ONLY(name, ...) \
name, [](const py::args &, const py::kwargs &) { \
ERROR((std::string)name + " is unavailable because FT_WITH_CUDA is " \
"disabled when building FreeTensor"); \
ERROR(FT_MSG << name \
<< " is unavailable because FT_WITH_CUDA is disabled " \
"when building FreeTensor"); \
}
#endif

Expand Down
1 change: 1 addition & 0 deletions include/config.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <filesystem>
#include <vector>

#include <container_utils.h>
#include <ref.h>

namespace freetensor {
Expand Down
10 changes: 1 addition & 9 deletions include/container_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
#include <range/v3/range.hpp>
#include <range/v3/view.hpp>

#include <except.h>

namespace freetensor {

namespace views = ranges::views;
Expand Down Expand Up @@ -153,13 +151,7 @@ inline std::string tolower(const std::string &s) {
/**
* Python-like slicing that supports negative indexing as reversed indexing
*/
inline std::string slice(const std::string &s, int _begin, int _end) {
int begin = _begin >= 0 ? _begin : s.length() + _begin;
int end = _end >= 0 ? _end : s.length() + _end;
int len = end - begin;
ASSERT(len >= 0);
return s.substr(begin, len);
}
std::string slice(const std::string &s, int begin, int end);
inline std::string slice(const std::string &s, int begin) {
return slice(s, begin, s.length());
}
Expand Down
24 changes: 19 additions & 5 deletions include/except.h
Original file line number Diff line number Diff line change
@@ -1,21 +1,35 @@
#ifndef FREE_TENSOR_EXCEPT_H
#define FREE_TENSOR_EXCEPT_H

#include <iostream>
#include <source_location>
#include <sstream>
#include <stdexcept>
#include <string>

namespace freetensor {

class MessageBuilder {
std::ostringstream os_;

public:
template <typename T> MessageBuilder &operator<<(const T &obj) {
os_ << obj;
return *this;
}

operator std::string() const { return os_.str(); }
};

#define FT_MSG MessageBuilder()

class Error : public std::runtime_error {
public:
// NOTE: `source_location` is intended to have a small size and can be
// copied efficiently.
Error(const std::string &msg,
std::source_location loc = std::source_location::current())
: std::runtime_error((std::string)loc.file_name() + ":" +
std::to_string(loc.line()) + ": " + msg) {}
: std::runtime_error(FT_MSG << loc.file_name() << ":" << loc.line()
<< ": " << msg) {}
};

class StmtNode;
Expand Down Expand Up @@ -131,8 +145,8 @@ void reportWarning(const std::string &msg);

#define WARNING(msg) \
do { \
reportWarning((std::string) "[WARNING] " __FILE__ ":" + \
std::to_string(__LINE__) + ": " + (msg)); \
reportWarning(FT_MSG << "[WARNING] " __FILE__ ":" << __LINE__ << ": " \
<< std::string(msg)); \
} while (0)

#define ASSERT(expr) \
Expand Down
10 changes: 5 additions & 5 deletions include/schedule/as_matmul.h
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ class AsMatMul : public SymbolTable<Mutator> {
int loopLevel = iterMap_.at(var->name_);
if (!HashComparator()(loop(var->name_)->len_, dimLen)) {
throw InvalidSchedule(
"Iterator " + var->name_ + " of " + acc->var_ +
" should loop over the entire range (" + toString(dimLen) +
"), instead of " + toString(loop(var->name_)->len_));
FT_MSG << "Iterator " << var->name_ << " of " << acc->var_
<< " should loop over the entire range (" << dimLen
<< "), instead of " << loop(var->name_)->len_);
}
usedBy[loopLevel] = true;
order.emplace_back(loopLevel);
Expand Down Expand Up @@ -158,8 +158,8 @@ class AsMatMul : public SymbolTable<Mutator> {
if (lastInDim.isValid()) {
if (!lastDimIn) {
throw InvalidSchedule(
"Dimensions " + toString(lastInDim) + " and " +
toString(idx) + " should be contiguous");
FT_MSG << "Dimensions " << lastInDim << " and "
<< idx << " should be contiguous");
}
}
len = len.isValid() ? makeMul(len, dimLen) : (Expr)dimLen;
Expand Down
6 changes: 3 additions & 3 deletions include/schedule/check_not_in_lib.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ namespace freetensor {

inline void checkNotInLib(const Stmt &ast, const ID &stmt) {
if (!findAllStmt(ast, "<MatMul>->>" + toString(stmt)).empty()) {
throw InvalidSchedule("Scheduling " + toString(stmt) +
" inside a sub-program bound to an external "
"library call is meaningless");
throw InvalidSchedule(FT_MSG << "Scheduling " << stmt
<< " inside a sub-program bound to an "
"external library call is meaningless");
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/analyze/find_stmt.cc
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ Stmt findStmt(const Stmt &ast, const ID &id) {
FindStmtById visitor(id);
visitor(ast);
if (!visitor.result().isValid()) {
throw UnexpectedQueryResult("Statement " + toString(id) + " not found");
throw UnexpectedQueryResult(FT_MSG << "Statement " << id
<< " not found");
}
return visitor.result();
}
Expand Down
4 changes: 2 additions & 2 deletions src/autograd/derivative.cc
Original file line number Diff line number Diff line change
Expand Up @@ -419,8 +419,8 @@ void Derivative::visit(const Abs &op) {
}

void Derivative::visit(const Intrinsic &op) {
throw InvalidAutoGrad("Please provide gradient of " + toString(op) +
" explicitly by `UserGrad`");
throw InvalidAutoGrad(FT_MSG << "Please provide gradient of " << op
<< " explicitly by `UserGrad`");
}

} // namespace freetensor
18 changes: 9 additions & 9 deletions src/autograd/merge_tape_input.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ Stmt MergeTapeInput::visitStmt(const Stmt &s) {
for (auto &&dim : newNode->buffer_->tensor()->shape()) {
auto allNamesInDim = allNames(dim);
if (!checkAllDefined(names(), allNamesInDim)) {
ERROR(
"Cannot merge tape inputs, or the shape of the input " +
toString(newNode) + " will be undefined");
ERROR(FT_MSG << "Cannot merge tape inputs, or the shape of "
"the input "
<< newNode << " will be undefined");
}
if (hasIntersect(allWritesInBody, allNamesInDim)) {
ERROR(
"Cannot merge tape inputs, or the shape of the input " +
toString(newNode) + " will be modified");
ERROR(FT_MSG << "Cannot merge tape inputs, or the shape of "
"the input "
<< newNode << " will be modified");
}
}
ret = makeVarDef(newNode->name_, newNode->buffer_, newNode->viewOf_,
Expand Down Expand Up @@ -70,9 +70,9 @@ Stmt mergeTapeInput(const Stmt &op) {
auto &&node = *it;
if (!HashComparator{}(newNode->buffer_->tensor(),
node->buffer_->tensor())) {
ERROR("Cannot merge tape input because " +
toString(newNode) + " and " + toString(node) +
" have different definitions");
ERROR(FT_MSG << "Cannot merge tape input because "
<< newNode << " and " << node
<< " have different definitions");
}
lca = lcaStmt(lca, node);
if (node->buffer_->atype() == AccessType::InputMutable) {
Expand Down
4 changes: 2 additions & 2 deletions src/codegen/detail/code_gen_c.h
Original file line number Diff line number Diff line change
Expand Up @@ -774,8 +774,8 @@ std::string CodeGenC<Stream>::gen(const DataType &dtype) {
case DataType::Bool:
return "bool";
default:
throw InvalidProgram(toString(dtype) +
" is not supported by this codegen backend");
throw InvalidProgram(
FT_MSG << dtype << " is not supported by this codegen backend");
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/config.cc
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ static std::string getStrEnvRequired(const char *name) {
if (auto &&ret = getStrEnv(name); ret.has_value()) {
return *ret;
} else {
ERROR((std::string) "Environment varialbe " + name + " not found");
ERROR(FT_MSG << "Environment varialbe " << name << " not found");
}
}

Expand All @@ -69,9 +69,9 @@ static std::optional<bool> getBoolEnv(const char *name) {
env == "0") {
return false;
} else {
ERROR(
(std::string) "Value of " + name +
" must be true/yes/on/1 or false/no/off/0 (case insensitive)");
ERROR(FT_MSG << "Value of " << name
<< " must be true/yes/on/1 or false/no/off/0 (case "
"insensitive)");
}
} else {
return std::nullopt;
Expand All @@ -98,7 +98,7 @@ Config::checkValidPaths(const std::vector<fs::path> &paths, bool required) {
auto ret =
filter(paths, static_cast<bool (*)(const fs::path &)>(fs::exists));
if (required && ret.empty()) {
ERROR(toString(paths) + " are not valid paths");
ERROR(FT_MSG << paths << " are not valid paths");
}
return ret;
}
Expand Down
14 changes: 14 additions & 0 deletions src/container_utils.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#include <container_utils.h>
#include <except.h>

namespace freetensor {

std::string slice(const std::string &s, int _begin, int _end) {
int begin = _begin >= 0 ? _begin : s.length() + _begin;
int end = _end >= 0 ? _end : s.length() + _end;
int len = end - begin;
ASSERT(len >= 0);
return s.substr(begin, len);
}

} // namespace freetensor
4 changes: 2 additions & 2 deletions src/data_type_infer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ namespace freetensor {

#define CHK_TYPE(cond, dtype, op) \
if (!(cond)(dtype) && (dtype) != DataType::Custom) { \
throw InvalidProgram("Invalid data type " + toString(dtype) + " in " + \
toString(op.self().as<ASTNode>())); \
throw InvalidProgram(FT_MSG << "Invalid data type " << dtype << " in " \
<< op.self().as<ASTNode>()); \
}

/**
Expand Down
50 changes: 24 additions & 26 deletions src/driver.cc
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ static void *requestPtr(const Ref<Array> &arr, const Ref<Device> &device,
d = device;
break;
default:
throw InvalidProgram("An I/O variable cannot have a " +
toString(mtype) + " memory type");
throw InvalidProgram(FT_MSG << "An I/O variable cannot have a " << mtype
<< " memory type");
}
switch (atype) {
case AccessType::Input:
Expand Down Expand Up @@ -306,25 +306,24 @@ void Driver::buildAndLoad() {

dlHandle_ = dlopen(so.c_str(), RTLD_NOW);
if (!dlHandle_) {
throw DriverError((std::string) "Unable to load target code: " +
dlerror());
throw DriverError(FT_MSG << "Unable to load target code: "
<< dlerror());
}

func_ = (void (*)(void **, void **, size_t **, size_t *, void *))dlsym(
dlHandle_, nativeCode_.entry().c_str());
if (!func_) {
throw DriverError((std::string) "Target function not found: " +
dlerror());
throw DriverError(FT_MSG << "Target function not found: " << dlerror());
}

if (!Config::debugBinary()) {
remove(cpp.c_str());
remove(so.c_str());
rmdir(path);
} else {
WARNING((std::string) "debug-binary mode on. The produced files are "
"saved in " +
path);
WARNING(
FT_MSG << "debug-binary mode on. The produced files are saved in "
<< path);
}

switch (dev_->type()) {
Expand Down Expand Up @@ -359,18 +358,18 @@ void Driver::setArgs(const std::vector<Ref<Array>> &args,
ASSERT(param.dtype_.has_value());
ASSERT(param.mtype_.has_value());
if (param.dtype_->base() != args[i]->dtype().base()) {
throw InvalidIO("Cannot pass a " + toString(args[i]->dtype()) +
" Array to the " + std::to_string(j) +
"-th parameter " + param.name_ + " of type " +
toString(*param.dtype_));
throw InvalidIO(FT_MSG << "Cannot pass a " << args[i]->dtype()
<< " Array to the " << j
<< "-th parameter " << param.name_
<< " of type " << *param.dtype_);
}
try {
rawArgs_[j] = requestPtr(args[i], dev_, hostDev_, *param.mtype_,
param.atype_);
} catch (const InvalidIO &e) {
throw InvalidIO("Error passing the " + std::to_string(j) +
"-th parameter " + param.name_ + ": " +
e.what());
throw InvalidIO(FT_MSG << "Error passing the " << j
<< "-th parameter " << param.name_
<< ": " << e.what());
}
}
if (param.isInClosure() && param.updateClosure_) {
Expand All @@ -389,19 +388,18 @@ void Driver::setArgs(const std::vector<Ref<Array>> &args,
ASSERT(param.dtype_.has_value());
ASSERT(param.mtype_.has_value());
if (param.dtype_->base() != value->dtype().base()) {
throw InvalidIO("Cannot pass a " + toString(value->dtype()) +
" Array to the " +
std::to_string(name2param_[key]) +
"-th parameter " + key + " of type " +
toString(*param.dtype_));
throw InvalidIO(FT_MSG << "Cannot pass a " << value->dtype()
<< " Array to the " << name2param_[key]
<< "-th parameter " << key << " of type "
<< *param.dtype_);
}
try {
rawArgs_[paramId] = requestPtr(value, dev_, hostDev_,
*param.mtype_, param.atype_);
} catch (const InvalidIO &e) {
throw InvalidIO("Error passing the " +
std::to_string(name2param_[key]) +
"-th parameter " + key + ": " + e.what());
throw InvalidIO(FT_MSG << "Error passing the "
<< name2param_[key] << "-th parameter "
<< key << ": " << e.what());
}
}
if (param.isInClosure()) {
Expand All @@ -426,8 +424,8 @@ void Driver::setArgs(const std::vector<Ref<Array>> &args,
*param.mtype_, param.atype_);
}
if (rawArg == nullptr) {
throw InvalidIO("The " + std::to_string(i) + "-th parameter " +
param.name_ + " is missing");
throw InvalidIO(FT_MSG << "The " << i << "-th parameter "
<< param.name_ << " is missing");
}
}
}
Expand Down
5 changes: 2 additions & 3 deletions src/driver/array.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@ static std::string writeToBorrowedMsg(const Ref<Device> &lendingDev,
std::ostringstream os;
os << "Attempted to write ";
if (requestDev.isValid()) {
os << "from " + toString(*requestDev) + ", ";
os << "from " << *requestDev << ", ";
}
os << "to a buffer borrowed from an external object at "
<< toString(*lendingDev)
os << "to a buffer borrowed from an external object at " << *lendingDev
<< ". Please either explicitly create a FreeTensor object by "
"`ft.array`, which features automatic inter-device data transfer, or "
"borrow from a object from the same device (e.g., from a "
Expand Down
Loading

0 comments on commit c23e6c6

Please sign in to comment.