[cfe-dev] How to write a matcher?

Stephen Kelly steveire at gmail.com
Tue Mar 11 06:04:13 PDT 2014


papin_g wrote:

> I have found the AST Matcher Reference to be useful while developing
> matchers: http://clang.llvm.org/docs/LibASTMatchersReference.html
> 
> 
> Instead of writing your own debug matcher you may want to try clang-query.

To avoid maintaining a build of clang, I'm using the debian packages. That 
doesn't seem to be part of it.

> To generate the AST dump you may want to use clang-check instead of
> clang++ with all the arguments. clang-check allows you to filter the AST
> and remove the need of specifying things like -fsyntax-only.

Thanks for the tip. 

However, as I wrote, getting the AST is not the primary problem. Properly 
making use of it is.

Anyway, lots of mostly-blind experimentation led me to add this to 
RemoveCStrCalls:

  Finder.addMatcher(
      operatorCallExpr(
        hasArgument(0, hasType(recordDecl(hasName("basic_ostream")))),
        hasOverloadedOperatorName("<<"),
        hasArgument(1,
          memberCallExpr(
            hasDescendant(
              memberExpr(
//               callee(expr().bind("match")),
//               
hasObjectExpression(hasType(recordDecl(hasName("basic_string")))),
                member(hasName("c_str"))
              ).bind("member")
            ),
            on(expr().bind("arg"))
          ).bind("call")
        )
      ),
      &Callback);

I still have no idea how to make it match 'c_str' on strings. However, it's 
good enough to port CMake, so I guess I'm done until I next encounter a 
need.

Thanks,

Steve.





More information about the cfe-dev mailing list