Skip to content

[Clang][ASTMatcher] Improve matching isDerivedFrom base in case of multi aliases exists #126793

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions clang/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,8 @@ Fixed Point Support in Clang
AST Matchers
------------

- Ensure ``isDerivedFrom`` matches the correct base in case more than one alias exists.

clang-format
------------

Expand Down
21 changes: 21 additions & 0 deletions clang/lib/ASTMatchers/ASTMatchFinder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1287,6 +1287,27 @@ class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
auto Aliases = TypeAliases.find(CanonicalType);
if (Aliases == TypeAliases.end())
return false;

if (const auto *ElaboratedTypeNode =
llvm::dyn_cast<ElaboratedType>(TypeNode)) {
if (ElaboratedTypeNode->isSugared() && Aliases->second.size() > 1) {
const auto &DesugaredTypeName =
ElaboratedTypeNode->desugar().getAsString();

for (const TypedefNameDecl *Alias : Aliases->second) {
if (Alias->getName() != DesugaredTypeName) {
continue;
}

BoundNodesTreeBuilder Result(*Builder);
if (Matcher.matches(*Alias, this, &Result)) {
*Builder = std::move(Result);
return true;
}
}
}
}

for (const TypedefNameDecl *Alias : Aliases->second) {
BoundNodesTreeBuilder Result(*Builder);
if (Matcher.matches(*Alias, this, &Result)) {
Expand Down
17 changes: 17 additions & 0 deletions clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1167,6 +1167,23 @@ TEST_P(ASTMatchersTest, IsDerivedFrom_EmptyName) {
EXPECT_TRUE(notMatches(Code, cxxRecordDecl(isSameOrDerivedFrom(""))));
}

TEST_P(ASTMatchersTest, IsDerivedFrom_ElaboratedType) {
if (!GetParam().isCXX()) {
return;
}

DeclarationMatcher IsDerivenFromBase =
cxxRecordDecl(isDerivedFrom(decl().bind("typedef")));

EXPECT_TRUE(matchAndVerifyResultTrue(
"struct AnInterface {};"
"typedef AnInterface UnusedTypedef;"
"typedef AnInterface Base;"
"class AClass : public Base {};",
IsDerivenFromBase,
std::make_unique<VerifyIdIsBoundTo<TypedefDecl>>("typedef", "Base")));
}

TEST_P(ASTMatchersTest, IsDerivedFrom_ObjC) {
DeclarationMatcher IsDerivedFromX = objcInterfaceDecl(isDerivedFrom("X"));
EXPECT_TRUE(
Expand Down