Fix segfault in hasDeclContext for nodes that have no decl context.
authorSamuel Benzaquen <sbenza@google.com>
Mon, 27 Oct 2014 20:58:44 +0000 (20:58 +0000)
committerSamuel Benzaquen <sbenza@google.com>
Mon, 27 Oct 2014 20:58:44 +0000 (20:58 +0000)
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

llvm-svn: 220719

clang/include/clang/ASTMatchers/ASTMatchers.h
clang/unittests/ASTMatchers/ASTMatchersTest.cpp

index fdb32f3..93cb0ef 100644 (file)
@@ -3567,8 +3567,9 @@ AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
 /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
 /// declaration of \c class \c D.
 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, 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.
index b2c2a38..5a8f42a 100644 (file)
@@ -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) {