Access to the field of a structure

Hi All,

in my .c file I have a struct like this:

typedef struct var {
int x;
int y;
} point;

Overriding the VisitTypedefDecl method I can access to the structure using a TypedefNameDecl variable. How can I access to the fields of the struct?

Thanks,
Alberto

You will first want to get the RecordDecl through TypedefNameDecl::getUnderlyingType and then use the decls_begin/end iterators for iterating (or the decls() range in a range-for) (note these methods are inherited from DeclContext).

– Sean Silva

Sean
Thanks I’ll do as you have suggested.

Alberto

Hi All,

i’m trying again to access to the fields of the struct but also after the first help i can’t do it. I tried in this way but it isn’t correct and i can’t understand how to fix it:

virtual bool VisitTypedefDecl (TypedefDecl *d) {
cout << “typedef\n”;
QualType qt = d->getUnderlyingType();
qt.dump();

for (clang::DeclContext::decl_iterator it = (qt).decls_begin(), declEnd = (qt).decls_end();it != declEnd; ++it) {
cout << “.” << endl;
}

return true;
}

Of course .decls_begins()/end() aren’t available but i think cast to DeclContext() isn’t the right solution.

Any suggestion?

Thanks,

Alberto

Hi all,

i solved in this way. Probably it isn’t the best one but i hope this help:

bool VisitDecl(Decl *D) {
clang::RecordDecl::field_iterator jt;
if (RecordDecl *var = dyn_cast(D)) {
for(jt = var->field_begin(); jt != var->field_end();++jt) {
std::cout << jt->getType().getAsString() << " " << jt->getNameAsString() << std::endl;
}
}
}

Any suggestion?

Thanks,

Alberto

Other than just overriding VisitRecordDecl (instead of VisitDecl) what you’ve done seems to make sense. Sorry about the confusion; I thought for some reason you already had a reference to the TypedefDecl and didn’t want to do another AST visitation to find the struct.

– Sean Silva