Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions mlir/include/mlir/Bindings/Python/NanobindAdaptors.h
Original file line number Diff line number Diff line change
Expand Up @@ -181,14 +181,22 @@ struct type_caster<MlirContext> {
bool from_python(handle src, uint8_t flags, cleanup_list *cleanup) noexcept {
if (src.is_none()) {
// Gets the current thread-bound context.
// TODO: This raises an error of "No current context" currently.
// Update the implementation to pretty-print the helpful error that the
// core implementations print in this case.
src = mlir::python::irModule().attr("Context").attr("current");
}
std::optional<nanobind::object> capsule = mlirApiObjectToCapsule(src);
value = mlirPythonCapsuleToContext(capsule->ptr());
return !mlirContextIsNull(value);
// If there is no context, including thread-bound, emit a warning (since
// this function is not allowed to throw) and fail to cast.
if (src.is_none()) {
PyErr_Warn(
PyExc_RuntimeWarning,
"Passing None as MLIR Context is only allowed inside "
"the " MAKE_MLIR_PYTHON_QUALNAME("ir.Context") " context manager.");
return false;
}
if (std::optional<nanobind::object> capsule = mlirApiObjectToCapsule(src)) {
value = mlirPythonCapsuleToContext(capsule->ptr());
return !mlirContextIsNull(value);
}
return false;
}
};

Expand Down
13 changes: 13 additions & 0 deletions mlir/test/python/dialects/pdl_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,16 @@ def test_value_type():
print(parsedType)
# CHECK: !pdl.value
print(constructedType)


# CHECK-LABEL: TEST: test_type_without_context
@run
def test_type_without_context():
# Constructing a type without the surrounding ir.Context context manager
# should raise an exception but not crash.
try:
constructedType = pdl.ValueType.get()
except TypeError:
pass
else:
assert False, "Expected TypeError to be raised."