Debian Codegraph @

clang/unittests/Analysis/FlowSensitive/ASTOpsTest.cpp

raw
1 //===- unittests/Analysis/FlowSensitive/ASTOpsTest.cpp --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "clang/Analysis/FlowSensitive/ASTOps.h"
10 #include "TestingSupport.h"
11 #include "gmock/gmock.h"
12 #include "gtest/gtest.h"
13 #include <memory>
14
15 namespace {
16
17 using namespace clang;
18 using namespace dataflow;
19
20 using ast_matchers::cxxRecordDecl;
21 using ast_matchers::hasName;
22 using ast_matchers::hasType;
23 using ast_matchers::initListExpr;
24 using ast_matchers::match;
25 using ast_matchers::selectFirst;
26 using test::findValueDecl;
27 using testing::IsEmpty;
28 using testing::UnorderedElementsAre;
29
30 TEST(ASTOpsTest, RecordInitListHelperOnEmptyUnionInitList) {
31 // This is a regression test: The `RecordInitListHelper` used to assert-fail
32 // when called for the `InitListExpr` of an empty union.
33 std::string Code = R"cc(
34 struct S {
35 S() : UField{} {};
36
37 union U {} UField;
38 };
39 )cc";
40 std::unique_ptr<ASTUnit> Unit =
41 tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++17"});
42 auto &ASTCtx = Unit->getASTContext();
43
44 ASSERT_EQ(ASTCtx.getDiagnostics().getClient()->getNumErrors(), 0U);
45
46 auto *InitList = selectFirst<InitListExpr>(
47 "init",
48 match(initListExpr(hasType(cxxRecordDecl(hasName("U")))).bind("init"),
49 ASTCtx));
50 ASSERT_NE(InitList, nullptr);
51
52 RecordInitListHelper Helper(InitList);
53 EXPECT_THAT(Helper.base_inits(), IsEmpty());
54 EXPECT_THAT(Helper.field_inits(), IsEmpty());
55 }
56
57 TEST(ASTOpsTest, ReferencedDeclsOnUnionInitList) {
58 // This is a regression test: `getReferencedDecls()` used to return a null
59 // `FieldDecl` in this case (in addition to the correct non-null `FieldDecl`)
60 // because `getInitializedFieldInUnion()` returns null for the syntactic form
61 // of the `InitListExpr`.
62 std::string Code = R"cc(
63 struct S {
64 S() : UField{0} {};
65
66 union U {
67 int I;
68 } UField;
69 };
70 )cc";
71 std::unique_ptr<ASTUnit> Unit =
72 tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++17"});
73 auto &ASTCtx = Unit->getASTContext();
74
75 ASSERT_EQ(ASTCtx.getDiagnostics().getClient()->getNumErrors(), 0U);
76
77 auto *InitList = selectFirst<InitListExpr>(
78 "init",
79 match(initListExpr(hasType(cxxRecordDecl(hasName("U")))).bind("init"),
80 ASTCtx));
81 ASSERT_NE(InitList, nullptr);
82 auto *IDecl = cast<FieldDecl>(findValueDecl(ASTCtx, "I"));
83
84 EXPECT_THAT(getReferencedDecls(*InitList).Fields,
85 UnorderedElementsAre(IDecl));
86 }
87
88 } // namespace