[cfe-dev] HOWTO: visit initializers via libclang

Stefan Seefeld seefeld at sympatico.ca
Tue Jan 25 09:45:06 PST 2011

On 2011-01-25 11:05, Stefan Seefeld wrote:
> I'm trying to translate initializers (such as from function parameter or
> template parameter default values), but right now those are hidden
> behind an "UnexposedExpr". Is there some way to change that so I can
> access the initializer expression ?
> Right now I'm mostly just interested into a stringified version, though
> eventually I would also like to extract the value, for cases where this
> is a compile-time expression.

Answering my own question (partially):

I'm starting from that UnexposedExpr cursor, compute its extent, then 
tokenize that range, and concatenate those token spellings, to 
regenerate the initializer expression. That seems to work well, with a 
single issue:

The range includes the first position, but excludes the last. However, 
passing that range to clang_tokenize will actually make the last token 
be one outside the range.

For example:

enum E { a = 1, b = 2};

yields ['1', ','] as token list for the first initializer expression, 
and ['2', '}'] for the second.

Here is my code:

   CXSourceRange r = clang_getCursorExtent(c);
   clang_tokenize(tu, r, &tokens, &num_tokens);
   for (unsigned i = 0; i != num_tokens; ++i)

I guess I could work around this by looping till "num_tokens - 1", 
instead of "num_tokens".

Is this intended behavior, or a bug ?



       ...ich hab' noch einen Koffer in Berlin...

More information about the cfe-dev mailing list