How to get tokens for a declaration using Clang C++ API?

1k views Asked by At

I have my own recursive AST visitor class with the clang::ASTContext object inside:

class Visitor : public clang::RecursiveASTVisitor<Visitor> {
 public:
  Visitor(const clang::ASTContext& context) : context_(context) {}

 private:
  const clang::ASTContext& context_;
};

Then I want to visit, for example, all namespace declarations and colorify their names:

bool VisitNamespaceDecl(clang::NamespaceDecl* decl) {
  const auto& sm = context_.getSourceManager();
  auto loc = decl->getLocStart();

  if (!sm.isInMainFile(loc)) {
    return true;
  }

  if (!sm.isMacroBodyExpansion(loc)) {
    auto line = sm.getSpellingLineNumber(loc);
    auto column = sm.getSpellingColumnNumber(loc);
    // Colorify the "namespace" keyword itself.

    // TODO: how to get location of the name token after "namespace" keyword?
  }

  return true;
}

It's just example. Even if there is a way to get the location of the namespace's name without tokens, I'm interested in a more global approach.


Is there a way to "jump" to the tokens within the declaration source range and traverse them?

0

There are 0 answers