Hi all,
In our code, we find variables, and then lookup other declarations in the declaration context of this variable. But lookups from DeclContext returns null if given variable (from which we got declaration context) is local.
Let’s consider an example. Say we have a simple matcher to match all declarations of integer variables:
const auto Matcher = decl(
varDecl(hasType(asString("int")))).bind("a");
Then a callback to process on all integer variables:
const NamedDecl *Decl =
Result.Nodes.getNodeAs<clang::NamedDecl>("a");
if (Decl) {
const DeclContext *DC = Decl->getDeclContext();
// ...
Then I want to find a variable in Decl’s declaration context (DC), e.g.
DeclarationName FDName(&Decl->getASTContext().Idents.get("y"));
(for global variables)
or, e.g.
DeclarationName FDName(&Decl->getASTContext().Idents.get("b"));
(for local variables)
and then I try to lookup this variable by FDName and check result:
auto Lookup = DC->lookup(FDName);
if (Lookup.empty()) {
llvm::outs() << "Empty \n";
return;
}
ValueDecl *ValD = dyn_cast<ValueDecl>(Lookup.front());
if (ValD == nullptr)
return;
ValD->print(llvm::outs());
I try to run it with a simple C code:
int x, y, z;
int main() {
int a, b, c;
return 0;
}
In my experiments, all lookups of global variables (x, y, z) in the declaration context of a global variable return the desired declaration (as expected), meanwhile all lookups of local variables (a, b, c) in the declaration context of local variable return emptiness.
Note, that even if I lookup the declaration itself:
auto Lookup = DC->lookup(Decl->getDeclName());
Is it a bug, or am I wrong understanding of lookup behavior?
Clang 13.0.1.