[cfe-dev] Visiting anonymous unions

Sergejs Belajevs sergejs.belajevs at gmail.com
Fri Aug 17 06:23:17 PDT 2012


Hi,

I am writing a source-to-source transformation tool and I need a way
to check if function contains at least one anonymous union inside. My
current way is the following:

class AnonymousUnionChecker : public
clang::RecursiveASTVisitor<AnonymousUnionChecker>
{
     bool foundAnonUnion;

public:
    AnonymousUnionChecker() {}

    bool VisitRecordType(RecordType *T)
    {
        RecordDecl *D = T->getDecl();
        if (D->isUnion() && !D->getIdentifier())
        {
            foundAnonUnion = true;
            return false;
        }
        return true;
    }

    bool CanFindInside(clang::Stmt* stmt)  // for functions' bodies
    {
        foundAnonUnion = false;
        TraverseStmt(stmt);
        return foundAnonUnion;
    }
};

It works for code like:

void foo()
{
  union { int a; } a;
  a.a = 5;
}

but it doesn't work (VisitRecordType isn't get called) for code like:

void foo()
{
  union { int a; };
  a = 5;
}

My current idea for a workaround is to scan preprocessed function body
token by token and to check if there is a "union" token followed by
whitespaces and "{" token. Does anybody know a better approach,
possibly using clang's visitor functionality?


Thanks,
Sergejs



More information about the cfe-dev mailing list