Booo
Booo

Reputation: 503

What are the differences between Clang AST Matcher and AST Visitor?

Two powerful ways to open the box of Clang. What should I consider when deciding to use one over the other?

Clang website offers some old tutorial on how to use RecursiveASTVisitor to find a Decl AST node, as well as some new tutorial on how to use ASTMatcherto find some for stmt. In this context, there is much overlap on what they can achieve.

For simple tasks as mentioned above, I find ASTMatcher more convenient, as the used predicate is short and easy to read. However, for more complex tasks such as source-to-source transformations, where analysis is needed for the whole translation unit. Implementing the Visitor functions seems a better approach. Because the predicates in my ASTMatcher tend to get lengthy and difficult to understand. Maybe there is an efficient way to use ASTMatcher with lang and complex predicates. I appreciate any advice on this. Since ASTMatcher was introduced later, is it intend to replace the old AST Visitor method?

Upvotes: 3

Views: 1244

Answers (1)

OneRaynyDay
OneRaynyDay

Reputation: 3968

Good question. Sometimes matchers are infeasible for a type of pattern that involves variable number of AST nodes and complexity in between two patterns that you're looking for. Here's an example:

For example, matching any class with the name Foo, and if all of its methods have a variable y in it. The AST would look something like:

|-CXXRecordDecl 0x563295d82010 <sandbox/class.cpp:1:1, line:6:1> line:1:7 class Foo definition
...
| |-CXXRecordDecl 0x563295d82128 <col:1, col:7> col:7 implicit class Foo
| |-FieldDecl 0x563295d821d0 <line:2:5, col:9> col:9 x 'int'
| `-CXXMethodDecl 0x563295d82298 <line:3:5, line:5:5> line:3:10 bar 'void ()'
|   `-CompoundStmt 0x563295d823e8 <col:16, line:5:5>
|     `-DeclStmt 0x563295d823d0 <line:4:9, col:14>
|       `-VarDecl 0x563295d82368 <col:9, col:13> col:13 y 'int'

For a single function. As far as I know, there is no easy way to match ALL methoddecls and match a wildcard number of stmts until you get to a variable y in the definition. It would be in your best interest to use an AST visitor pattern for this.

Upvotes: 2

Related Questions