[clang] [clang-bindings] Add strict typing to clang Python bindings (#76664) (PR #78114)

Jannick Kremer via cfe-commits cfe-commits at lists.llvm.org
Sun Jan 14 13:48:05 PST 2024


================
@@ -232,13 +840,16 @@ class _CXString(Structure):
 
     _fields_ = [("spelling", c_char_p), ("free", c_int)]
 
-    def __del__(self):
+    def __del__(self) -> None:
         conf.lib.clang_disposeString(self)
 
     @staticmethod
-    def from_result(res, fn=None, args=None):
+    def from_result(res: _CXString, fn: Any = None, args: Any = None) -> str:
         assert isinstance(res, _CXString)
-        return conf.lib.clang_getCString(res)
+        pystr = conf.lib.clang_getCString(res)
+        if pystr is None:
+            return ""
+        return pystr
----------------
DeinAlptraum wrote:

`conf.lib.clang_getCString` may sometimes (though seemingly rarely) return `None` instead of a Python `str`. This is used in a lot of places throughout this file, and while parts of it seem to be aware of this (e.g. doc string saying that this may return `None`) other places are not (e.g. calling `len` on the return value, which will crash if it is `None`). Many parts of the interface also directly return the result of this function, and having to check for `None` in all of these places seems potentially impractical, so I went for returning empty strings instead of `None` instead.
But due to the inconsistent usage throughout this file, I'm not sure how far this corresponds more or less to the original intention.

https://github.com/llvm/llvm-project/pull/78114


More information about the cfe-commits mailing list