0

I am parsing a C++ header file using Clang module in Python. I am trying to list all class names and its member functions.

Here is what I've have tried

I found this under https://stackoverflow.com/a/40328378/6223628

import clang
import clang.cindex as cl
from clang.cindex import CursorKind

def fully_qualified(c):
    if c is None:
        return ''
    elif c.kind == CursorKind.TRANSLATION_UNIT:
        return ''
    else:
        res = fully_qualified(c.semantic_parent)
        if res != '':
            return res + '::' + c.spelling
    return c.spelling

cl.Config.set_library_file('C:/Program Files/LLVM/bin/libclang.dll')
idx = clang.cindex.Index.create()
tu = idx.parse('C:/Repository/myproject/myHeader.h', args='-xc++ --std=c++11'.split())
for c in tu.cursor.walk_preorder():
    if c.kind == CursorKind.CALL_EXPR:
        print (fully_qualified(c.referenced))

I am able to retrieve only some of the class names and the rest or the results are from std namespace.

Any other options available?

L. Scott Johnson
  • 4,213
  • 2
  • 17
  • 28
Seetharama
  • 129
  • 14
  • What does you mean "some"? Can you post a source file, for which you're missing data? – Radosław Cybulski Jul 17 '19 at 12:16
  • 1
    The reference question/answer seems to be about finding function calls not classes, thus firstly you need to adjust `CursorKind` to something different. To avoid stuff from other libraries/headers you may check that `c.location.file` is equal to your file for example. – Predelnik Jul 17 '19 at 13:02

1 Answers1

0

From the hint from @Predelnik from the comments, I adjusted the CursorKind to Class_decl and CXX_methods and got the required.

import clang
import clang.cindex as cl
from clang.cindex import CursorKind

def fully_qualified(c):
    if c is None:
        return ''
    elif c.kind == CursorKind.TRANSLATION_UNIT:
        return ''
    else:
        res = fully_qualified(c.semantic_parent)
        if res != '': 
            if res.startswith("myWord"):
                return res+"::"+c.spelling
        return c.spelling 

cl.Config.set_library_file('C:/Program Files/LLVM/bin/libclang.dll')
idx = clang.cindex.Index.create()
tu = idx.parse('C:/myproject/myHeader.h', args='-xc++ --std=c++11'.split())
for c in tu.cursor.walk_preorder():
    if c.kind == CursorKind.CLASS_DECL:
        print(fully_qualified(c.referenced))
    elif c.kind == CursorKind.CXX_METHOD:
        print(fully_qualified(c.referenced))
Seetharama
  • 129
  • 14