Given the following code:
class Foo {};
void f() {
Foo* uooooo = nullptr;
int* ip = nullptr;
auto lambda = [uooooo, ip](){
if (uooooo != nullptr) {
++*ip;
}
};
}
Runing the matcher in clang-query:
clang-query> m lambdaExpr(forEachDescendant(fieldDecl().bind("x")))
Match #1:
C:\llvm-project\clang-tools-extra\test\clang-tidy\.\temp.cpp(5,17): note: "root" binds here
5 | auto lambda = [uooooo, ip](){};
| ^~~~~~~~~~~~~~~~
C:\llvm-project\clang-tools-extra\test\clang-tidy\.\temp.cpp(5,18): note: "x" binds here
5 | auto lambda = [uooooo, ip](){};
| ^~~~~~
Match #2:
C:\llvm-project\clang-tools-extra\test\clang-tidy\.\temp.cpp(5,17): note: "root" binds here
5 | auto lambda = [uooooo, ip](){};
| ^~~~~~~~~~~~~~~~
C:\llvm-project\clang-tools-extra\test\clang-tidy\.\temp.cpp(5,26): note: "x" binds here
5 | auto lambda = [uooooo, ip](){};
| ^~
2 matches.
clang-query>
Implementing the same matcher in a clang-tidy check:
void LambdaCaptureRawPointerCheck::registerMatchers(
MatchFinder *Finder) {
auto Matcher = lambdaExpr(forEachDescendant(fieldDecl().bind("x")));
Finder->addMatcher(Matcher, this);
}
void LambdaCaptureRawPointerCheck::check(
const MatchFinder::MatchResult &Result) {
const auto *Matched = Result.Nodes.getNodeAs<FieldDecl>("x");
const auto &SM = Matched->getASTContext().getSourceManager();
auto SR = Matched->getSourceRange();
SR.dump(SM);
Matched->getBeginLoc().dump(SM);
Matched->getEndLoc().dump(SM);
}
The output of running the check on the sample code:
<C:\llvm-project\clang-tools-extra\test\clang-tidy\.\temp.cpp:5:18>
C:\llvm-project\clang-tools-extra\test\clang-tidy\.\temp.cpp:5:18
C:\llvm-project\clang-tools-extra\test\clang-tidy\.\temp.cpp:5:18
<C:\llvm-project\clang-tools-extra\test\clang-tidy\.\temp.cpp:5:26>
C:\llvm-project\clang-tools-extra\test\clang-tidy\.\temp.cpp:5:26
C:\llvm-project\clang-tools-extra\test\clang-tidy\.\temp.cpp:5:26
In clang-tidy the matched FieldDecl
has a zero-length source range, I guess this is because it is an implicit one. However, clang-query has a way to figure out the original piece of code an implicit lambda field matches. This is indicated by the ~s marking the indentifier uooooo
and ip
. I want to know how can I do the same in a clang-tidy check?
Thanks