[cfe-dev] [ast_matcher] Match variable declaration by type name

James Dennett via cfe-dev cfe-dev at lists.llvm.org
Tue Jun 11 09:04:52 PDT 2019


On Mon, Jun 10, 2019 at 8:31 AM Michael Schellenberger Costa via cfe-dev <
cfe-dev at lists.llvm.org> wrote:

> Hi,
>
> I am trying to learn more about libTooling and the ast_matcher. In my
> first toy example I wanted to try to match arbitrary variable
> declaration against a given type name, e.g.
>
> foo var1;
>
> baz var2;
>
>
> I have tried the following matcher
>
>
> varDecl(hasType(cxxRecordDecl(hasAnyName("foo", "bar")))).bind("var")
>
>
> However, it seems that this is not able to match the declaration. My
> unit test harness looks like this
>
> myContext runOnCode(const char* const Code = "")
> {
>      myContext Context;
>      auto Factory = llvm::make_unique<myActionFactory>(&Context);
>      tooling::runToolOnCode(Factory->create(), Code);
>      return Context;
> }
>
> where myContext is a simple holder that stores the matched nodes in a
> set. The test looks like this
>
> TEST(variableMatcher, variable)
> {
>      myContext context = runOnCode("foo var1;");
>      auto res = context.getVariables();
>      EXPECT_EQ(res.size(), size_t(1));
> }
>
>
> Is the problem that the classes "foo" and "bar" are never declared?


Yes; parsing C++ requires knowing which names are types (and which are
templates, etc.).


> If
> so how could I instantiate the tool with the necessary declarations.


The path of least resistance is to ensure that the translation unit you
parse is self-contained, i.e., includes the necessary declarations.  A
useful sanity check is to compile it with clang from the command line.

-- James
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20190611/05cec5bc/attachment.html>


More information about the cfe-dev mailing list