I have a header header.h
with a macro definition which expands into a class definition and a source file test.cpp
which includes header.h
and uses this macro. Then I use RecursiveASTVisitor
to visit all CXXRecordDecl
's.
When I visit the CXXRecordDecl which is expansion of the macro (in test.cpp) and query for its SourceLocation
and dump()
it, the location points to header.h
- the location of macro definition.
What I need to get for this CXXRecordDecl is the SourceLocation
of macro expansion - in my case it should be test.cpp
.
Thanks in advance.
Found solution.
The required method is SourceManager's getFileLoc(SourceLocation loc), which "returns the expansion location" if loc
"is a macro location".
My code to get source location for both normal class definitions and definitions as macro expansions:
bool VisitCXXRecordDecl(CXXRecordDecl* record)
{
SourceLocation loc = record->getLocStart();
SourceLocation locExp = m_sourceManager.getFileLoc(loc);
// if record is a macro expansion in test.cpp, locExp points to test.cpp
// if record is not a macro expansion, locExp correctly points to matching source file
}