Finding default value for function argument with clang-c API

Hello again.

When encountering a CXCursor_ParmDecl, how can I figure out if it has a
default value and what that value is? E.g.:

void foo(int i = 42);

Here I'd like to know that "i" is 42 by default. A string representation of
the default value would be sufficient to me, but even that doesn't seem to be
accessible. I could find some range for where the "= 42" is, but then I cannot
find any function in the C-API of clang to get a string representation of that
range.

Bye

I think you should just continue traversal the AST using clang_visitChildren. Also have a look at clang_Cursor_getArgument, you might need that as well.

When I'm already encountering a CXCursor_ParmDecl in my visitor,
clang_Cursor_getArgument would not give me anything else - would it? The
cursor it returns would point to the same ParmDecl I'm already trying to
handle.

Now, I could continue visitChildren recursively on the ParmDecl cursor to
figure out if it has any default argument. But I still cannot find any API to
get a stringified version of the default argument.

In the example above the "42" default value is represented as a
CXCursor_IntegerLiteral. But neither clang_getCursorSpelling nor
clang_getCursorDisplayName give me a string containing "42" - both return a
null CXString...

So, what other function can I use to get the stringified (raw) version of a
cursor?

Bye

Ok, I see. How about clang_getCursorExtent?

Followed by clang_tokenize of the returned range, then stringifying those
tokens via clang_getTokenSpelling? Is that what you have in mind? I'll try
that out and write back - thanks.

Bye

I was thinking about extracting the file, line and column information using these functions [1], then read that location from the file (or buffer). I don't know which is most effective. Although I do agree with you, libclang could have made this easier, or we're missing something.

[1] http://clang.llvm.org/doxygen/group__CINDEX__LOCATIONS.html