[cfe-dev] printing name of owning anonymous structure in RecursiveASTVisitor::VisitFieldDecl?

Yang Chen chenyang at cs.utah.edu
Tue Dec 11 15:04:39 PST 2012


Richard Smith wrote:
> On Tue, Dec 11, 2012 at 11:04 AM, Yang Chen <chenyang at cs.utah.edu> wrote:
>   
>> On 12/11/12 9:17 AM, Peeter Joot wrote:
>>     
>>> With an AST field visitor of the following form:
>>>
>>>    bool VisitFieldDecl( FieldDecl * f )
>>>    {
>>>       RecordDecl * r = f->getParent() ;
>>>
>>>       TypeSourceInfo * t = f->getTypeSourceInfo() ;
>>>
>>>       TypeLoc TL = t->getTypeLoc() ;
>>>
>>>       if ( const ArrayTypeLoc *Arr = dyn_cast<ArrayTypeLoc>(&TL) )
>>>       {
>>>          TL = Arr->getElementLoc() ;
>>>       }
>>>
>>>       const QualType & q = TL.getType() ;
>>>
>>>       cout
>>> << r->getName().str()
>>> << " : " << q.getAsString() << endl ;
>>>
>>>       return true ;
>>>    }
>>>
>>> I get a printout of
>>>
>>> <classname> : type-dependence.  Example:
>>>
>>> struct Test
>>> {
>>>    int a, b ;
>>> } ;
>>>
>>> gives:
>>>
>>> Test : int
>>> Test : int
>>>
>>> For anonymous structs like:
>>>
>>> struct TestA
>>> {
>>>    struct {
>>>       int a, b ;
>>>    } m ;
>>> } ;
>>>
>>> I do get a "name" for the dependent type m:
>>>
>>> TestA : struct <anonymous struct at asample2.cpp:8:4>
>>>
>>> However, when the AST visitor is called for the a, b fields in this
>>> anonymous struct, my r->getName().str() call returns an empty string.
>>>
>>> I'm guessing I could get the "name" above, if I could get the QualType
>>> from the 'RecordDecl * r' variable, but am unsure how to do so, because
>>> getTypeSourceInfo() doesn't appear to be available to a RecordDecl object.
>>> How can I get the RecordDecl's QualType?
>>>       
>> You can try this:
>> const Type *RT = r->getTypeForDecl();
>> QualType QT = RT->getCanonicalTypeInternal();
>>     
>
> That's not the right way. getTypeForDecl is a cache, and
> getCanonicalTypeInternal is internal. Use ASTContext::getRecordType.
>   

Thanks for correcting!

- Yang




More information about the cfe-dev mailing list