[cfe-dev] Problems finding the modifiers to a function

Gregory Szorc gregory.szorc at gmail.com
Tue May 15 10:34:37 PDT 2012

On Tue, May 15, 2012 at 12:13 AM, CodieCodemonkey <ken.j.hill at gmail.com> wrote:
> Fred Stakem wrote
>> I am fairly new to clang and was using the python bindings and was having
>> a problem figuring out how to find more information on a function.
>> Specifically I found the functions in a C file but I can't find a way to
>> find if a function is static or not. How do you do this? I don't have to
>> use to python bindings but they seemed the easiest way to get things up
>> and running.
>> Fred
> I don't have a solution for you, but I'll share my hack.    You problably
> have done something similar by now.
> def emit_pre_function_modifiers(cursor, source_text):
>    """
>    Find function modifiers that are specified at the beginning of a
>    function declaration.
>    cursor -- is the clang AST Cursor object representing a function-like
> unit
>        (e.g. CursorKind.CXX_METHOD)
>    source_text -- String containing the source code being examined.
>    Unfortunately the clang AST doesn't track function modifiers

We should add this functionality to libclang [and the Python bindings
by extension].

> This technique can be fooled with
>    preprocessor definitions and compiler-specific directives!
>    """
>    so = cursor.extent.start.offset
>    eo = cursor.extent.end.offset
>    defn = source_text[so:eo].split(' ')
>    for word in defn:
>        if '(' in word: break
>        if word in ['static', 'virtual', 'inline']: sys.stdout.write(word+'
> ')

The Python bindings should have support for the token stream in the
near future. Using that, at least you could correlate the cursor's
source range with tokens and look for "raw identifier" tokens
occurring before the function name's "raw identifier" token. That is
still hacky and not much different from the above code. We really want
API support for extracting function modifiers.

More information about the cfe-dev mailing list