1 //===- unittest/AST/MatchVerifier.h - AST unit test support ---------------===//
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 // Provides MatchVerifier, a base class to implement gtest matchers that
10 // verify things that can be matched on the AST.
11 //
12 // Also implements matchers based on MatchVerifier:
13 // LocationVerifier and RangeVerifier to verify whether a matched node has
14 // the expected source location or source range.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #ifndef LLVM_CLANG_UNITTESTS_AST_MATCHVERIFIER_H
19 #define LLVM_CLANG_UNITTESTS_AST_MATCHVERIFIER_H
20
21 #include "clang/AST/ASTContext.h"
22 #include "clang/ASTMatchers/ASTMatchFinder.h"
23 #include "clang/ASTMatchers/ASTMatchers.h"
24 #include "clang/Testing/CommandLineArgs.h"
25 #include "clang/Tooling/Tooling.h"
26 #include "gtest/gtest.h"
27
28 namespace clang {
29 namespace ast_matchers {
30
31 /// \brief Base class for verifying some property of nodes found by a matcher.
32 template <typename NodeType>
33 class MatchVerifier : public MatchFinder::MatchCallback {
34 public:
35 template <typename MatcherType>
match(const std::string & Code,const MatcherType & AMatcher)36 testing::AssertionResult match(const std::string &Code,
37 const MatcherType &AMatcher) {
38 std::vector<std::string> Args;
39 return match(Code, AMatcher, Args, Lang_CXX03);
40 }
41
42 template <typename MatcherType>
match(const std::string & Code,const MatcherType & AMatcher,TestLanguage L)43 testing::AssertionResult match(const std::string &Code,
44 const MatcherType &AMatcher, TestLanguage L) {
45 std::vector<std::string> Args;
46 return match(Code, AMatcher, Args, L);
47 }
48
49 template <typename MatcherType>
50 testing::AssertionResult
51 match(const std::string &Code, const MatcherType &AMatcher,
52 std::vector<std::string> &Args, TestLanguage L);
53
54 template <typename MatcherType>
55 testing::AssertionResult match(const Decl *D, const MatcherType &AMatcher);
56
57 protected:
58 void run(const MatchFinder::MatchResult &Result) override;
verify(const MatchFinder::MatchResult & Result,const NodeType & Node)59 virtual void verify(const MatchFinder::MatchResult &Result,
60 const NodeType &Node) {}
61
setFailure(const Twine & Result)62 void setFailure(const Twine &Result) {
63 Verified = false;
64 VerifyResult = Result.str();
65 }
66
setSuccess()67 void setSuccess() {
68 Verified = true;
69 }
70
71 private:
72 bool Verified;
73 std::string VerifyResult;
74 };
75
76 /// \brief Runs a matcher over some code, and returns the result of the
77 /// verifier for the matched node.
78 template <typename NodeType>
79 template <typename MatcherType>
80 testing::AssertionResult
match(const std::string & Code,const MatcherType & AMatcher,std::vector<std::string> & Args,TestLanguage L)81 MatchVerifier<NodeType>::match(const std::string &Code,
82 const MatcherType &AMatcher,
83 std::vector<std::string> &Args, TestLanguage L) {
84 MatchFinder Finder;
85 Finder.addMatcher(AMatcher.bind(""), this);
86 std::unique_ptr<tooling::FrontendActionFactory> Factory(
87 tooling::newFrontendActionFactory(&Finder));
88
89 StringRef FileName;
90 switch (L) {
91 case Lang_C89:
92 Args.push_back("-std=c89");
93 FileName = "input.c";
94 break;
95 case Lang_C99:
96 Args.push_back("-std=c99");
97 FileName = "input.c";
98 break;
99 case Lang_CXX03:
100 Args.push_back("-std=c++03");
101 FileName = "input.cc";
102 break;
103 case Lang_CXX11:
104 Args.push_back("-std=c++11");
105 FileName = "input.cc";
106 break;
107 case Lang_CXX14:
108 Args.push_back("-std=c++14");
109 FileName = "input.cc";
110 break;
111 case Lang_CXX17:
112 Args.push_back("-std=c++17");
113 FileName = "input.cc";
114 break;
115 case Lang_CXX20:
116 Args.push_back("-std=c++20");
117 FileName = "input.cc";
118 break;
119 case Lang_OpenCL:
120 Args.push_back("-cl-no-stdinc");
121 FileName = "input.cl";
122 break;
123 case Lang_OBJCXX:
124 FileName = "input.mm";
125 break;
126 }
127
128 // Default to failure in case callback is never called
129 setFailure("Could not find match");
130 if (!tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args, FileName))
131 return testing::AssertionFailure() << "Parsing error";
132 if (!Verified)
133 return testing::AssertionFailure() << VerifyResult;
134 return testing::AssertionSuccess();
135 }
136
137 /// \brief Runs a matcher over some AST, and returns the result of the
138 /// verifier for the matched node.
139 template <typename NodeType> template <typename MatcherType>
match(const Decl * D,const MatcherType & AMatcher)140 testing::AssertionResult MatchVerifier<NodeType>::match(
141 const Decl *D, const MatcherType &AMatcher) {
142 MatchFinder Finder;
143 Finder.addMatcher(AMatcher.bind(""), this);
144
145 setFailure("Could not find match");
146 Finder.match(*D, D->getASTContext());
147
148 if (!Verified)
149 return testing::AssertionFailure() << VerifyResult;
150 return testing::AssertionSuccess();
151 }
152
153 template <typename NodeType>
run(const MatchFinder::MatchResult & Result)154 void MatchVerifier<NodeType>::run(const MatchFinder::MatchResult &Result) {
155 const NodeType *Node = Result.Nodes.getNodeAs<NodeType>("");
156 if (!Node) {
157 setFailure("Matched node has wrong type");
158 } else {
159 // Callback has been called, default to success.
160 setSuccess();
161 verify(Result, *Node);
162 }
163 }
164
165 template <>
166 inline void
run(const MatchFinder::MatchResult & Result)167 MatchVerifier<DynTypedNode>::run(const MatchFinder::MatchResult &Result) {
168 BoundNodes::IDToNodeMap M = Result.Nodes.getMap();
169 BoundNodes::IDToNodeMap::const_iterator I = M.find("");
170 if (I == M.end()) {
171 setFailure("Node was not bound");
172 } else {
173 // Callback has been called, default to success.
174 setSuccess();
175 verify(Result, I->second);
176 }
177 }
178
179 /// \brief Verify whether a node has the correct source location.
180 ///
181 /// By default, Node.getSourceLocation() is checked. This can be changed
182 /// by overriding getLocation().
183 template <typename NodeType>
184 class LocationVerifier : public MatchVerifier<NodeType> {
185 public:
expectLocation(unsigned Line,unsigned Column)186 void expectLocation(unsigned Line, unsigned Column) {
187 ExpectLine = Line;
188 ExpectColumn = Column;
189 }
190
191 protected:
verify(const MatchFinder::MatchResult & Result,const NodeType & Node)192 void verify(const MatchFinder::MatchResult &Result,
193 const NodeType &Node) override {
194 SourceLocation Loc = getLocation(Node);
195 unsigned Line = Result.SourceManager->getSpellingLineNumber(Loc);
196 unsigned Column = Result.SourceManager->getSpellingColumnNumber(Loc);
197 if (Line != ExpectLine || Column != ExpectColumn) {
198 std::string MsgStr;
199 llvm::raw_string_ostream Msg(MsgStr);
200 Msg << "Expected location <" << ExpectLine << ":" << ExpectColumn
201 << ">, found <";
202 Loc.print(Msg, *Result.SourceManager);
203 Msg << '>';
204 this->setFailure(Msg.str());
205 }
206 }
207
getLocation(const NodeType & Node)208 virtual SourceLocation getLocation(const NodeType &Node) {
209 return Node.getLocation();
210 }
211
212 private:
213 unsigned ExpectLine, ExpectColumn;
214 };
215
216 /// \brief Verify whether a node has the correct source range.
217 ///
218 /// By default, Node.getSourceRange() is checked. This can be changed
219 /// by overriding getRange().
220 template <typename NodeType>
221 class RangeVerifier : public MatchVerifier<NodeType> {
222 public:
expectRange(unsigned BeginLine,unsigned BeginColumn,unsigned EndLine,unsigned EndColumn)223 void expectRange(unsigned BeginLine, unsigned BeginColumn,
224 unsigned EndLine, unsigned EndColumn) {
225 ExpectBeginLine = BeginLine;
226 ExpectBeginColumn = BeginColumn;
227 ExpectEndLine = EndLine;
228 ExpectEndColumn = EndColumn;
229 }
230
231 protected:
verify(const MatchFinder::MatchResult & Result,const NodeType & Node)232 void verify(const MatchFinder::MatchResult &Result,
233 const NodeType &Node) override {
234 SourceRange R = getRange(Node);
235 SourceLocation Begin = R.getBegin();
236 SourceLocation End = R.getEnd();
237 unsigned BeginLine = Result.SourceManager->getSpellingLineNumber(Begin);
238 unsigned BeginColumn = Result.SourceManager->getSpellingColumnNumber(Begin);
239 unsigned EndLine = Result.SourceManager->getSpellingLineNumber(End);
240 unsigned EndColumn = Result.SourceManager->getSpellingColumnNumber(End);
241 if (BeginLine != ExpectBeginLine || BeginColumn != ExpectBeginColumn ||
242 EndLine != ExpectEndLine || EndColumn != ExpectEndColumn) {
243 std::string MsgStr;
244 llvm::raw_string_ostream Msg(MsgStr);
245 Msg << "Expected range <" << ExpectBeginLine << ":" << ExpectBeginColumn
246 << '-' << ExpectEndLine << ":" << ExpectEndColumn << ">, found <";
247 Begin.print(Msg, *Result.SourceManager);
248 Msg << '-';
249 End.print(Msg, *Result.SourceManager);
250 Msg << '>';
251 this->setFailure(Msg.str());
252 }
253 }
254
getRange(const NodeType & Node)255 virtual SourceRange getRange(const NodeType &Node) {
256 return Node.getSourceRange();
257 }
258
259 private:
260 unsigned ExpectBeginLine, ExpectBeginColumn, ExpectEndLine, ExpectEndColumn;
261 };
262
263 /// \brief Verify whether a node's dump contains a given substring.
264 class DumpVerifier : public MatchVerifier<DynTypedNode> {
265 public:
expectSubstring(const std::string & Str)266 void expectSubstring(const std::string &Str) {
267 ExpectSubstring = Str;
268 }
269
270 protected:
verify(const MatchFinder::MatchResult & Result,const DynTypedNode & Node)271 void verify(const MatchFinder::MatchResult &Result,
272 const DynTypedNode &Node) override {
273 std::string DumpStr;
274 llvm::raw_string_ostream Dump(DumpStr);
275 Node.dump(Dump, *Result.Context);
276
277 if (Dump.str().find(ExpectSubstring) == std::string::npos) {
278 std::string MsgStr;
279 llvm::raw_string_ostream Msg(MsgStr);
280 Msg << "Expected dump substring <" << ExpectSubstring << ">, found <"
281 << Dump.str() << '>';
282 this->setFailure(Msg.str());
283 }
284 }
285
286 private:
287 std::string ExpectSubstring;
288 };
289
290 /// \brief Verify whether a node's pretty print matches a given string.
291 class PrintVerifier : public MatchVerifier<DynTypedNode> {
292 public:
expectString(const std::string & Str)293 void expectString(const std::string &Str) {
294 ExpectString = Str;
295 }
296
297 protected:
verify(const MatchFinder::MatchResult & Result,const DynTypedNode & Node)298 void verify(const MatchFinder::MatchResult &Result,
299 const DynTypedNode &Node) override {
300 std::string PrintStr;
301 llvm::raw_string_ostream Print(PrintStr);
302 Node.print(Print, Result.Context->getPrintingPolicy());
303
304 if (Print.str() != ExpectString) {
305 std::string MsgStr;
306 llvm::raw_string_ostream Msg(MsgStr);
307 Msg << "Expected pretty print <" << ExpectString << ">, found <"
308 << Print.str() << '>';
309 this->setFailure(Msg.str());
310 }
311 }
312
313 private:
314 std::string ExpectString;
315 };
316
317 } // end namespace ast_matchers
318 } // end namespace clang
319
320 #endif
321