Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print source location from a clang AST Node

I'm loosely following the tutorial at http://clang.llvm.org/docs/LibASTMatchersTutorial.html . I managed to create an AST Matcher that matches class definitions and my MatchFinder looks like this

class ClassDeclPrinter : public MatchFinder::MatchCallback
{
public:
  virtual void run(const MatchFinder::MatchResult &result) override
  {
    if (clang::NamedDecl const* nd = result.Nodes.getNodeAs<clang::NamedDecl>("id"))
    {
      nd->dump();
    }
  }
};

If I call dump() on the matched node, the output already contains its file and source location:

CXXRecordDecl 0x10dd250 </home/name/llvm-dev/build/../../cpp/classes.cpp:4:1, line:6:1> class B definition

However, when I call getLocation(), I only get a SourceLocation object, whose print() and dump() functions need a SourceManager instance to work. I have no idea how to obtain this SourceManager, or if there is another way to get a printable source location.

like image 680
Benno Avatar asked Jan 24 '14 03:01

Benno


People also ask

What is AST in clang?

1.2 The Clang Abstract Syntax Tree. An Abstract Syntax Tree (AST) is the structural in-memory repre- sentation of a program's source code. Clang's AST mixes syntactic- only (such as parenthesis) and semantic-only (such as implicit con- versions) nodes into the same tree structure.

What is AST dump?

The ast. dump() method returns a formatted string of the tree structure in a tree. The visit method available to the visitor object visits all the nodes in the tree structure.

What is clang query?

clang-query is a tool that allows you to quickly iterate and develop the difficult part of a matcher. Once the design of the matcher is completed, it can be transferred to a C++ clang-tidy plugin, similar to the ones in mozilla-central.

What is C++ AST?

An AST is essentially the same thing, a tree-like diagram of the meaningful content of a program. The part of the compiler responsible for producing the AST is called the front-end. That's where all the grammatical rules of C++ are interpreted and applied to the incoming source code.


1 Answers

The correct SourceManager is available via

result.Context->getSourceManager();
like image 150
Benno Avatar answered Sep 28 '22 07:09

Benno