This is an automated email from the ASF dual-hosted git repository.
tqchen pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tvm-tirx.git
The following commit(s) were added to refs/heads/main by this push:
new de910cb7d [FEAT] Render structural callback failures as underlined
TVMScript (#147)
de910cb7d is described below
commit de910cb7df3ff2c6927ab77cc108f71a6a6a7a10
Author: Tianqi Chen <[email protected]>
AuthorDate: Sat Oct 31 20:15:53 2026 -0400
[FEAT] Render structural callback failures as underlined TVMScript (#147)
Structural callback failures now append an underlined TVMScript location
through the concrete root IR type's FFI error hook. The shared renderer
resolves exact and prefix access paths against the supplied traversal
root, preserves the original error and traceback, and consumes visit
context after successful rendering.
Register enrichment alongside repr through `RegisterScriptRepr`, with
both redirect helpers in `tvm::script::printer` and declared in
`support.h`. Share the renderer with pass error handling while
preserving its module/function selection and normal function-pass
execution.
This pins current `tvm-ffi` main
(`69be48a2931505255733bfc5a18d6e0e5cc1a033`) for exact-type hooks and
container-aware paths. A supporting published FFI runtime is still
required for packaged use: the latest `apache-tvm-ffi==0.1.15.post2`
does not invoke these hooks. Source builds must install the pinned FFI
source; the package minimum will need to be raised when a supporting
release is available.
---
3rdparty/tvm-ffi | 2 +-
include/tvm/ir/transform.h | 10 ++---
include/tvm/script/printer/config.h | 13 +------
include/tvm/script/printer/support.h | 33 +++++++++++++---
src/ir/transform.cc | 67 +++++++++++++--------------------
src/script/printer/printer.cc | 36 ++++++++++--------
tests/python/ir/test_structural_walk.py | 19 +++++++++-
7 files changed, 101 insertions(+), 79 deletions(-)
diff --git a/3rdparty/tvm-ffi b/3rdparty/tvm-ffi
index e9fdc58fa..69be48a29 160000
--- a/3rdparty/tvm-ffi
+++ b/3rdparty/tvm-ffi
@@ -1 +1 @@
-Subproject commit e9fdc58fa4bf2e60ed701dacac48a01e41a3dc1f
+Subproject commit 69be48a2931505255733bfc5a18d6e0e5cc1a033
diff --git a/include/tvm/ir/transform.h b/include/tvm/ir/transform.h
index bd3035a6a..27fe8f922 100644
--- a/include/tvm/ir/transform.h
+++ b/include/tvm/ir/transform.h
@@ -458,14 +458,12 @@ TVM_TIRX_DLL Pass PrintIR(ffi::String header = "");
* its visit context so outer handlers do not append the location again.
*
* \param err The original error.
- * \param mod The module containing the visited nodes.
- * \param context The operation description preceding the location.
- * \param func Optional function to search before falling back to the module.
+ * \param root The IR root containing the visited nodes.
+ * \param context Optional operation description preceding the location.
* \return The enriched error, or the original error on fallback.
*/
-TVM_TIRX_DLL ffi::Error EnrichErrorWithContext(
- const ffi::Error& err, const IRModule& mod, ffi::String context,
- ffi::Optional<GlobalVar> func = ffi::Optional<GlobalVar>(std::nullopt));
+TVM_TIRX_DLL ffi::Error EnrichErrorWithContext(const ffi::Error& err, const
ffi::ObjectRef& root,
+ ffi::String context = "");
/*!
* \brief Enrich a pass-time error with a TVMScript-rendered, underlined source
diff --git a/include/tvm/script/printer/config.h
b/include/tvm/script/printer/config.h
index 7e80f1ccd..d409242ee 100644
--- a/include/tvm/script/printer/config.h
+++ b/include/tvm/script/printer/config.h
@@ -20,8 +20,8 @@
* \file tvm/script/printer/config.h
* \brief Configuration object for the TVMScript printer.
*
- * Contains PrinterConfig / PrinterConfigObj, GetBuiltinKeywords,
GetExtraConfig,
- * and RedirectedReprPrinterMethod. Translation APIs live in doc_translator.h,
+ * Contains PrinterConfig / PrinterConfigObj, GetBuiltinKeywords, and
GetExtraConfig.
+ * Translation APIs live in doc_translator.h, registration helpers live in
support.h,
* and text entry points live in printer.h.
*/
#ifndef TVM_SCRIPT_PRINTER_CONFIG_H_
@@ -122,14 +122,5 @@ class TVM_TIRX_DLL PrinterConfig : public ffi::ObjectRef {
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(PrinterConfig, ffi::ObjectRef,
PrinterConfigObj);
};
-/*!
- * \brief Render an IR object for its registered repr callback.
- *
- * Tries to translate \p obj directly; on error falls back to a plain
- * address string. Defined in src/script/printer/script_printer.cc so that
- * <tvm/runtime/logging.h> is not pulled into this public header.
- */
-TVM_TIRX_DLL ffi::String RedirectedReprPrinterMethod(const ffi::ObjectRef&
obj);
-
} // namespace tvm
#endif // TVM_SCRIPT_PRINTER_CONFIG_H_
diff --git a/include/tvm/script/printer/support.h
b/include/tvm/script/printer/support.h
index 90fd671a8..64c40f82c 100644
--- a/include/tvm/script/printer/support.h
+++ b/include/tvm/script/printer/support.h
@@ -24,6 +24,7 @@
#define TVM_SCRIPT_PRINTER_SUPPORT_H_
#include <tvm/ffi/extra/dataclass.h>
+#include <tvm/ffi/extra/visit_error_context.h>
#include <tvm/ffi/reflection/registry.h>
#include <tvm/ir/expr.h>
#include <tvm/script/printer/config.h>
@@ -33,14 +34,36 @@ namespace tvm {
namespace script {
namespace printer {
-/*! \brief Register TVMScript as the FFI repr renderer for ObjectType. */
+/*!
+ * \brief Render an IR object for its registered repr callback.
+ *
+ * Tries to translate \p obj directly; on error falls back to a plain
+ * address string. Defined in src/script/printer/printer.cc so that
+ * <tvm/runtime/logging.h> is not pulled into this public header.
+ */
+TVM_TIRX_DLL ffi::String RedirectReprPrinterMethod(const ffi::ObjectRef& obj);
+
+/*!
+ * \brief Render visit-error context through the shared IR error renderer.
+ * \param error The original callback error, with traversal breadcrumbs.
+ * \param root The original structural operation root.
+ * \return The enriched error, or the original error if rendering is
unavailable.
+ */
+TVM_TIRX_DLL ffi::Error RedirectVisitErrorEnrichMethod(const ffi::Error& error,
+ const ffi::ObjectRef&
root);
+
+/*! \brief Register TVMScript repr and visit-error rendering for ObjectType. */
template <typename ObjectType>
void RegisterScriptRepr() {
namespace refl = ffi::reflection;
- refl::TypeAttrDef<ObjectType>().def(ffi::type_attr::kRepr.name,
- [](ffi::ObjectRef obj, ffi::Function) ->
ffi::String {
- return
RedirectedReprPrinterMethod(obj);
- });
+ refl::TypeAttrDef<ObjectType>()
+ .def(ffi::type_attr::kRepr.name,
+ [](ffi::ObjectRef obj, ffi::Function) -> ffi::String {
+ return RedirectReprPrinterMethod(obj);
+ })
+ .def(ffi::type_attr::kEnrichVisitError.name, [](ffi::Error error,
ffi::ObjectRef root) {
+ return RedirectVisitErrorEnrichMethod(error, root);
+ });
}
/*!
diff --git a/src/ir/transform.cc b/src/ir/transform.cc
index 12e4c5ba5..117b5c49c 100644
--- a/src/ir/transform.cc
+++ b/src/ir/transform.cc
@@ -316,56 +316,43 @@ std::optional<std::string>
RenderScriptWithUnderline(const ffi::ObjectRef& node,
}
} // namespace
-ffi::Error EnrichErrorWithContext(const ffi::Error& err, const IRModule& mod,
ffi::String context,
- ffi::Optional<GlobalVar> func) {
- namespace ffi = tvm::ffi;
- // No visit-context payload => nothing to resolve; return the error
untouched.
- // (The enriched error below drops the payload, so an outer catch that
- // re-enriches lands here and returns unchanged — no double location block.)
+ffi::Error EnrichErrorWithContext(const ffi::Error& err, const ffi::ObjectRef&
root,
+ ffi::String context) {
auto visit_ctx = ffi::VisitErrorContext::TryGetFromError(err);
if (!visit_ctx) return err;
-
- // Resolve + render against the local function when requested, else the
module.
- // Fall back to the module root if the function is missing or yields no path.
- ffi::ObjectRef root = mod;
- if (func.has_value()) {
- if (auto bf = mod->functions.Get(func.value())) {
- root = bf.value();
- } else {
- func = ffi::Optional<GlobalVar>(std::nullopt);
- }
- }
-
- auto try_render = [&](const ffi::ObjectRef& search_root) ->
std::optional<std::string> {
- // Prefer the precise throw site. Prefix matches may include unrelated
- // leaves of an enclosing statement before the full match in traversal
order.
- auto paths = ffi::VisitErrorContext::FindAccessPaths(search_root,
visit_ctx.value());
+ try {
+ auto paths = ffi::VisitErrorContext::FindAccessPaths(root,
visit_ctx.value());
if (paths.empty()) {
- paths = ffi::VisitErrorContext::FindAccessPaths(search_root,
visit_ctx.value(),
+ paths = ffi::VisitErrorContext::FindAccessPaths(root, visit_ctx.value(),
/*allow_prefix_match=*/true);
}
- if (paths.empty()) return std::nullopt;
- return RenderScriptWithUnderline(search_root, paths[0]);
- };
-
- std::optional<std::string> snippet = try_render(root);
- if (!snippet && func.has_value()) {
- // Function-local resolution failed; retry against the whole module.
- snippet = try_render(mod);
+ if (paths.empty()) return err;
+ auto snippet = RenderScriptWithUnderline(root, paths[0]);
+ if (!snippet) return err;
+
+ // Successful rendering consumes the visit context, so enclosing boundaries
+ // do not append a second location. Preserve the original failure and
trace.
+ std::ostringstream suffix;
+ suffix << "\n\n";
+ if (!context.empty()) suffix << context << "\n";
+ suffix << kLocationMarker << "\n" << snippet.value();
+ return ffi::Error(err.kind(), err.message() + suffix.str(),
err.backtrace(), err.cause_chain(),
+ std::nullopt);
+ } catch (...) {
+ return err;
}
- if (!snippet) return err;
-
- // Append the operation context + underlined TVMScript location. Preserve
kind,
- // original message, and backtrace; drop the VisitErrorContext payload so an
- // outer catch does not re-enrich.
- std::ostringstream suffix;
- suffix << "\n\n" << context << "\n" << kLocationMarker << "\n" <<
snippet.value();
- return ffi::Error(err.kind(), err.message() + suffix.str(), err.backtrace());
}
ffi::Error EnrichPassErrorWithContext(const ffi::Error& err, const IRModule&
mod,
ffi::String pass_name,
ffi::Optional<GlobalVar> func) {
- return EnrichErrorWithContext(err, mod, "Error in pass: " + pass_name, func);
+ ffi::String context = "Error in pass: " + pass_name;
+ if (func.has_value()) {
+ if (auto root = mod->functions.Get(func.value())) {
+ ffi::Error enriched = EnrichErrorWithContext(err, root.value(), context);
+ if (!enriched.same_as(err)) return enriched;
+ }
+ }
+ return EnrichErrorWithContext(err, mod, context);
}
IRModule Pass::operator()(IRModule mod, const PassContext& pass_ctx) const {
diff --git a/src/script/printer/printer.cc b/src/script/printer/printer.cc
index 7f13bdd2e..662796fef 100644
--- a/src/script/printer/printer.cc
+++ b/src/script/printer/printer.cc
@@ -21,10 +21,12 @@
#include <tvm/ffi/reflection/accessor.h>
#include <tvm/ffi/reflection/registry.h>
#include <tvm/ir/function.h>
+#include <tvm/ir/transform.h>
#include <tvm/runtime/logging.h>
#include <tvm/script/printer/doc.h>
#include <tvm/script/printer/doc_translator.h>
#include <tvm/script/printer/printer.h>
+#include <tvm/script/printer/support.h>
#include <algorithm>
#include <functional>
@@ -435,6 +437,25 @@ ffi::String RenderScript(const ffi::ObjectRef& obj, const
PrinterConfig& config)
} // namespace
+ffi::String RedirectReprPrinterMethod(const ffi::ObjectRef& obj) {
+ try {
+ PrinterConfig config;
+ config->extra_config.Set("ir.comment_imports", true);
+ // Call translation directly so an unsupported type cannot recurse through
ffi repr.
+ return RenderScript(obj, config);
+ } catch (const tvm::ffi::Error& e) {
+ LOG(WARNING) << "TVMScript printer falls back to the basic address printer
with the error:\n"
+ << e.what();
+ std::ostringstream os;
+ os << obj->GetTypeKey() << '(' << obj.get() << ')';
+ return os.str();
+ }
+}
+
+ffi::Error RedirectVisitErrorEnrichMethod(const ffi::Error& error, const
ffi::ObjectRef& root) {
+ return transform::EnrichErrorWithContext(error, root);
+}
+
} // namespace printer
} // namespace script
namespace {
@@ -470,19 +491,4 @@ ffi::String Script(const ffi::ObjectRef& node, const
ffi::Optional<PrinterConfig
return script::printer::RenderScript(node, config);
}
-ffi::String RedirectedReprPrinterMethod(const ffi::ObjectRef& obj) {
- try {
- PrinterConfig config;
- config->extra_config.Set("ir.comment_imports", true);
- // Call translation directly so an unsupported type cannot recurse through
ffi repr.
- return script::printer::RenderScript(obj, config);
- } catch (const tvm::ffi::Error& e) {
- LOG(WARNING) << "TVMScript printer falls back to the basic address printer
with the error:\n"
- << e.what();
- std::ostringstream os;
- os << obj->GetTypeKey() << '(' << obj.get() << ')';
- return os.str();
- }
-}
-
} // namespace tvm
diff --git a/tests/python/ir/test_structural_walk.py
b/tests/python/ir/test_structural_walk.py
index e7c545b7a..9b4f08ebe 100644
--- a/tests/python/ir/test_structural_walk.py
+++ b/tests/python/ir/test_structural_walk.py
@@ -15,10 +15,11 @@
# specific language governing permissions and limitations
# under the License.
+import pytest
import tvm_ffi
import tvm_tirx.testing
-from tvm_tirx import tirx
+from tvm_tirx import ir, tirx
def test_mixed_iter_type_detection_interrupts_walk():
@@ -45,5 +46,21 @@ def test_mixed_iter_type_detection_interrupts_walk():
assert not any(var.same_as(unreachable) for var in visited)
+def test_callback_error_underlines_traversal_root():
+ addition = tirx.Var("x", "int32") + 1
+ root = ir.SeqStmt([ir.Evaluate(addition)])
+
+ def fail(node):
+ raise ValueError("unexpected addition")
+
+ with pytest.raises(ValueError, match="unexpected addition") as caught:
+ tvm_ffi.structural_walk(root, (type(addition), fail))
+ message = str(caught.value)
+ assert message.count("Location (TVMScript):") == 1
+ assert "x + 1" in message
+ assert "^" in message
+ assert caught.value.__tvm_ffi_error__.extra_context is None
+
+
if __name__ == "__main__":
tvm_tirx.testing.main()