Reputation: 340
I'm trying to use the Clang Lexer library to find the location of a token (specifically the left brace of a namespace declaration). My idea (since the NamespaceDecl doesn't have a method for it) was to find the location of the first left brace after the start of the namespace declaration. However, looking at the Lexer API, I can't seem to find a short and simple way to do this while visiting an AST. Any suggestions/alternatives without having to do something drastic like reparse the code?
Upvotes: 4
Views: 1173
Reputation: 1111
Here is a way to find the brace. In my test, it works for both named and anonymous namespaces.
// Assuming ns_decl is pointer to the NamespaceDecl
// sm is reference to the SourceManager
... in addition to the usual headers:
#include "clang/Basic/TokenKinds.h" // for clang::tok
#include "clang/Lex/Lexer.h" // for Lexer
...
clang::LangOptions lopt;
bool skipNewLines = false;
SourceLocation locToUse = ns_decl->isAnonymousNamespace() ?
ns_decl->getLocStart() : ns_decl->getLocation();
SourceLocation next_loc(
clang::Lexer::findLocationAfterToken(
locToUse,clang::tok::l_brace, sm,lopt,skipNewLines));
In a declaration like
namespace NOPQ {
void f(int){}
}
namespace
ABCD
{
void g(float){}
}
namespace {
void h(int){}
}
next_loc will correspond to line 1, col 18 for NOPQ; line 7, col 7 for ABCD; and line 11, col 12 for the anonymous ns.
Upvotes: 3