[cfe-dev] extracting name of type with cindex

Jacob Carlborg doob at me.com
Wed May 9 00:38:08 PDT 2012


On 2012-05-08 17:52, Mark Moreno wrote:
> Hello,
>
> let's say I have:
>
> class Test {
>    int foo;
>    vector<string>  bar;
>    char* ptr;
> };
>
> with cindex, I want to extract the variable name and data type from
> this class, eg, I want to have 'int', 'foo', 'vector<string>', 'bar',
> 'char*', 'ptr'.
>
> Getting into the class with a cursor seems easy, as getting the
> variable, but how do I get the original representation of the type?
>
> If I use something like:
>
> print>>output, cursor.type.kind.spelling,
> cursor.type.get_declaration().spelling, cursor.spelling, cursor.kind,
> cursor.kind.name
>
> I get back:
>
> Int None foo CursorKind.FIELD_DECL FIELD_DECL
> Unexposed vector bar CursorKind.FIELD_DECL FIELD_DECL
> Pointer None ptr CursorKind.FIELD_DECL FIELD_DECL
>
> Any easy way to get the original representation of the type? or at
> least reconstruct what it should be like?
> Is this a shortcoming of the python API? would I have better luck
> using the C++ one? anyone who can point me in the right direction?
>
> Instead of Int, I'd like int, instead of Unexposed vector, I'd like
> vector<string>, ...
>
> (trying to build a tool for serialization, that needs the original
> data type for diagnostic purposes and to generate code)
>
> Thank you in advance,
> Mark

I don't know about the Python bindings but using the C bindings I do:

1. Iterate all declarations
2. For every declaration of the type (cursor.kind) CXCursor_StructDecl
3. Iterate all the children of the declaration
4. For every declaration of the type (cursor.kind) CXCursor_FieldDecl
5. Get the type, clang_getCursorType
7. Get the spelling, clang_getCursorSpelling

Now the tricky thing is the type, it's really depends on what you want 
out of the information. What you want here is the spelling of the type:

cursor = clang_getTypeDeclaration(type)
clang_getCursorSpelling(cursor)

For structs, enums and so on I use the spelling. But the thing is that 
the built-in types doesn't have any spelling. I don't know if this is 
the correct way to do it but I have a big switch-statement for the 
built-in types, something like this (in some kind of pseudo code) :

string getType (type)
{
     switch (type.kind)
     {
         case CXType_Void: return "void";
         case CXType_Char_S: return "char";
         case CXType_Short: return "short";
         case CXType_Int: return "int";
         case CXType_Float: return "float";
         case CXType_Double: return "double";

         case CXType_Record:
         case CXType_Enum:
         case CXType_Typedef:
             return type.spelling;
     }
}

-- 
/Jacob Carlborg




More information about the cfe-dev mailing list