[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:38:04 PST 2024


================
@@ -642,51 +1259,29 @@ def register(value, name):
 
 
 ### Cursor Kinds ###
-class BaseEnumeration(object):
-    """
-    Common base class for named enumerations held in sync with Index.h values.
+TEnum = TypeVar("TEnum", bound="BaseEnumeration")
 
-    Subclasses must define their own _kinds and _name_map members, as:
-    _kinds = []
-    _name_map = None
-    These values hold the per-subclass instances and value-to-name mappings,
-    respectively.
 
+class BaseEnumeration(Enum):
+    """
+    Common base class for named enumerations held in sync with Index.h values.
     """
 
-    def __init__(self, value):
-        if value >= len(self.__class__._kinds):
-            self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1)
-        if self.__class__._kinds[value] is not None:
-            raise ValueError(
-                "{0} value {1} already loaded".format(str(self.__class__), value)
-            )
-        self.value = value
-        self.__class__._kinds[value] = self
-        self.__class__._name_map = None
+    value: int
 
-    def from_param(self):
+    def from_param(self) -> int:
         return self.value
 
-    @property
-    def name(self):
-        """Get the enumeration name of this cursor kind."""
-        if self._name_map is None:
-            self._name_map = {}
-            for key, value in self.__class__.__dict__.items():
-                if isinstance(value, self.__class__):
-                    self._name_map[value] = key
-        return self._name_map[self]
-
     @classmethod
-    def from_id(cls, id):
-        if id >= len(cls._kinds) or cls._kinds[id] is None:
-            raise ValueError("Unknown template argument kind %d" % id)
-        return cls._kinds[id]
+    def from_id(cls: type[TEnum], id: int) -> TEnum:
+        try:
+            return cls(id)
+        except ValueError:
+            raise ValueError("Unknown %s %d" % (cls.__class__, id))
----------------
DeinAlptraum wrote:

This also resolves behavior that I would consider a bug: for negative IDs, if you pass e.g. -1, this would return the last element of `_kinds` (due to Python list syntax) instea dof raising the appropriate value error.

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


More information about the cfe-commits mailing list