From: Samuel Benzaquen Date: Mon, 27 Oct 2014 20:58:44 +0000 (+0000) Subject: Fix segfault in hasDeclContext for nodes that have no decl context. X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=03ee47bd153732c48ece2970e27d8740fc443e1e;p=clang Fix segfault in hasDeclContext for nodes that have no decl context. Summary: Some declarations do not have a declaration context, like TranslationUnitDecl. Fix hasDeclContext() to not segfault on these nodes. Reviewers: klimek Subscribers: klimek, cfe-commits Differential Revision: http://reviews.llvm.org/D6003 git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@220719 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/include/clang/ASTMatchers/ASTMatchers.h b/include/clang/ASTMatchers/ASTMatchers.h index fdb32f3ae9..93cb0ef6ec 100644 --- a/include/clang/ASTMatchers/ASTMatchers.h +++ b/include/clang/ASTMatchers/ASTMatchers.h @@ -3567,8 +3567,9 @@ AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher, /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the /// declaration of \c class \c D. AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher, InnerMatcher) { - return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()), - Finder, Builder); + const DeclContext *DC = Node.getDeclContext(); + if (!DC) return false; + return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder); } /// \brief Matches nested name specifiers. diff --git a/unittests/ASTMatchers/ASTMatchersTest.cpp b/unittests/ASTMatchers/ASTMatchersTest.cpp index b2c2a386e8..5a8f42a87c 100644 --- a/unittests/ASTMatchers/ASTMatchersTest.cpp +++ b/unittests/ASTMatchers/ASTMatchersTest.cpp @@ -375,6 +375,8 @@ TEST(DeclarationMatcher, hasDeclContext) { "}", recordDecl(hasDeclContext(namespaceDecl( hasName("M"), hasDeclContext(namespaceDecl())))))); + + EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl())))); } TEST(DeclarationMatcher, LinkageSpecification) {