[clang] 9693bf4 - [libclang/python] Add some logical typing changes. (#138074)

via cfe-commits cfe-commits at lists.llvm.org
Thu May 1 03:30:10 PDT 2025


Author: Jannick Kremer
Date: 2025-05-01T12:30:06+02:00
New Revision: 9693bf457b8a3ae95735f86e23a94a7946ec540e

URL: https://github.com/llvm/llvm-project/commit/9693bf457b8a3ae95735f86e23a94a7946ec540e
DIFF: https://github.com/llvm/llvm-project/commit/9693bf457b8a3ae95735f86e23a94a7946ec540e.diff

LOG: [libclang/python] Add some logical typing changes. (#138074)

This adds a few logical changes that might require discussion to the
libclang/python typing project, as the next step towards #76664 .

Some documentation is also updated to reflect the recent changes in
returned types.

Added: 
    

Modified: 
    clang/bindings/python/clang/cindex.py

Removed: 
    


################################################################################
diff  --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py
index a5227df093e73..e4a731b1d57fa 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -71,8 +71,10 @@
 from typing import (
     Any,
     Callable,
+    cast as Tcast,
     Generic,
     Optional,
+    Sequence,
     Type as TType,
     TypeVar,
     TYPE_CHECKING,
@@ -314,6 +316,8 @@ def is_in_system_header(self):
         return conf.lib.clang_Location_isInSystemHeader(self)  # type: ignore [no-any-return]
 
     def __eq__(self, other):
+        if not isinstance(other, SourceLocation):
+            return False
         return conf.lib.clang_equalLocations(self, other)  # type: ignore [no-any-return]
 
     def __ne__(self, other):
@@ -372,6 +376,8 @@ def end(self):
         return conf.lib.clang_getRangeEnd(self)  # type: ignore [no-any-return]
 
     def __eq__(self, other):
+        if not isinstance(other, SourceRange):
+            return False
         return conf.lib.clang_equalRanges(self, other)  # type: ignore [no-any-return]
 
     def __ne__(self, other):
@@ -1556,6 +1562,8 @@ def from_location(tu, location):
         return cursor
 
     def __eq__(self, other):
+        if not isinstance(other, Cursor):
+            return False
         return conf.lib.clang_equalCursors(self, other)  # type: ignore [no-any-return]
 
     def __ne__(self, other):
@@ -1746,7 +1754,7 @@ def get_definition(self):
 
     def get_usr(self):
         """Return the Unified Symbol Resolution (USR) for the entity referenced
-        by the given cursor (or None).
+        by the given cursor.
 
         A Unified Symbol Resolution (USR) is a string that identifies a
         particular entity (function, class, variable, etc.) within a
@@ -2776,7 +2784,7 @@ def pretty_printed(self, policy):
         return _CXString.from_result(conf.lib.clang_getTypePrettyPrinted(self, policy))
 
     def __eq__(self, other):
-        if type(other) != type(self):
+        if not isinstance(other, Type):
             return False
 
         return conf.lib.clang_equalTypes(self, other)  # type: ignore [no-any-return]
@@ -2886,10 +2894,9 @@ def kind(self):
     def string(self):
         res = conf.lib.clang_getCompletionChunkCompletionString(self.cs, self.key)
 
-        if res:
-            return CompletionString(res)
-        else:
-            None
+        if not res:
+            return None
+        return CompletionString(res)
 
     def isKindOptional(self):
         return self.__kindNumber == 0
@@ -2955,6 +2962,13 @@ def __getitem__(self, key):
             raise IndexError
         return CompletionChunk(self.obj, key)
 
+    if TYPE_CHECKING:
+        # Defining __getitem__ and __len__ is enough to make an iterable
+        # but the typechecker doesn't understand that.
+        def __iter__(self):
+            for i in range(len(self)):
+                yield self[i]
+
     @property
     def priority(self):
         return conf.lib.clang_getCompletionPriority(self.obj)  # type: ignore [no-any-return]
@@ -2970,7 +2984,7 @@ def briefComment(self):
             return _CXString.from_result(
                 conf.lib.clang_getCompletionBriefComment(self.obj)
             )
-        return _CXString()
+        return ""
 
     def __repr__(self):
         return (
@@ -3155,8 +3169,8 @@ def from_source(
         a list via args. These can be used to specify include paths, warnings,
         etc. e.g. ["-Wall", "-I/path/to/include"].
 
-        In-memory file content can be provided via unsaved_files. This is an
-        iterable of 2-tuples. The first element is the filename (str or
+        In-memory file content can be provided via unsaved_files. This is a
+        list of 2-tuples. The first element is the filename (str or
         PathLike). The second element defines the content. Content can be
         provided as str source code or as file objects (anything with a read()
         method). If a file object is being used, content will be read until EOF
@@ -3328,6 +3342,7 @@ def get_extent(self, filename, locations):
         start_location, end_location = locations
 
         if hasattr(start_location, "__len__"):
+            start_location = Tcast(Sequence[int], start_location)
             start_location = SourceLocation.from_position(
                 self, f, start_location[0], start_location[1]
             )
@@ -3335,6 +3350,7 @@ def get_extent(self, filename, locations):
             start_location = SourceLocation.from_offset(self, f, start_location)
 
         if hasattr(end_location, "__len__"):
+            end_location = Tcast(Sequence[int], end_location)
             end_location = SourceLocation.from_position(
                 self, f, end_location[0], end_location[1]
             )
@@ -3464,6 +3480,8 @@ def get_tokens(self, locations=None, extent=None):
         2-tuple of SourceLocation or as a SourceRange. If both are defined,
         behavior is undefined.
         """
+        if locations is None and extent is None:
+            raise TypeError("get_tokens() requires at least one argument")
         if locations is not None:
             extent = SourceRange(start=locations[0], end=locations[1])
 
@@ -3510,11 +3528,11 @@ def __ne__(self, other) -> bool:
     @staticmethod
     def from_result(res, arg):
         assert isinstance(res, c_object_p)
-        res = File(res)
+        file = File(res)
 
         # Copy a reference to the TranslationUnit to prevent premature GC.
-        res._tu = arg._tu
-        return res
+        file._tu = arg._tu
+        return file
 
 
 class FileInclusion:
@@ -3593,7 +3611,7 @@ def filename(self):
     def arguments(self):
         """
         Get an iterable object providing each argument in the
-        command line for the compiler invocation as a _CXString.
+        command line for the compiler invocation as a string.
 
         Invariant : the first argument is the compiler executable
         """


        


More information about the cfe-commits mailing list