2

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?

abyss.7
  • 13,882
  • 11
  • 56
  • 100
  • The AST is an "Abstract Syntax Tree", which does mean that "to find things, you need to walk the tree". There is, as far as I know, no way to "find me all items of type X" - you could of course write something that gives you, for example, a vector of all occurrences of type X in the tree, but it would require recursively walking the tree, regardless of what it is you are looking for. – Mats Petersson Jun 14 '15 at 17:47
  • And of course, `namespace` may be `using namespace std;` rather than a `namespace something { ... code here ... }`, so you probably need to look at "what is before". as well. – Mats Petersson Jun 14 '15 at 17:48
  • @MatsPetersson Sorry, but I don't understand what your comment is about. I suppose you are not familiar with Clang C++ API, since the question is not about finding something or "walking the tree" - it's about the API parts unknown to me, that allow to link tokens with declarations. By the way, `using ...` is another type of declaration, which won't be caught by `VisitNamespaceDecl()`. – abyss.7 Jun 14 '15 at 17:56
  • Sorry, misunderstood what you were asking for, because I thought when you said "jump", I thought you wanted to "skip to AST entry X" in some way. You can get the the end location for a statement with `getLocEnd()` - but I'm not sure that's what you want... – Mats Petersson Jun 14 '15 at 18:30

0 Answers0