[cfe-dev] Obtaining the parent of a given libclang CXCursor

David Röthlisberger david at rothlis.net
Wed Aug 1 02:28:02 PDT 2012


On 30 Jul 2012, at 19:41, Nick Beer wrote:
> given a position inside a function, I'd like to be able to get the
> cursor from that position, and then look at that cursor's parents until
> I find the function declaration.

Hi Nick

Have a look at clang_getCursorLexicalParent and
clang_getCursorSemanticParent.

By the way, ipython is an excellent way to explore this API. Here's how
I found the above:

   $ export PYTHONPATH=/path/to/clang/bindings/python
   $ ipython
   :::  import clang.cindex
   :::  index = clang.cindex.Index.create()
   :::  tu = index.parse('example.cpp')
   :::  cs = tu.cursor.get_children()
   :::  c = cs.next(); print c.spelling # Ignore the first few implicit typedefs
   :::  c = cs.next(); print c.spelling
   :::  c = cs.next(); print c.spelling
   :::  c = cs.next(); print c.spelling
   :::  cs = c.get_children()
   :::  c = cs.next()
   :::  c.<TAB>
   c.canonical                c.get_definition           c.result_type
   c.data                     c.get_usr                  c.semantic_parent
   c.displayname              c.hash                     c.spelling
   c.enum_type                c.is_definition            c.translation_unit
   c.enum_value               c.is_static_method         c.type
   c.extent                   c.kind                     c.underlying_typedef_type
   c.from_location            c.lexical_parent           c.xdata
   c.from_result              c.location                 
   c.get_children             c.objc_type_encoding       

Then look in clang/bindings/python/clang/cindex.py to find the names
of the corresponding C functions.

Hope this helps!

--Dave.





More information about the cfe-dev mailing list