Skip to content

[cindex] Add API to query the class methods of a type #123539

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Mar 1, 2025

Conversation

trelau
Copy link
Contributor

@trelau trelau commented Jan 20, 2025

Inspired by #120300, add a new API clang_visitCXXMethods to libclang (and the Python bindings) which allows iterating over the class methods of a type.

@trelau trelau requested a review from DeinAlptraum as a code owner January 20, 2025 00:28
Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot llvmbot added clang Clang issues not falling into any other category clang:as-a-library libclang and C++ API labels Jan 20, 2025
@llvmbot
Copy link
Member

llvmbot commented Jan 20, 2025

@llvm/pr-subscribers-clang

Author: Trevor Laughlin (trelau)

Changes

Inspired by #120300, add a new API clang_visitCXXMethods to libclang (and the Python bindings) which allows iterating over the class methods of a type.


Full diff: https://github.com/llvm/llvm-project/pull/123539.diff

6 Files Affected:

  • (modified) clang/bindings/python/clang/cindex.py (+16)
  • (modified) clang/bindings/python/tests/cindex/test_type.py (+18)
  • (modified) clang/docs/ReleaseNotes.rst (+4)
  • (modified) clang/include/clang-c/Index.h (+23)
  • (modified) clang/tools/libclang/CIndexCXX.cpp (+27)
  • (modified) clang/tools/libclang/libclang.map (+1)
diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py
index 806e1b40f3c9e1..9e65ea2942d163 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -2710,6 +2710,21 @@ def visitor(base, children):
         conf.lib.clang_visitCXXBaseClasses(self, fields_visit_callback(visitor), bases)
         return iter(bases)
 
