[MLIR] [Python] Pybind adaptors: coerce None to default MlirLocation
authorJohn Demme <john.demme@microsoft.com>
Wed, 6 Apr 2022 00:10:20 +0000 (17:10 -0700)
committerJohn Demme <john.demme@microsoft.com>
Wed, 6 Apr 2022 00:10:20 +0000 (17:10 -0700)
Add default source location coercion to enable location elision in
Python code.

mlir/include/mlir/Bindings/Python/PybindAdaptors.h

index 661ed48..582855a 100644 (file)
@@ -125,11 +125,16 @@ struct type_caster<MlirContext> {
 };
 
 /// Casts object <-> MlirLocation.
-// TODO: Coerce None to default MlirLocation.
 template <>
 struct type_caster<MlirLocation> {
   PYBIND11_TYPE_CASTER(MlirLocation, _("MlirLocation"));
   bool load(handle src, bool) {
+    if (src.is_none()) {
+      // Gets the current thread-bound context.
+      src = py::module::import(MAKE_MLIR_PYTHON_QUALNAME("ir"))
+                .attr("Location")
+                .attr("current");
+    }
     py::object capsule = mlirApiObjectToCapsule(src);
     value = mlirPythonCapsuleToLocation(capsule.ptr());
     return !mlirLocationIsNull(value);