[cfe-dev] inspecting generalized attributes in the AST with the libclang python bindings

Tamás Szelei hello.sztomi at gmail.com
Tue Nov 12 05:43:57 PST 2013


I'm writing a tool to parse generalized attributes that annotate a source
file.
I'm trying to parse the following code with the libclang python bindings:

test.h:

=============================
#ifndef test_h
#define test_h

class Foo
{
public:
    void foo [[interesting]] ();
    void bar ();
};

#endif
=============================

I'm using the following python code to dump the AST:

=============================
import sys
import clang.cindex

def setup():
    #clang.cindex.Config.set_library_path(r'c:\Program Files (x86)\LLVM
3.4.svn\bin')
    global ind
    ind = clang.cindex.Index.create()
    tu = ind.parse('test.h', ['-x', 'c++', '-std=c++11'])
    output_cursor_and_children(tu.cursor)

def indent(level):
    return '  '*level

def output_cursor(cursor, level):
    """ Low level cursor output
    """
    spelling = ''
    displayname = ''

    if cursor.spelling:
        spelling = cursor.spelling
    if cursor.displayname:
        displayname = cursor.displayname
    kind = cursor.kind;

    print indent(level) + spelling, '<' + str(kind) + '>'
    print indent(level+1) + '"'  + displayname + '"'

def output_cursor_and_children(cursor, level=0):
    """ Output this cursor and its children with minimal formatting.
    """
    output_cursor(cursor, level)
    if cursor.kind.is_reference():
        print indent(level) + 'reference to:'
        output_cursor(clang.cindex.Cursor_ref(cursor), level+1)

    # Recurse for children of this cursor
    has_children = False;
    for c in cursor.get_children():
        if not has_children:
            print indent(level) + '{'
            has_children = True
        output_cursor_and_children(c, level+1)

    if has_children:
        print indent(level) + '}'
=============================

I get the following output:

=============================
 <CursorKind.TRANSLATION_UNIT>
  "test.h"
{
  __builtin_va_list <CursorKind.TYPEDEF_DECL>
    "__builtin_va_list"
  type_info <CursorKind.CLASS_DECL>
    "type_info"
  Foo <CursorKind.CLASS_DECL>
    "Foo"
  {
     <CursorKind.CXX_ACCESS_SPEC_DECL>
      ""
    foo <CursorKind.CXX_METHOD>
      "foo()"
    bar <CursorKind.CXX_METHOD>
      "bar()"
  }
}
=============================

I would expect to see at least an UNEXPOSED_ATTR somewhere in the output.
What am I doing wrong here?

Tamás
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20131112/487d6c65/attachment.html>


More information about the cfe-dev mailing list