[cfe-dev] API for auto type deduction in libclang

Jacob Carlborg doob at me.com
Sat Jan 25 06:18:50 PST 2014

On 2014-01-25 01:33, Kevin Funk wrote:
> Hey guys,
> I'm also part of the group trying to integrate Clang into KDevelop. We're
> using the C interface to Clang.
> I'm currently struggling to figure out how to get the automatically deduced
> type of a C++11 auto type. What we basically do atm is the following:
> Assume we have some code such as 'auto i = 42;'
> Following situation:
> - We have a CXCursor pointing to the declaration
> - Now clang_getCursorType(cursor) at this point
>    just returns CXType_Unexposed. This indicates some internal type.
> - clang_getTypeSpelling(cursor) then just gives us 'auto'.
>    Which is somewhat correct, but not what we really want.
> - We'd like to know the deduced type
> So the question is:
> Is there some way to get the deduced type for 'i' (obviously 'int' here)?
> Through debugging, I found out that C++11 auto types are internally handled as
> clang::AutoType. So, right now I'm missing API in the C interface, such as
> 'CXType clang_getAutoDeducedType(CXType)' that internally calls something like
> clang::AutoType::getDeducedType() (from AST/Type.h).
> I actually tried to patch Clang (excerpt attached) to get a proof-of-concept,
> but apparently AutoType::getDeducedType() always returns a null QualType for
> me. Hence the resulting type we get is garbage. Is AutoType::getDeducedType()
> even the correct method to use here? Is this approach completely wrong?
> Any hints are welcome

This seems to work without modifications to libclang:

CXType type = clang_getCursorType(cursor);
CXType deducedType = clang_getCanonicalType(type);
assert(deducedType.kind == CXType_Int);

/Jacob Carlborg

More information about the cfe-dev mailing list