[Mlir-commits] [mlir] [mlir][python] expose remaining Location inspection API (PR #192630)
Maksim Levental
llvmlistbot at llvm.org
Tue Apr 28 20:57:36 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();
+ }
+
----------------
makslevental wrote:
nit: can you add a `__repr__` like here https://github.com/llvm/llvm-project/blob/f217197c8d658390be97d962627a52f2cd97bd4a/mlir/include/mlir/Bindings/Python/IRCore.h#L1121-L1129
https://github.com/llvm/llvm-project/pull/192630
More information about the Mlir-commits
mailing list