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.
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.
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.
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.
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.
The correct SourceManager is available via
result.Context->getSourceManager();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With