简体   繁体   中英

How can I find the SourceLocation of a character after a SourceLocation in a Clang AST?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM