2

In Clang AST, is it possible to find type by name?

For example I have qualified name : nspace::my_type<int, 10u>. How can I check if type is present in current translation unit?

Unapiedra
  • 15,037
  • 12
  • 64
  • 93
random
  • 3,868
  • 3
  • 22
  • 39

1 Answers1

1

NOTE: my knowledge is extremely limited from just once writing a clang tidy check to do some update I needed. Might be wrong.

There are two possible things that you might need in clang AST depending on the task at hand: Type and TypeLocation. I needed the type location, so this is what I'll mention first.

Find the type spelling.

In this case what you actually want is the TypeLocation ast nodes. They represent a spelling of a type. Unfortunately are not printed by clang-query.

The way to search for them is by using a type_loc matcher.

This is from something I needed: find all specialisations of a wide template. This would find me all the spellings of wide<T>

l isWide            hasDeclaration(classTemplateDecl(namedDecl(hasName("wide"))))
l isWideSpec        templateSpecializationType(isWide)
l wideLoc           typeLoc(loc(isWideSpec))

wideLoc - is what I was using to change the spelling of the type.

Different type_loc have parents that are also type_loc.

So for example I can find all entries of T unless they are inside wide<T>

typeLoc(loc(asString("T")), unless(hasAncestor(wideLoc)))

Find all of the actual usages of the type, regardless of how it is spelled.

Now for this type of problem you'd need to match on a type.

Have never done this myself, but we can see abseil doing this for example here: https://github.com/llvm/llvm-project/blob/b426b45d101740a21610205ec80610c6d0969966/clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.cpp#L36

PS. Just in case - all clang ast matchers: https://clang.llvm.org/docs/LibASTMatchersReference.html

Denis Yaroshevskiy
  • 1,218
  • 11
  • 24