[Mlir-commits] [mlir] [mlir][python] expose remaining Location inspection API (PR #192630)
Soowon Jeong
llvmlistbot at llvm.org
Tue Apr 28 23:58:17 PDT 2026
================
@@ -1164,6 +1168,122 @@ class MLIR_PYTHON_API_EXPORTED PyStringAttribute
static void bindDerived(ClassTy &c);
};
+/// CRTP base class for Python classes that subclass Location and should be
+/// castable from it (i.e. via something like FileLineColLoc(loc)).
+template <typename DerivedTy, typename BaseTy = PyLocation>
+class MLIR_PYTHON_API_EXPORTED PyConcreteLocation : public BaseTy {
+public:
+ // Derived classes must define statics for:
+ // IsAFunctionTy isaFunction
+ // const char *pyClassName
+ using ClassTy = nanobind::class_<DerivedTy, BaseTy>;
+ using IsAFunctionTy = bool (*)(MlirLocation);
+ using GetTypeIDFunctionTy = MlirTypeID (*)();
+ static constexpr GetTypeIDFunctionTy getTypeIdFunction = nullptr;
+ using Base = PyConcreteLocation;
+
+ PyConcreteLocation() = default;
+ PyConcreteLocation(PyMlirContextRef contextRef, MlirLocation loc)
+ : BaseTy(std::move(contextRef), loc) {}
+ PyConcreteLocation(PyLocation &orig)
+ : PyConcreteLocation(orig.getContext(), castFrom(orig)) {}
+
+ static MlirLocation castFrom(PyLocation &orig) {
+ if (!DerivedTy::isaFunction(orig.get())) {
+ auto origRepr =
+ nanobind::cast<std::string>(nanobind::repr(nanobind::cast(orig)));
+ throw nanobind::value_error((std::string("Cannot cast location to ") +
+ DerivedTy::pyClassName + " (from " +
+ origRepr + ")")
+ .c_str());
+ }
+ return orig.get();
+ }
+
----------------
swjng wrote:
Done in a1f6541. Mirrored the `PyConcreteAttribute` `__repr__` pattern; also added `__str__` on the base `Location` (assembly form) so `str()` keeps producing the assembly form regardless of subclass, same split as `Attribute`/`PyConcreteAttribute`.
https://github.com/llvm/llvm-project/pull/192630
More information about the Mlir-commits
mailing list