Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clang libtooling: determine macro expansion location

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.

like image 810
LVK Avatar asked Oct 27 '25 20:10

LVK


1 Answers

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
}
like image 73
LVK Avatar answered Oct 31 '25 01:10

LVK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!