File: MatchSwitchTest.cpp

package info (click to toggle)
llvm-toolchain-15 1%3A15.0.6-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,554,644 kB
  • sloc: cpp: 5,922,452; ansic: 1,012,136; asm: 674,362; python: 191,568; objc: 73,855; f90: 42,327; lisp: 31,913; pascal: 11,973; javascript: 10,144; sh: 9,421; perl: 7,447; ml: 5,527; awk: 3,523; makefile: 2,520; xml: 885; cs: 573; fortran: 567
file content (229 lines) | stat: -rw-r--r-- 6,849 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
//===- unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
//  This file defines a simplistic version of Constant Propagation as an example
//  of a forward, monotonic dataflow analysis. The analysis tracks all
//  variables in the scope, but lacks escape analysis.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/FlowSensitive/MatchSwitch.h"
#include "TestingSupport.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Stmt.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
#include "clang/Analysis/FlowSensitive/DataflowLattice.h"
#include "clang/Analysis/FlowSensitive/MapLattice.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
#include "llvm/Testing/Support/Annotations.h"
#include "llvm/Testing/Support/Error.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <cstdint>
#include <memory>
#include <ostream>
#include <string>
#include <utility>

using namespace clang;
using namespace dataflow;

namespace {
using ::testing::Pair;
using ::testing::UnorderedElementsAre;

class BooleanLattice {
public:
  BooleanLattice() : Value(false) {}
  explicit BooleanLattice(bool B) : Value(B) {}

  static BooleanLattice bottom() { return BooleanLattice(false); }

  static BooleanLattice top() { return BooleanLattice(true); }

  LatticeJoinEffect join(BooleanLattice Other) {
    auto Prev = Value;
    Value = Value || Other.Value;
    return Prev == Value ? LatticeJoinEffect::Unchanged
                         : LatticeJoinEffect::Changed;
  }

  friend bool operator==(BooleanLattice LHS, BooleanLattice RHS) {
    return LHS.Value == RHS.Value;
  }

  friend std::ostream &operator<<(std::ostream &Os, const BooleanLattice &B) {
    Os << B.Value;
    return Os;
  }

  bool value() const { return Value; }

private:
  bool Value;
};
} // namespace

MATCHER_P(Holds, m,
          ((negation ? "doesn't hold" : "holds") +
           llvm::StringRef(" a lattice element that ") +
           ::testing::DescribeMatcher<BooleanLattice>(m, negation))
              .str()) {
  return ExplainMatchResult(m, arg.Lattice, result_listener);
}

void TransferSetTrue(const DeclRefExpr *,
                     const ast_matchers::MatchFinder::MatchResult &,
                     TransferState<BooleanLattice> &State) {
  State.Lattice = BooleanLattice(true);
}

void TransferSetFalse(const Stmt *,
                      const ast_matchers::MatchFinder::MatchResult &,
                      TransferState<BooleanLattice> &State) {
  State.Lattice = BooleanLattice(false);
}

class TestAnalysis : public DataflowAnalysis<TestAnalysis, BooleanLattice> {
  MatchSwitch<TransferState<BooleanLattice>> TransferSwitch;

public:
  explicit TestAnalysis(ASTContext &Context)
      : DataflowAnalysis<TestAnalysis, BooleanLattice>(Context) {
    using namespace ast_matchers;
    TransferSwitch =
        MatchSwitchBuilder<TransferState<BooleanLattice>>()
            .CaseOf<DeclRefExpr>(declRefExpr(to(varDecl(hasName("X")))),
                                 TransferSetTrue)
            .CaseOf<Stmt>(callExpr(callee(functionDecl(hasName("Foo")))),
                          TransferSetFalse)
            .Build();
  }

  static BooleanLattice initialElement() { return BooleanLattice::bottom(); }

  void transfer(const Stmt *S, BooleanLattice &L, Environment &Env) {
    TransferState<BooleanLattice> State(L, Env);
    TransferSwitch(*S, getASTContext(), State);
  }
};

template <typename Matcher>
void RunDataflow(llvm::StringRef Code, Matcher Expectations) {
  ASSERT_THAT_ERROR(
      test::checkDataflow<TestAnalysis>(
          Code, "fun",
          [](ASTContext &C, Environment &) { return TestAnalysis(C); },
          [&Expectations](
              llvm::ArrayRef<std::pair<
                  std::string, DataflowAnalysisState<TestAnalysis::Lattice>>>
                  Results,
              ASTContext &) { EXPECT_THAT(Results, Expectations); },
          {"-fsyntax-only", "-std=c++17"}),
      llvm::Succeeded());
}

TEST(MatchSwitchTest, JustX) {
  std::string Code = R"(
    void fun() {
      int X = 1;
      (void)X;
      // [[p]]
    }
  )";
  RunDataflow(Code,
              UnorderedElementsAre(Pair("p", Holds(BooleanLattice(true)))));
}

TEST(MatchSwitchTest, JustFoo) {
  std::string Code = R"(
    void Foo();
    void fun() {
      Foo();
      // [[p]]
    }
  )";
  RunDataflow(Code,
              UnorderedElementsAre(Pair("p", Holds(BooleanLattice(false)))));
}

TEST(MatchSwitchTest, XThenFoo) {
  std::string Code = R"(
    void Foo();
    void fun() {
      int X = 1;
      (void)X;
      Foo();
      // [[p]]
    }
  )";
  RunDataflow(Code,
              UnorderedElementsAre(Pair("p", Holds(BooleanLattice(false)))));
}

TEST(MatchSwitchTest, FooThenX) {
  std::string Code = R"(
    void Foo();
    void fun() {
      Foo();
      int X = 1;
      (void)X;
      // [[p]]
    }
  )";
  RunDataflow(Code,
              UnorderedElementsAre(Pair("p", Holds(BooleanLattice(true)))));
}

TEST(MatchSwitchTest, Neither) {
  std::string Code = R"(
    void Bar();
    void fun(bool b) {
      Bar();
      // [[p]]
    }
  )";
  RunDataflow(Code,
              UnorderedElementsAre(Pair("p", Holds(BooleanLattice(false)))));
}

TEST(MatchSwitchTest, ReturnNonVoid) {
  using namespace ast_matchers;

  auto Unit =
      tooling::buildASTFromCode("void f() { int x = 42; }", "input.cc",
                                std::make_shared<PCHContainerOperations>());
  auto &Context = Unit->getASTContext();
  const auto *S =
      selectFirst<FunctionDecl>(
          "f",
          match(functionDecl(isDefinition(), hasName("f")).bind("f"), Context))
          ->getBody();

  MatchSwitch<const int, std::vector<int>> Switch =
      MatchSwitchBuilder<const int, std::vector<int>>()
          .CaseOf<Stmt>(stmt(),
                        [](const Stmt *, const MatchFinder::MatchResult &,
                           const int &State) -> std::vector<int> {
                          return {1, State, 3};
                        })
          .Build();
  std::vector<int> Actual = Switch(*S, Context, 7);
  std::vector<int> Expected{1, 7, 3};
  EXPECT_EQ(Actual, Expected);
}