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

Kevin Funk krf at gmx.de
Sat Jan 25 13:03:47 PST 2014


Am Samstag, 25. Januar 2014, 15:18:50 schrieb Jacob Carlborg:
> 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);

That doesn't work for me.

For testing we have a small wrapper binary that basically creates a 
CXTranslationUnit and then traverses through the AST via 
clang_visitChildren().

During the call to 'visit' it does the following (amongst other things):
- auto location = clang_getCursorLocation(cursor)
- auto type = clang_getCursorType(cursor)
- auto typeString = clang_getTypeSpelling(type)
- now: auto canonicalTypeString = 
    clang_getTypeSpelling(clang_getCanonicalType(type))

It outputs all the values of those variabes to stdout, and when I pass "auto i 
= 5;" to it I get:

"""
decl: "auto (canonical type: auto) i " of kind VarDecl (9) in stdin.cpp at 1:6
  "int (canonical type: int) " of kind IntegerLiteral (106) in stdin.cpp at 1:10
"""

So the 'canonical type' of VarDecl still resolves to 'auto', instead of 'int'.
Sorry, if we're doing something completely wrong, but I don't seem to get this 
working as you suggest.

Greets

-- 
Kevin Funk



More information about the cfe-dev mailing list