[cfe-dev] How to write a matcher?

Richard legalize at xmission.com
Thu Mar 13 17:06:39 PDT 2014


In article <E1WOEAb-00071u-8w at shell.xmission.com>,
    Richard <legalize at xmission.com> writes:

> I think the reason you didn't get a match here is that the structure is:
> 
> CXXOperatorCallExpr
> |-ImplicitCastExpr
> |-DeclRefExpr
> |-CXXOperatorCallExpr
> | |-CXXMemberCallExpr
> 
> <http://clang.llvm.org/docs/LibASTMatchersReference.html> says that
> operatorCallExpr expects a Matcher<CXXOperatorCallExpr> argument, but
> you supplied memberCallExpr() which returns type Matcher<Stmt>.
> 
> operatorCallExpr() could take hasOverloadedOperatorName() in order to
> narrow it to the specific operator.
> 
> I think then you need to narrow it further based on the arguments to
> the operator.

OK, finally figured out how to get clang-query built (you need libedit
or it won't build) and tried it out on your example file:

clang-query> match operatorCallExpr(hasOverloadedOperatorName("<<"),
hasArgument(1, hasType(asString("const char *"))))

Match #1:

/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../include/c++/4.7/ostream:542:15:
note: "root" binds here
    { return (__out << reinterpret_cast<const char*>(__s)); }
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Match #2:

/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../include/c++/4.7/ostream:547:15:
note: "root" binds here
    { return (__out << reinterpret_cast<const char*>(__s)); }
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Match #3:

/tmp/foo.cpp:7:3: note: "root" binds here
  std::cout << s.c_str() << std::endl;
  ^~~~~~~~~~~~~~~~~~~~~~
3 matches.

If you add in the suggestion about narrowing based on source file
location, then we're getting exactly the one you want from your source
file.

However, more narrowing is needed because you may have other functions
besides std::string::c_str() that return a const char * expression.
-- 
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
     The Computer Graphics Museum <http://ComputerGraphicsMuseum.org>
         The Terminals Wiki <http://terminals.classiccmp.org>
  Legalize Adulthood! (my blog) <http://LegalizeAdulthood.wordpress.com>



More information about the cfe-dev mailing list