+    def get_methods(self):
+        """Return an iterator for accessing the methods of this type."""
+
+        def visitor(method, children):
+            assert method != conf.lib.clang_getNullCursor()
+
+            # Create reference to TU so it isn't GC'd before Cursor.
+            method._tu = self._tu
+            methods.append(method)
+            return 1  # continue
+
+        methods: list[Cursor] = []
+        conf.lib.clang_visitCXXMethods(self, fields_visit_callback(visitor), methods)
+        return iter(methods)
+
     def get_exception_specification_kind(self):
         """
         Return the kind of the exception specification; a value from
@@ -4017,6 +4032,7 @@ def set_property(self, property, value):
     ),
     ("clang_visitChildren", [Cursor, cursor_visit_callback, py_object], c_uint),
     ("clang_visitCXXBaseClasses", [Type, fields_visit_callback, py_object], c_uint),
+    ("clang_visitCXXMethods", [Type, fields_visit_callback, py_object], c_uint),
     ("clang_Cursor_getNumArguments", [Cursor], c_int),
     ("clang_Cursor_getArgument", [Cursor, c_uint], Cursor),
     ("clang_Cursor_getNumTemplateArguments", [Cursor], c_int),
diff --git a/clang/bindings/python/tests/cindex/test_type.py b/clang/bindings/python/tests/cindex/test_type.py
index 9bac33f3041f40..bc893d509524e0 100644
--- a/clang/bindings/python/tests/cindex/test_type.py
+++ b/clang/bindings/python/tests/cindex/test_type.py
@@ -559,3 +559,21 @@ class Template : public A, public B, virtual C {
         self.assertEqual(bases[1].get_base_offsetof(cursor_type_decl), 96)
         self.assertTrue(bases[2].is_virtual_base())
         self.assertEqual(bases[2].get_base_offsetof(cursor_type_decl), 128)
+
+    def test_class_methods(self):
+        source = """
+        template <typename T>
+        class Template { void Foo(); };
+        typedef Template<int> instance;
+        instance bar;
+        """
+        tu = get_tu(source, lang="cpp", flags=["--target=x86_64-linux-gnu"])
+        cursor = get_cursor(tu, "instance")
+        cursor_type = cursor.underlying_typedef_type
+        self.assertEqual(cursor.kind, CursorKind.TYPEDEF_DECL)
+        methods = list(cursor_type.get_methods())
+        self.assertEqual(len(methods), 4)
+        self.assertEqual(methods[0].kind, CursorKind.CXX_METHOD)
+        self.assertEqual(methods[1].kind, CursorKind.CONSTRUCTOR)
+        self.assertEqual(methods[2].kind, CursorKind.CONSTRUCTOR)
+        self.assertEqual(methods[3].kind, CursorKind.CONSTRUCTOR)
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b02ac467cd3a22..dd9f722a6a08cb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1241,6 +1241,8 @@ libclang
   of a class.
 - Added ``clang_getOffsetOfBase``, which allows computing the offset of a base
   class in a class's layout.
+- Added ``clang_visitCXXMethods``, which allows visiting the methods
+  of a class.
 
 Static Analyzer
 ---------------
@@ -1394,6 +1396,8 @@ Python Binding Changes
   allows visiting the base classes of a class.
 - Added ``Cursor.get_base_offsetof``, a binding for ``clang_getOffsetOfBase``,
   which allows computing the offset of a base class in a class's layout.
+- Added ``Type.get_methods``, a binding for ``clang_visitCXXMethods``, which
+  allows visiting the methods of a class.
 
 OpenMP Support
 --------------
diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index aac5d1fa8aa2e0..5d961ca0cdd7fc 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -6680,6 +6680,29 @@ CINDEX_LINKAGE unsigned clang_visitCXXBaseClasses(CXType T,
                                                   CXFieldVisitor visitor,
                                                   CXClientData client_data);
 
+/**
+ * Visit the class methods of a type.
+ *
+ * This function visits all the methods of the given cursor,
+ * invoking the given \p visitor function with the cursors of each
+ * visited method. The traversal may be ended prematurely, if
+ * the visitor returns \c CXFieldVisit_Break.
+ *
+ * \param T the record type whose field may be visited.
+ *
+ * \param visitor the visitor function that will be invoked for each
+ * field of \p T.
+ *
+ * \param client_data pointer data supplied by the client, which will
+ * be passed to the visitor each time it is invoked.
+ *
+ * \returns a non-zero value if the traversal was terminated
+ * prematurely by the visitor returning \c CXFieldVisit_Break.
+ */
+CINDEX_LINKAGE unsigned clang_visitCXXMethods(CXType T,
+                                              CXFieldVisitor visitor,
+                                              CXClientData client_data);
+
 /**
  * Describes the kind of binary operators.
  */
diff --git a/clang/tools/libclang/CIndexCXX.cpp b/clang/tools/libclang/CIndexCXX.cpp
index 8b84fdc22ecff1..4d8ff696950b34 100644
--- a/clang/tools/libclang/CIndexCXX.cpp
+++ b/clang/tools/libclang/CIndexCXX.cpp
@@ -54,6 +54,33 @@ unsigned clang_visitCXXBaseClasses(CXType PT, CXFieldVisitor visitor,
   return true;
 }
 
+unsigned clang_visitCXXMethods(CXType PT, CXFieldVisitor visitor,
+                               CXClientData client_data) {
+  CXCursor PC = clang_getTypeDeclaration(PT);
+  if (clang_isInvalid(PC.kind))
+    return false;
+  const CXXRecordDecl *RD =
+      dyn_cast_if_present<CXXRecordDecl>(cxcursor::getCursorDecl(PC));
+  if (!RD || RD->isInvalidDecl())
+    return false;
+  RD = RD->getDefinition();
+  if (!RD || RD->isInvalidDecl())
+    return false;
+
+  for (auto Method : RD->methods()) {
+    // Callback to the client.
+    switch (
+        visitor(cxcursor::MakeCXCursor(Method, getCursorTU(PC)),
+                client_data)) {
+    case CXVisit_Break:
+      return true;
+    case CXVisit_Continue:
+      break;
+    }
+  }
+  return true;
+}
+
 enum CX_CXXAccessSpecifier clang_getCXXAccessSpecifier(CXCursor C) {
   AccessSpecifier spec = AS_none;
 
diff --git a/clang/tools/libclang/libclang.map b/clang/tools/libclang/libclang.map
index 8ca8a58b76d9e0..a86c5a95303f8e 100644
--- a/clang/tools/libclang/libclang.map
+++ b/clang/tools/libclang/libclang.map
@@ -440,6 +440,7 @@ LLVM_20 {
     clang_getTypePrettyPrinted;
     clang_isBeforeInTranslationUnit;
     clang_visitCXXBaseClasses;
+    clang_visitCXXMethods;
 };
 
 # Example of how to add a new symbol version entry.  If you do add a new symbol

Copy link

github-actions bot commented Jan 26, 2025

✅ With the latest revision this PR passed the C/C++ code formatter.

Copy link
Contributor

@DeinAlptraum DeinAlptraum left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Python part looks mostly good to me. I'm not too familiar with the non-Python side of things though, so would like someone else to take a look as well.
@Endilll do you want to take a look?

@trelau trelau force-pushed the class-methods-cindex branch from 8aea4bc to bb0542e Compare January 26, 2025 13:21
Copy link
Contributor

@Endilll Endilll left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python part of this looks fine to me.
We need to rename fields_visit_callback to something else, but that's not in the scope of this PR.

@trelau
Copy link
Contributor Author

trelau commented Feb 16, 2025

Not sure what happen, but there was a merge conflict with ReleaseNotes.rst where it looked like previous enhancements to liblang and Python bindings had been removed. To resolve the conflict I only left changes relevant to this PR.

edit: looks like release notes were "reset" after cutting rc (?)

@trelau
Copy link
Contributor Author

trelau commented Feb 16, 2025

Ping

@Endilll
Copy link
Contributor

Endilll commented Feb 16, 2025

edit: looks like release notes were "reset" after cutting rc (?)

Yes, this happens every time a release branch is created.
I checked your release notes, they seem fine to me.

@DeinAlptraum
Copy link
Contributor

@Endilll can you also review the non-Python part, or do you know someone who can?

Copy link
Contributor

@Endilll Endilll left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems fine to me, but I'd like @AaronBallman to take a look, too, because libclang doesn't have a dedicated maintainer and I'm not familiar enough with it to sign off new functions we add to it.

Co-authored-by: Vlad Serebrennikov <[email protected]>
Copy link
Collaborator

@AaronBallman AaronBallman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! LGTM aside from some very minor nits.

@DeinAlptraum
Copy link
Contributor

DeinAlptraum commented Mar 1, 2025

Is this ready to be merged? @trelau
Edit: no, this is still missing a formatting fix, see CI failure below

@trelau
Copy link
Contributor Author

trelau commented Mar 1, 2025

@DeinAlptraum ok now i think it's ready

@Endilll Endilll merged commit 304c053 into llvm:main Mar 1, 2025
14 checks passed
Copy link

github-actions bot commented Mar 1, 2025

@trelau Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@trelau trelau deleted the class-methods-cindex branch March 2, 2025 14:55
jph-13 pushed a commit to jph-13/llvm-project that referenced this pull request Mar 21, 2025
Inspired by llvm#120300, add a new
API `clang_visitCXXMethods` to libclang (and the Python bindings) which
allows iterating over the class methods of a type.

---------

Co-authored-by: Vlad Serebrennikov <[email protected]>
Co-authored-by: Aaron Ballman <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang:as-a-library libclang and C++ API clang Clang issues not falling into any other category
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants