blob: 5eb0c6481b0a41785fef5ab5365ad02038e6504c [file] [log] [blame]
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00006//
7//===----------------------------------------------------------------------===//
8//
9// FileCheck does a line-by line check of a file that validates whether it
10// contains the expected content. This is useful for regression tests etc.
11//
12// This file implements most of the API that will be used by the FileCheck utility
13// as well as various unittests.
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Support/FileCheck.h"
17#include "llvm/ADT/StringSet.h"
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +000018#include "llvm/Support/FormatVariadic.h"
19#include <cstdint>
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +000020#include <list>
21#include <map>
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +000022#include <tuple>
23#include <utility>
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +000024
25using namespace llvm;
26
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000027bool FileCheckNumericVariable::setValue(uint64_t NewValue) {
28 if (Value)
29 return true;
30 Value = NewValue;
31 return false;
32}
33
34bool FileCheckNumericVariable::clearValue() {
35 if (!Value)
36 return true;
37 Value = llvm::None;
38 return false;
39}
40
41llvm::Optional<uint64_t> FileCheckNumExpr::eval() const {
42 llvm::Optional<uint64_t> LeftOp = this->LeftOp->getValue();
43 // Variable is undefined.
44 if (!LeftOp)
45 return llvm::None;
46 return EvalBinop(*LeftOp, RightOp);
47}
48
49StringRef FileCheckNumExpr::getUndefVarName() const {
50 if (!LeftOp->getValue())
51 return LeftOp->getName();
52 return StringRef();
53}
54
Thomas Preud'homme1a944d22019-05-23 00:10:14 +000055llvm::Optional<std::string> FileCheckSubstitution::getResult() const {
56 if (IsNumSubst) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000057 llvm::Optional<uint64_t> EvaluatedValue = NumExpr->eval();
58 if (!EvaluatedValue)
Thomas Preud'homme288ed912019-05-02 00:04:38 +000059 return llvm::None;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000060 return utostr(*EvaluatedValue);
Thomas Preud'homme288ed912019-05-02 00:04:38 +000061 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000062
63 // Look up the value and escape it so that we can put it into the regex.
64 llvm::Optional<StringRef> VarVal = Context->getPatternVarValue(FromStr);
65 if (!VarVal)
66 return llvm::None;
67 return Regex::escape(*VarVal);
Thomas Preud'homme288ed912019-05-02 00:04:38 +000068}
69
Thomas Preud'homme1a944d22019-05-23 00:10:14 +000070StringRef FileCheckSubstitution::getUndefVarName() const {
71 if (IsNumSubst)
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000072 // Although a use of an undefined numeric variable is detected at parse
73 // time, a numeric variable can be undefined later by ClearLocalVariables.
74 return NumExpr->getUndefVarName();
Thomas Preud'homme288ed912019-05-02 00:04:38 +000075
76 if (!Context->getPatternVarValue(FromStr))
77 return FromStr;
78
79 return StringRef();
80}
81
Thomas Preud'homme5a330472019-04-29 13:32:36 +000082bool FileCheckPattern::isValidVarNameStart(char C) {
83 return C == '_' || isalpha(C);
84}
85
86bool FileCheckPattern::parseVariable(StringRef Str, bool &IsPseudo,
87 unsigned &TrailIdx) {
88 if (Str.empty())
89 return true;
90
91 bool ParsedOneChar = false;
92 unsigned I = 0;
93 IsPseudo = Str[0] == '@';
94
95 // Global vars start with '$'.
96 if (Str[0] == '$' || IsPseudo)
97 ++I;
98
99 for (unsigned E = Str.size(); I != E; ++I) {
100 if (!ParsedOneChar && !isValidVarNameStart(Str[I]))
101 return true;
102
103 // Variable names are composed of alphanumeric characters and underscores.
104 if (Str[I] != '_' && !isalnum(Str[I]))
105 break;
106 ParsedOneChar = true;
107 }
108
109 TrailIdx = I;
110 return false;
111}
112
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000113// StringRef holding all characters considered as horizontal whitespaces by
114// FileCheck input canonicalization.
115StringRef SpaceChars = " \t";
116
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000117// Parsing helper function that strips the first character in S and returns it.
118static char popFront(StringRef &S) {
119 char C = S.front();
120 S = S.drop_front();
121 return C;
122}
123
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000124static uint64_t add(uint64_t LeftOp, uint64_t RightOp) {
125 return LeftOp + RightOp;
126}
127static uint64_t sub(uint64_t LeftOp, uint64_t RightOp) {
128 return LeftOp - RightOp;
129}
130
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000131FileCheckNumExpr *
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000132FileCheckPattern::parseNumericSubstitution(StringRef Name, bool IsPseudo,
133 StringRef Trailer,
134 const SourceMgr &SM) const {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000135 if (IsPseudo && !Name.equals("@LINE")) {
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000136 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000137 "invalid pseudo numeric variable '" + Name + "'");
138 return nullptr;
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000139 }
140
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000141 // This method is indirectly called from ParsePattern for all numeric
142 // variable definitions and uses in the order in which they appear in the
143 // CHECK pattern. For each definition, the pointer to the class instance of
144 // the corresponding numeric variable definition is stored in
145 // GlobalNumericVariableTable. Therefore, the pointer we get below is for the
146 // class instance corresponding to the last definition of this variable use.
147 auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
148 if (VarTableIter == Context->GlobalNumericVariableTable.end()) {
149 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
150 "using undefined numeric variable '" + Name + "'");
151 return nullptr;
152 }
153
154 FileCheckNumericVariable *LeftOp = VarTableIter->second;
155
156 // Check if this is a supported operation and select a function to perform
157 // it.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000158 Trailer = Trailer.ltrim(SpaceChars);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000159 if (Trailer.empty()) {
160 return Context->makeNumExpr(add, LeftOp, 0);
161 }
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000162 SMLoc OpLoc = SMLoc::getFromPointer(Trailer.data());
163 char Operator = popFront(Trailer);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000164 binop_eval_t EvalBinop;
165 switch (Operator) {
166 case '+':
167 EvalBinop = add;
168 break;
169 case '-':
170 EvalBinop = sub;
171 break;
172 default:
173 SM.PrintMessage(OpLoc, SourceMgr::DK_Error,
174 Twine("unsupported numeric operation '") + Twine(Operator) +
175 "'");
176 return nullptr;
177 }
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000178
179 // Parse right operand.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000180 Trailer = Trailer.ltrim(SpaceChars);
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000181 if (Trailer.empty()) {
182 SM.PrintMessage(SMLoc::getFromPointer(Trailer.data()), SourceMgr::DK_Error,
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000183 "missing operand in numeric expression");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000184 return nullptr;
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000185 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000186 uint64_t RightOp;
187 if (Trailer.consumeInteger(10, RightOp)) {
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000188 SM.PrintMessage(SMLoc::getFromPointer(Trailer.data()), SourceMgr::DK_Error,
189 "invalid offset in numeric expression '" + Trailer + "'");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000190 return nullptr;
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000191 }
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000192 Trailer = Trailer.ltrim(SpaceChars);
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000193 if (!Trailer.empty()) {
194 SM.PrintMessage(SMLoc::getFromPointer(Trailer.data()), SourceMgr::DK_Error,
195 "unexpected characters at end of numeric expression '" +
196 Trailer + "'");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000197 return nullptr;
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000198 }
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000199
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000200 return Context->makeNumExpr(EvalBinop, LeftOp, RightOp);
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000201}
202
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000203bool FileCheckPattern::ParsePattern(StringRef PatternStr, StringRef Prefix,
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000204 SourceMgr &SM, unsigned LineNumber,
205 const FileCheckRequest &Req) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000206 bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
207
208 this->LineNumber = LineNumber;
209 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
210
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000211 // Create fake @LINE pseudo variable definition.
212 StringRef LinePseudo = "@LINE";
213 uint64_t LineNumber64 = LineNumber;
214 FileCheckNumericVariable *LinePseudoVar =
215 Context->makeNumericVariable(LinePseudo, LineNumber64);
216 Context->GlobalNumericVariableTable[LinePseudo] = LinePseudoVar;
217
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000218 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
219 // Ignore trailing whitespace.
220 while (!PatternStr.empty() &&
221 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
222 PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
223
224 // Check that there is something on the line.
225 if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
226 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
227 "found empty check string with prefix '" + Prefix + ":'");
228 return true;
229 }
230
231 if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
232 SM.PrintMessage(
233 PatternLoc, SourceMgr::DK_Error,
234 "found non-empty check string for empty check with prefix '" + Prefix +
235 ":'");
236 return true;
237 }
238
239 if (CheckTy == Check::CheckEmpty) {
240 RegExStr = "(\n$)";
241 return false;
242 }
243
244 // Check to see if this is a fixed string, or if it has regex pieces.
245 if (!MatchFullLinesHere &&
246 (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
247 PatternStr.find("[[") == StringRef::npos))) {
248 FixedStr = PatternStr;
249 return false;
250 }
251
252 if (MatchFullLinesHere) {
253 RegExStr += '^';
254 if (!Req.NoCanonicalizeWhiteSpace)
255 RegExStr += " *";
256 }
257
258 // Paren value #0 is for the fully matched string. Any new parenthesized
259 // values add from there.
260 unsigned CurParen = 1;
261
262 // Otherwise, there is at least one regex piece. Build up the regex pattern
263 // by escaping scary characters in fixed strings, building up one big regex.
264 while (!PatternStr.empty()) {
265 // RegEx matches.
266 if (PatternStr.startswith("{{")) {
267 // This is the start of a regex match. Scan for the }}.
268 size_t End = PatternStr.find("}}");
269 if (End == StringRef::npos) {
270 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
271 SourceMgr::DK_Error,
272 "found start of regex string with no end '}}'");
273 return true;
274 }
275
276 // Enclose {{}} patterns in parens just like [[]] even though we're not
277 // capturing the result for any purpose. This is required in case the
278 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
279 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
280 RegExStr += '(';
281 ++CurParen;
282
283 if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
284 return true;
285 RegExStr += ')';
286
287 PatternStr = PatternStr.substr(End + 2);
288 continue;
289 }
290
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000291 // String and numeric substitution blocks. String substitution blocks come
292 // in two forms: [[foo:.*]] and [[foo]]. The former matches .* (or some
293 // other regex) and assigns it to the string variable 'foo'. The latter
294 // substitutes foo's value. Numeric substitution blocks start with a
295 // '#' sign after the double brackets and only have the substitution form.
296 // Both string and numeric variables must satisfy the regular expression
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000297 // "[a-zA-Z_][0-9a-zA-Z_]*" to be valid, as this helps catch some common
298 // errors.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000299 if (PatternStr.startswith("[[")) {
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000300 StringRef UnparsedPatternStr = PatternStr.substr(2);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000301 // Find the closing bracket pair ending the match. End is going to be an
302 // offset relative to the beginning of the match string.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000303 size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
304 StringRef MatchStr = UnparsedPatternStr.substr(0, End);
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000305 bool IsNumBlock = MatchStr.consume_front("#");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000306
307 if (End == StringRef::npos) {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000308 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
309 SourceMgr::DK_Error,
310 "Invalid substitution block, no ]] found");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000311 return true;
312 }
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000313 // Strip the substitution block we are parsing. End points to the start
314 // of the "]]" closing the expression so account for it in computing the
315 // index of the first unparsed character.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000316 PatternStr = UnparsedPatternStr.substr(End + 2);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000317
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000318 size_t VarEndIdx = MatchStr.find(":");
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000319 if (IsNumBlock)
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000320 MatchStr = MatchStr.ltrim(SpaceChars);
321 else {
322 size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
323 if (SpacePos != StringRef::npos) {
324 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
325 SourceMgr::DK_Error, "unexpected whitespace");
326 return true;
327 }
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000328 }
329
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000330 // Get the variable name (e.g. "foo") and verify it is well formed.
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000331 bool IsPseudo;
332 unsigned TrailIdx;
333 if (parseVariable(MatchStr, IsPseudo, TrailIdx)) {
334 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data()),
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000335 SourceMgr::DK_Error, "invalid variable name");
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000336 return true;
337 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000338
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000339 size_t SubstInsertIdx = RegExStr.size();
340 FileCheckNumExpr *NumExpr;
341
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000342 StringRef Name = MatchStr.substr(0, TrailIdx);
343 StringRef Trailer = MatchStr.substr(TrailIdx);
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000344 bool IsVarDef = (VarEndIdx != StringRef::npos);
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000345
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000346 if (IsVarDef) {
347 if (IsPseudo || !Trailer.consume_front(":")) {
348 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data()),
349 SourceMgr::DK_Error,
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000350 "invalid name in string variable definition");
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000351 return true;
352 }
353
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000354 // Detect collisions between string and numeric variables when the
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000355 // former is created later than the latter.
356 if (Context->GlobalNumericVariableTable.find(Name) !=
357 Context->GlobalNumericVariableTable.end()) {
358 SM.PrintMessage(
359 SMLoc::getFromPointer(MatchStr.data()), SourceMgr::DK_Error,
360 "numeric variable with name '" + Name + "' already exists");
361 return true;
362 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000363 }
364
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000365 if (IsNumBlock || (!IsVarDef && IsPseudo)) {
366 NumExpr = parseNumericSubstitution(Name, IsPseudo, Trailer, SM);
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000367 if (NumExpr == nullptr)
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000368 return true;
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000369 IsNumBlock = true;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000370 }
371
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000372 // Handle substitutions: [[foo]] and [[#<foo expr>]].
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000373 if (!IsVarDef) {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000374 // Handle substitution of string variables that were defined earlier on
375 // the same line by emitting a backreference.
376 if (!IsNumBlock && VariableDefs.find(Name) != VariableDefs.end()) {
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000377 unsigned CaptureParen = VariableDefs[Name];
378 if (CaptureParen < 1 || CaptureParen > 9) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000379 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
380 SourceMgr::DK_Error,
381 "Can't back-reference more than 9 variables");
382 return true;
383 }
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000384 AddBackrefToRegEx(CaptureParen);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000385 } else {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000386 // Handle substitution of string variables ([[<var>]]) defined in
387 // previous CHECK patterns, and substitution of numeric expressions.
388 FileCheckSubstitution Substitution =
389 IsNumBlock ? FileCheckSubstitution(Context, MatchStr, NumExpr,
390 SubstInsertIdx)
391 : FileCheckSubstitution(Context, MatchStr,
392 SubstInsertIdx);
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000393 Substitutions.push_back(Substitution);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000394 }
395 continue;
396 }
397
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000398 // Handle variable definitions: [[foo:.*]].
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000399 VariableDefs[Name] = CurParen;
400 RegExStr += '(';
401 ++CurParen;
402
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000403 if (AddRegExToRegEx(Trailer, CurParen, SM))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000404 return true;
405
406 RegExStr += ')';
407 }
408
409 // Handle fixed string matches.
410 // Find the end, which is the start of the next regex.
411 size_t FixedMatchEnd = PatternStr.find("{{");
412 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
413 RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
414 PatternStr = PatternStr.substr(FixedMatchEnd);
415 }
416
417 if (MatchFullLinesHere) {
418 if (!Req.NoCanonicalizeWhiteSpace)
419 RegExStr += " *";
420 RegExStr += '$';
421 }
422
423 return false;
424}
425
426bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
427 Regex R(RS);
428 std::string Error;
429 if (!R.isValid(Error)) {
430 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
431 "invalid regex: " + Error);
432 return true;
433 }
434
435 RegExStr += RS.str();
436 CurParen += R.getNumMatches();
437 return false;
438}
439
440void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
441 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
442 std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
443 RegExStr += Backref;
444}
445
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000446size_t FileCheckPattern::match(StringRef Buffer, size_t &MatchLen) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000447 // If this is the EOF pattern, match it immediately.
448 if (CheckTy == Check::CheckEOF) {
449 MatchLen = 0;
450 return Buffer.size();
451 }
452
453 // If this is a fixed string pattern, just match it now.
454 if (!FixedStr.empty()) {
455 MatchLen = FixedStr.size();
456 return Buffer.find(FixedStr);
457 }
458
459 // Regex match.
460
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000461 // If there are substitutions, we need to create a temporary string with the
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000462 // actual value.
463 StringRef RegExToMatch = RegExStr;
464 std::string TmpStr;
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000465 if (!Substitutions.empty()) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000466 TmpStr = RegExStr;
467
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000468 size_t InsertOffset = 0;
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000469 // Substitute all string variables and numeric expressions whose values are
470 // only now known. Use of string variables defined on the same line are
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000471 // handled by back-references.
472 for (const auto &Substitution : Substitutions) {
473 // Substitute and check for failure (e.g. use of undefined variable).
474 llvm::Optional<std::string> Value = Substitution.getResult();
475 if (!Value)
476 return StringRef::npos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000477
478 // Plop it into the regex at the adjusted offset.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000479 TmpStr.insert(TmpStr.begin() + Substitution.getIndex() + InsertOffset,
480 Value->begin(), Value->end());
481 InsertOffset += Value->size();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000482 }
483
484 // Match the newly constructed regex.
485 RegExToMatch = TmpStr;
486 }
487
488 SmallVector<StringRef, 4> MatchInfo;
489 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
490 return StringRef::npos;
491
492 // Successful regex match.
493 assert(!MatchInfo.empty() && "Didn't get any match");
494 StringRef FullMatch = MatchInfo[0];
495
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000496 // If this defines any string variables, remember their values.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000497 for (const auto &VariableDef : VariableDefs) {
498 assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000499 Context->GlobalVariableTable[VariableDef.first] =
500 MatchInfo[VariableDef.second];
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000501 }
502
503 // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
504 // the required preceding newline, which is consumed by the pattern in the
505 // case of CHECK-EMPTY but not CHECK-NEXT.
506 size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
507 MatchLen = FullMatch.size() - MatchStartSkip;
508 return FullMatch.data() - Buffer.data() + MatchStartSkip;
509}
510
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000511unsigned FileCheckPattern::computeMatchDistance(StringRef Buffer) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000512 // Just compute the number of matching characters. For regular expressions, we
513 // just compare against the regex itself and hope for the best.
514 //
515 // FIXME: One easy improvement here is have the regex lib generate a single
516 // example regular expression which matches, and use that as the example
517 // string.
518 StringRef ExampleString(FixedStr);
519 if (ExampleString.empty())
520 ExampleString = RegExStr;
521
522 // Only compare up to the first line in the buffer, or the string size.
523 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
524 BufferPrefix = BufferPrefix.split('\n').first;
525 return BufferPrefix.edit_distance(ExampleString);
526}
527
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000528void FileCheckPattern::printSubstitutions(const SourceMgr &SM, StringRef Buffer,
529 SMRange MatchRange) const {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000530 // Print what we know about substitutions.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000531 if (!Substitutions.empty()) {
532 for (const auto &Substitution : Substitutions) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000533 SmallString<256> Msg;
534 raw_svector_ostream OS(Msg);
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000535 bool IsNumSubst = Substitution.isNumSubst();
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000536 llvm::Optional<std::string> MatchedValue = Substitution.getResult();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000537
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000538 // Substitution failed or is not known at match time, print the undefined
539 // variable it uses.
540 if (!MatchedValue) {
541 StringRef UndefVarName = Substitution.getUndefVarName();
542 if (UndefVarName.empty())
543 continue;
544 OS << "uses undefined variable \"";
545 OS.write_escaped(UndefVarName) << "\"";
546 } else {
547 // Substitution succeeded. Print substituted value.
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000548 if (IsNumSubst)
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000549 OS << "with numeric expression \"";
550 else
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000551 OS << "with string variable \"";
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000552 OS.write_escaped(Substitution.getFromString()) << "\" equal to \"";
553 OS.write_escaped(*MatchedValue) << "\"";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000554 }
555
556 if (MatchRange.isValid())
557 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
558 {MatchRange});
559 else
560 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
561 SourceMgr::DK_Note, OS.str());
562 }
563 }
564}
565
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000566static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
567 const SourceMgr &SM, SMLoc Loc,
568 Check::FileCheckType CheckTy,
569 StringRef Buffer, size_t Pos, size_t Len,
Joel E. Denny7df86962018-12-18 00:03:03 +0000570 std::vector<FileCheckDiag> *Diags,
571 bool AdjustPrevDiag = false) {
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000572 SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
573 SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
574 SMRange Range(Start, End);
Joel E. Denny96f0e842018-12-18 00:03:36 +0000575 if (Diags) {
Joel E. Denny7df86962018-12-18 00:03:03 +0000576 if (AdjustPrevDiag)
577 Diags->rbegin()->MatchTy = MatchTy;
578 else
579 Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
580 }
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000581 return Range;
582}
583
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000584void FileCheckPattern::printFuzzyMatch(
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000585 const SourceMgr &SM, StringRef Buffer,
Joel E. Denny2c007c82018-12-18 00:02:04 +0000586 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000587 // Attempt to find the closest/best fuzzy match. Usually an error happens
588 // because some string in the output didn't exactly match. In these cases, we
589 // would like to show the user a best guess at what "should have" matched, to
590 // save them having to actually check the input manually.
591 size_t NumLinesForward = 0;
592 size_t Best = StringRef::npos;
593 double BestQuality = 0;
594
595 // Use an arbitrary 4k limit on how far we will search.
596 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
597 if (Buffer[i] == '\n')
598 ++NumLinesForward;
599
600 // Patterns have leading whitespace stripped, so skip whitespace when
601 // looking for something which looks like a pattern.
602 if (Buffer[i] == ' ' || Buffer[i] == '\t')
603 continue;
604
605 // Compute the "quality" of this match as an arbitrary combination of the
606 // match distance and the number of lines skipped to get to this match.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000607 unsigned Distance = computeMatchDistance(Buffer.substr(i));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000608 double Quality = Distance + (NumLinesForward / 100.);
609
610 if (Quality < BestQuality || Best == StringRef::npos) {
611 Best = i;
612 BestQuality = Quality;
613 }
614 }
615
616 // Print the "possible intended match here" line if we found something
617 // reasonable and not equal to what we showed in the "scanning from here"
618 // line.
619 if (Best && Best != StringRef::npos && BestQuality < 50) {
Joel E. Denny2c007c82018-12-18 00:02:04 +0000620 SMRange MatchRange =
621 ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
622 getCheckTy(), Buffer, Best, 0, Diags);
623 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
624 "possible intended match here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000625
626 // FIXME: If we wanted to be really friendly we would show why the match
627 // failed, as it can be hard to spot simple one character differences.
628 }
629}
630
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000631llvm::Optional<StringRef>
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000632FileCheckPatternContext::getPatternVarValue(StringRef VarName) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000633 auto VarIter = GlobalVariableTable.find(VarName);
634 if (VarIter == GlobalVariableTable.end())
635 return llvm::None;
636
637 return VarIter->second;
638}
639
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000640FileCheckNumExpr *
641FileCheckPatternContext::makeNumExpr(binop_eval_t EvalBinop,
642 FileCheckNumericVariable *OperandLeft,
643 uint64_t OperandRight) {
644 NumExprs.push_back(llvm::make_unique<FileCheckNumExpr>(EvalBinop, OperandLeft,
645 OperandRight));
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000646 return NumExprs.back().get();
647}
648
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000649FileCheckNumericVariable *
650FileCheckPatternContext::makeNumericVariable(StringRef Name, uint64_t Value) {
651 NumericVariables.push_back(
652 llvm::make_unique<FileCheckNumericVariable>(Name, Value));
653 return NumericVariables.back().get();
654}
655
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000656size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
657 // Offset keeps track of the current offset within the input Str
658 size_t Offset = 0;
659 // [...] Nesting depth
660 size_t BracketDepth = 0;
661
662 while (!Str.empty()) {
663 if (Str.startswith("]]") && BracketDepth == 0)
664 return Offset;
665 if (Str[0] == '\\') {
666 // Backslash escapes the next char within regexes, so skip them both.
667 Str = Str.substr(2);
668 Offset += 2;
669 } else {
670 switch (Str[0]) {
671 default:
672 break;
673 case '[':
674 BracketDepth++;
675 break;
676 case ']':
677 if (BracketDepth == 0) {
678 SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
679 SourceMgr::DK_Error,
680 "missing closing \"]\" for regex variable");
681 exit(1);
682 }
683 BracketDepth--;
684 break;
685 }
686 Str = Str.substr(1);
687 Offset++;
688 }
689 }
690
691 return StringRef::npos;
692}
693
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000694StringRef
695llvm::FileCheck::CanonicalizeFile(MemoryBuffer &MB,
696 SmallVectorImpl<char> &OutputBuffer) {
697 OutputBuffer.reserve(MB.getBufferSize());
698
699 for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
700 Ptr != End; ++Ptr) {
701 // Eliminate trailing dosish \r.
702 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
703 continue;
704 }
705
706 // If current char is not a horizontal whitespace or if horizontal
707 // whitespace canonicalization is disabled, dump it to output as is.
708 if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
709 OutputBuffer.push_back(*Ptr);
710 continue;
711 }
712
713 // Otherwise, add one space and advance over neighboring space.
714 OutputBuffer.push_back(' ');
715 while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
716 ++Ptr;
717 }
718
719 // Add a null byte and then return all but that byte.
720 OutputBuffer.push_back('\0');
721 return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
722}
723
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000724FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
725 const Check::FileCheckType &CheckTy,
726 SMLoc CheckLoc, MatchType MatchTy,
727 SMRange InputRange)
728 : CheckTy(CheckTy), MatchTy(MatchTy) {
729 auto Start = SM.getLineAndColumn(InputRange.Start);
730 auto End = SM.getLineAndColumn(InputRange.End);
731 InputStartLine = Start.first;
732 InputStartCol = Start.second;
733 InputEndLine = End.first;
734 InputEndCol = End.second;
735 Start = SM.getLineAndColumn(CheckLoc);
736 CheckLine = Start.first;
737 CheckCol = Start.second;
738}
739
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000740static bool IsPartOfWord(char c) {
741 return (isalnum(c) || c == '-' || c == '_');
742}
743
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000744Check::FileCheckType &Check::FileCheckType::setCount(int C) {
Fedor Sergeev8477a3e2018-11-13 01:09:53 +0000745 assert(Count > 0 && "zero and negative counts are not supported");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000746 assert((C == 1 || Kind == CheckPlain) &&
747 "count supported only for plain CHECK directives");
748 Count = C;
749 return *this;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000750}
751
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000752std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
753 switch (Kind) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000754 case Check::CheckNone:
755 return "invalid";
756 case Check::CheckPlain:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000757 if (Count > 1)
758 return Prefix.str() + "-COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000759 return Prefix;
760 case Check::CheckNext:
761 return Prefix.str() + "-NEXT";
762 case Check::CheckSame:
763 return Prefix.str() + "-SAME";
764 case Check::CheckNot:
765 return Prefix.str() + "-NOT";
766 case Check::CheckDAG:
767 return Prefix.str() + "-DAG";
768 case Check::CheckLabel:
769 return Prefix.str() + "-LABEL";
770 case Check::CheckEmpty:
771 return Prefix.str() + "-EMPTY";
772 case Check::CheckEOF:
773 return "implicit EOF";
774 case Check::CheckBadNot:
775 return "bad NOT";
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000776 case Check::CheckBadCount:
777 return "bad COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000778 }
779 llvm_unreachable("unknown FileCheckType");
780}
781
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000782static std::pair<Check::FileCheckType, StringRef>
783FindCheckType(StringRef Buffer, StringRef Prefix) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000784 if (Buffer.size() <= Prefix.size())
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000785 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000786
787 char NextChar = Buffer[Prefix.size()];
788
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000789 StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000790 // Verify that the : is present after the prefix.
791 if (NextChar == ':')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000792 return {Check::CheckPlain, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000793
794 if (NextChar != '-')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000795 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000796
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000797 if (Rest.consume_front("COUNT-")) {
798 int64_t Count;
799 if (Rest.consumeInteger(10, Count))
800 // Error happened in parsing integer.
801 return {Check::CheckBadCount, Rest};
802 if (Count <= 0 || Count > INT32_MAX)
803 return {Check::CheckBadCount, Rest};
804 if (!Rest.consume_front(":"))
805 return {Check::CheckBadCount, Rest};
806 return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
807 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000808
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000809 if (Rest.consume_front("NEXT:"))
810 return {Check::CheckNext, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000811
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000812 if (Rest.consume_front("SAME:"))
813 return {Check::CheckSame, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000814
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000815 if (Rest.consume_front("NOT:"))
816 return {Check::CheckNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000817
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000818 if (Rest.consume_front("DAG:"))
819 return {Check::CheckDAG, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000820
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000821 if (Rest.consume_front("LABEL:"))
822 return {Check::CheckLabel, Rest};
823
824 if (Rest.consume_front("EMPTY:"))
825 return {Check::CheckEmpty, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000826
827 // You can't combine -NOT with another suffix.
828 if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
829 Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
830 Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
831 Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000832 return {Check::CheckBadNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000833
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000834 return {Check::CheckNone, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000835}
836
837// From the given position, find the next character after the word.
838static size_t SkipWord(StringRef Str, size_t Loc) {
839 while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
840 ++Loc;
841 return Loc;
842}
843
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +0000844/// Searches the buffer for the first prefix in the prefix regular expression.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000845///
846/// This searches the buffer using the provided regular expression, however it
847/// enforces constraints beyond that:
848/// 1) The found prefix must not be a suffix of something that looks like
849/// a valid prefix.
850/// 2) The found prefix must be followed by a valid check type suffix using \c
851/// FindCheckType above.
852///
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +0000853/// \returns a pair of StringRefs into the Buffer, which combines:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000854/// - the first match of the regular expression to satisfy these two is
855/// returned,
856/// otherwise an empty StringRef is returned to indicate failure.
857/// - buffer rewound to the location right after parsed suffix, for parsing
858/// to continue from
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000859///
860/// If this routine returns a valid prefix, it will also shrink \p Buffer to
861/// start at the beginning of the returned prefix, increment \p LineNumber for
862/// each new line consumed from \p Buffer, and set \p CheckTy to the type of
863/// check found by examining the suffix.
864///
865/// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
866/// is unspecified.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000867static std::pair<StringRef, StringRef>
868FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer,
869 unsigned &LineNumber, Check::FileCheckType &CheckTy) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000870 SmallVector<StringRef, 2> Matches;
871
872 while (!Buffer.empty()) {
873 // Find the first (longest) match using the RE.
874 if (!PrefixRE.match(Buffer, &Matches))
875 // No match at all, bail.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000876 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000877
878 StringRef Prefix = Matches[0];
879 Matches.clear();
880
881 assert(Prefix.data() >= Buffer.data() &&
882 Prefix.data() < Buffer.data() + Buffer.size() &&
883 "Prefix doesn't start inside of buffer!");
884 size_t Loc = Prefix.data() - Buffer.data();
885 StringRef Skipped = Buffer.substr(0, Loc);
886 Buffer = Buffer.drop_front(Loc);
887 LineNumber += Skipped.count('\n');
888
889 // Check that the matched prefix isn't a suffix of some other check-like
890 // word.
891 // FIXME: This is a very ad-hoc check. it would be better handled in some
892 // other way. Among other things it seems hard to distinguish between
893 // intentional and unintentional uses of this feature.
894 if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
895 // Now extract the type.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000896 StringRef AfterSuffix;
897 std::tie(CheckTy, AfterSuffix) = FindCheckType(Buffer, Prefix);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000898
899 // If we've found a valid check type for this prefix, we're done.
900 if (CheckTy != Check::CheckNone)
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000901 return {Prefix, AfterSuffix};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000902 }
903
904 // If we didn't successfully find a prefix, we need to skip this invalid
905 // prefix and continue scanning. We directly skip the prefix that was
906 // matched and any additional parts of that check-like word.
907 Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
908 }
909
910 // We ran out of buffer while skipping partial matches so give up.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000911 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000912}
913
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000914bool llvm::FileCheck::ReadCheckFile(
915 SourceMgr &SM, StringRef Buffer, Regex &PrefixRE,
916 std::vector<FileCheckString> &CheckStrings) {
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000917 if (PatternContext.defineCmdlineVariables(Req.GlobalDefines, SM))
918 return true;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000919
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000920 std::vector<FileCheckPattern> ImplicitNegativeChecks;
921 for (const auto &PatternString : Req.ImplicitCheckNot) {
922 // Create a buffer with fake command line content in order to display the
923 // command line option responsible for the specific implicit CHECK-NOT.
924 std::string Prefix = "-implicit-check-not='";
925 std::string Suffix = "'";
926 std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
927 Prefix + PatternString + Suffix, "command line");
928
929 StringRef PatternInBuffer =
930 CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
931 SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
932
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000933 ImplicitNegativeChecks.push_back(
934 FileCheckPattern(Check::CheckNot, &PatternContext));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000935 ImplicitNegativeChecks.back().ParsePattern(PatternInBuffer,
936 "IMPLICIT-CHECK", SM, 0, Req);
937 }
938
939 std::vector<FileCheckPattern> DagNotMatches = ImplicitNegativeChecks;
940
941 // LineNumber keeps track of the line on which CheckPrefix instances are
942 // found.
943 unsigned LineNumber = 1;
944
945 while (1) {
946 Check::FileCheckType CheckTy;
947
948 // See if a prefix occurs in the memory buffer.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000949 StringRef UsedPrefix;
950 StringRef AfterSuffix;
951 std::tie(UsedPrefix, AfterSuffix) =
952 FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, CheckTy);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000953 if (UsedPrefix.empty())
954 break;
955 assert(UsedPrefix.data() == Buffer.data() &&
956 "Failed to move Buffer's start forward, or pointed prefix outside "
957 "of the buffer!");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000958 assert(AfterSuffix.data() >= Buffer.data() &&
959 AfterSuffix.data() < Buffer.data() + Buffer.size() &&
960 "Parsing after suffix doesn't start inside of buffer!");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000961
962 // Location to use for error messages.
963 const char *UsedPrefixStart = UsedPrefix.data();
964
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000965 // Skip the buffer to the end of parsed suffix (or just prefix, if no good
966 // suffix was processed).
967 Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
968 : AfterSuffix;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000969
970 // Complain about useful-looking but unsupported suffixes.
971 if (CheckTy == Check::CheckBadNot) {
972 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
973 "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
974 return true;
975 }
976
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000977 // Complain about invalid count specification.
978 if (CheckTy == Check::CheckBadCount) {
979 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
980 "invalid count in -COUNT specification on prefix '" +
981 UsedPrefix + "'");
982 return true;
983 }
984
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000985 // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
986 // leading whitespace.
987 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
988 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
989
990 // Scan ahead to the end of line.
991 size_t EOL = Buffer.find_first_of("\n\r");
992
993 // Remember the location of the start of the pattern, for diagnostics.
994 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
995
996 // Parse the pattern.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000997 FileCheckPattern P(CheckTy, &PatternContext);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000998 if (P.ParsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, LineNumber, Req))
999 return true;
1000
1001 // Verify that CHECK-LABEL lines do not define or use variables
1002 if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
1003 SM.PrintMessage(
1004 SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
1005 "found '" + UsedPrefix + "-LABEL:'"
1006 " with variable definition or use");
1007 return true;
1008 }
1009
1010 Buffer = Buffer.substr(EOL);
1011
1012 // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
1013 if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
1014 CheckTy == Check::CheckEmpty) &&
1015 CheckStrings.empty()) {
1016 StringRef Type = CheckTy == Check::CheckNext
1017 ? "NEXT"
1018 : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
1019 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
1020 SourceMgr::DK_Error,
1021 "found '" + UsedPrefix + "-" + Type +
1022 "' without previous '" + UsedPrefix + ": line");
1023 return true;
1024 }
1025
1026 // Handle CHECK-DAG/-NOT.
1027 if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
1028 DagNotMatches.push_back(P);
1029 continue;
1030 }
1031
1032 // Okay, add the string we captured to the output vector and move on.
1033 CheckStrings.emplace_back(P, UsedPrefix, PatternLoc);
1034 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1035 DagNotMatches = ImplicitNegativeChecks;
1036 }
1037
1038 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
1039 // prefix as a filler for the error message.
1040 if (!DagNotMatches.empty()) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001041 CheckStrings.emplace_back(
1042 FileCheckPattern(Check::CheckEOF, &PatternContext),
1043 *Req.CheckPrefixes.begin(), SMLoc::getFromPointer(Buffer.data()));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001044 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1045 }
1046
1047 if (CheckStrings.empty()) {
1048 errs() << "error: no check strings found with prefix"
1049 << (Req.CheckPrefixes.size() > 1 ? "es " : " ");
1050 auto I = Req.CheckPrefixes.begin();
1051 auto E = Req.CheckPrefixes.end();
1052 if (I != E) {
1053 errs() << "\'" << *I << ":'";
1054 ++I;
1055 }
1056 for (; I != E; ++I)
1057 errs() << ", \'" << *I << ":'";
1058
1059 errs() << '\n';
1060 return true;
1061 }
1062
1063 return false;
1064}
1065
1066static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
1067 StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001068 int MatchedCount, StringRef Buffer, size_t MatchPos,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001069 size_t MatchLen, const FileCheckRequest &Req,
1070 std::vector<FileCheckDiag> *Diags) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001071 bool PrintDiag = true;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001072 if (ExpectedMatch) {
1073 if (!Req.Verbose)
1074 return;
1075 if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
1076 return;
Joel E. Denny352695c2019-01-22 21:41:42 +00001077 // Due to their verbosity, we don't print verbose diagnostics here if we're
1078 // gathering them for a different rendering, but we always print other
1079 // diagnostics.
1080 PrintDiag = !Diags;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001081 }
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001082 SMRange MatchRange = ProcessMatchResult(
Joel E. Dennye2afb612018-12-18 00:03:51 +00001083 ExpectedMatch ? FileCheckDiag::MatchFoundAndExpected
1084 : FileCheckDiag::MatchFoundButExcluded,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001085 SM, Loc, Pat.getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
Joel E. Denny352695c2019-01-22 21:41:42 +00001086 if (!PrintDiag)
1087 return;
1088
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001089 std::string Message = formatv("{0}: {1} string found in input",
1090 Pat.getCheckTy().getDescription(Prefix),
1091 (ExpectedMatch ? "expected" : "excluded"))
1092 .str();
1093 if (Pat.getCount() > 1)
1094 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
1095
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001096 SM.PrintMessage(
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001097 Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001098 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
1099 {MatchRange});
Thomas Preud'homme288ed912019-05-02 00:04:38 +00001100 Pat.printSubstitutions(SM, Buffer, MatchRange);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001101}
1102
1103static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001104 const FileCheckString &CheckStr, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001105 StringRef Buffer, size_t MatchPos, size_t MatchLen,
1106 FileCheckRequest &Req,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001107 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001108 PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001109 MatchedCount, Buffer, MatchPos, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001110}
1111
1112static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001113 StringRef Prefix, SMLoc Loc,
1114 const FileCheckPattern &Pat, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001115 StringRef Buffer, bool VerboseVerbose,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001116 std::vector<FileCheckDiag> *Diags) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001117 bool PrintDiag = true;
1118 if (!ExpectedMatch) {
1119 if (!VerboseVerbose)
1120 return;
1121 // Due to their verbosity, we don't print verbose diagnostics here if we're
1122 // gathering them for a different rendering, but we always print other
1123 // diagnostics.
1124 PrintDiag = !Diags;
1125 }
1126
1127 // If the current position is at the end of a line, advance to the start of
1128 // the next line.
1129 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
1130 SMRange SearchRange = ProcessMatchResult(
1131 ExpectedMatch ? FileCheckDiag::MatchNoneButExpected
1132 : FileCheckDiag::MatchNoneAndExcluded,
1133 SM, Loc, Pat.getCheckTy(), Buffer, 0, Buffer.size(), Diags);
1134 if (!PrintDiag)
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001135 return;
1136
Joel E. Denny352695c2019-01-22 21:41:42 +00001137 // Print "not found" diagnostic.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001138 std::string Message = formatv("{0}: {1} string not found in input",
1139 Pat.getCheckTy().getDescription(Prefix),
1140 (ExpectedMatch ? "expected" : "excluded"))
1141 .str();
1142 if (Pat.getCount() > 1)
1143 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001144 SM.PrintMessage(
1145 Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001146
Joel E. Denny352695c2019-01-22 21:41:42 +00001147 // Print the "scanning from here" line.
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001148 SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001149
1150 // Allow the pattern to print additional information if desired.
Thomas Preud'homme288ed912019-05-02 00:04:38 +00001151 Pat.printSubstitutions(SM, Buffer);
Joel E. Denny96f0e842018-12-18 00:03:36 +00001152
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001153 if (ExpectedMatch)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001154 Pat.printFuzzyMatch(SM, Buffer, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001155}
1156
1157static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001158 const FileCheckString &CheckStr, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001159 StringRef Buffer, bool VerboseVerbose,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001160 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001161 PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001162 MatchedCount, Buffer, VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001163}
1164
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +00001165/// Counts the number of newlines in the specified range.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001166static unsigned CountNumNewlinesBetween(StringRef Range,
1167 const char *&FirstNewLine) {
1168 unsigned NumNewLines = 0;
1169 while (1) {
1170 // Scan for newline.
1171 Range = Range.substr(Range.find_first_of("\n\r"));
1172 if (Range.empty())
1173 return NumNewLines;
1174
1175 ++NumNewLines;
1176
1177 // Handle \n\r and \r\n as a single newline.
1178 if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
1179 (Range[0] != Range[1]))
1180 Range = Range.substr(1);
1181 Range = Range.substr(1);
1182
1183 if (NumNewLines == 1)
1184 FirstNewLine = Range.begin();
1185 }
1186}
1187
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001188size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001189 bool IsLabelScanMode, size_t &MatchLen,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001190 FileCheckRequest &Req,
1191 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001192 size_t LastPos = 0;
1193 std::vector<const FileCheckPattern *> NotStrings;
1194
1195 // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
1196 // bounds; we have not processed variable definitions within the bounded block
1197 // yet so cannot handle any final CHECK-DAG yet; this is handled when going
1198 // over the block again (including the last CHECK-LABEL) in normal mode.
1199 if (!IsLabelScanMode) {
1200 // Match "dag strings" (with mixed "not strings" if any).
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001201 LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001202 if (LastPos == StringRef::npos)
1203 return StringRef::npos;
1204 }
1205
1206 // Match itself from the last position after matching CHECK-DAG.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001207 size_t LastMatchEnd = LastPos;
1208 size_t FirstMatchPos = 0;
1209 // Go match the pattern Count times. Majority of patterns only match with
1210 // count 1 though.
1211 assert(Pat.getCount() != 0 && "pattern count can not be zero");
1212 for (int i = 1; i <= Pat.getCount(); i++) {
1213 StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
1214 size_t CurrentMatchLen;
1215 // get a match at current start point
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001216 size_t MatchPos = Pat.match(MatchBuffer, CurrentMatchLen);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001217 if (i == 1)
1218 FirstMatchPos = LastPos + MatchPos;
1219
1220 // report
1221 if (MatchPos == StringRef::npos) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001222 PrintNoMatch(true, SM, *this, i, MatchBuffer, Req.VerboseVerbose, Diags);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001223 return StringRef::npos;
1224 }
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001225 PrintMatch(true, SM, *this, i, MatchBuffer, MatchPos, CurrentMatchLen, Req,
1226 Diags);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001227
1228 // move start point after the match
1229 LastMatchEnd += MatchPos + CurrentMatchLen;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001230 }
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001231 // Full match len counts from first match pos.
1232 MatchLen = LastMatchEnd - FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001233
1234 // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1235 // or CHECK-NOT
1236 if (!IsLabelScanMode) {
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001237 size_t MatchPos = FirstMatchPos - LastPos;
1238 StringRef MatchBuffer = Buffer.substr(LastPos);
1239 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001240
1241 // If this check is a "CHECK-NEXT", verify that the previous match was on
1242 // the previous line (i.e. that there is one newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001243 if (CheckNext(SM, SkippedRegion)) {
Joel E. Dennye2afb612018-12-18 00:03:51 +00001244 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001245 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001246 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001247 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001248 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001249
1250 // If this check is a "CHECK-SAME", verify that the previous match was on
1251 // the same line (i.e. that there is no newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001252 if (CheckSame(SM, SkippedRegion)) {
Joel E. Dennye2afb612018-12-18 00:03:51 +00001253 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001254 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001255 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001256 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001257 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001258
1259 // If this match had "not strings", verify that they don't exist in the
1260 // skipped region.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001261 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001262 return StringRef::npos;
1263 }
1264
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001265 return FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001266}
1267
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001268bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1269 if (Pat.getCheckTy() != Check::CheckNext &&
1270 Pat.getCheckTy() != Check::CheckEmpty)
1271 return false;
1272
1273 Twine CheckName =
1274 Prefix +
1275 Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
1276
1277 // Count the number of newlines between the previous match and this one.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001278 const char *FirstNewLine = nullptr;
1279 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1280
1281 if (NumNewLines == 0) {
1282 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1283 CheckName + ": is on the same line as previous match");
1284 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1285 "'next' match was here");
1286 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1287 "previous match ended here");
1288 return true;
1289 }
1290
1291 if (NumNewLines != 1) {
1292 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1293 CheckName +
1294 ": is not on the line after the previous match");
1295 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1296 "'next' match was here");
1297 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1298 "previous match ended here");
1299 SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
1300 "non-matching line after previous match is here");
1301 return true;
1302 }
1303
1304 return false;
1305}
1306
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001307bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
1308 if (Pat.getCheckTy() != Check::CheckSame)
1309 return false;
1310
1311 // Count the number of newlines between the previous match and this one.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001312 const char *FirstNewLine = nullptr;
1313 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1314
1315 if (NumNewLines != 0) {
1316 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1317 Prefix +
1318 "-SAME: is not on the same line as the previous match");
1319 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1320 "'next' match was here");
1321 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1322 "previous match ended here");
1323 return true;
1324 }
1325
1326 return false;
1327}
1328
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001329bool FileCheckString::CheckNot(
1330 const SourceMgr &SM, StringRef Buffer,
1331 const std::vector<const FileCheckPattern *> &NotStrings,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001332 const FileCheckRequest &Req, std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001333 for (const FileCheckPattern *Pat : NotStrings) {
1334 assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1335
1336 size_t MatchLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001337 size_t Pos = Pat->match(Buffer, MatchLen);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001338
1339 if (Pos == StringRef::npos) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001340 PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001341 Req.VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001342 continue;
1343 }
1344
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001345 PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, Pos, MatchLen,
1346 Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001347
1348 return true;
1349 }
1350
1351 return false;
1352}
1353
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001354size_t
1355FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1356 std::vector<const FileCheckPattern *> &NotStrings,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001357 const FileCheckRequest &Req,
1358 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001359 if (DagNotStrings.empty())
1360 return 0;
1361
1362 // The start of the search range.
1363 size_t StartPos = 0;
1364
1365 struct MatchRange {
1366 size_t Pos;
1367 size_t End;
1368 };
1369 // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
1370 // ranges are erased from this list once they are no longer in the search
1371 // range.
1372 std::list<MatchRange> MatchRanges;
1373
1374 // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
1375 // group, so we don't use a range-based for loop here.
1376 for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
1377 PatItr != PatEnd; ++PatItr) {
1378 const FileCheckPattern &Pat = *PatItr;
1379 assert((Pat.getCheckTy() == Check::CheckDAG ||
1380 Pat.getCheckTy() == Check::CheckNot) &&
1381 "Invalid CHECK-DAG or CHECK-NOT!");
1382
1383 if (Pat.getCheckTy() == Check::CheckNot) {
1384 NotStrings.push_back(&Pat);
1385 continue;
1386 }
1387
1388 assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1389
1390 // CHECK-DAG always matches from the start.
1391 size_t MatchLen = 0, MatchPos = StartPos;
1392
1393 // Search for a match that doesn't overlap a previous match in this
1394 // CHECK-DAG group.
1395 for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
1396 StringRef MatchBuffer = Buffer.substr(MatchPos);
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001397 size_t MatchPosBuf = Pat.match(MatchBuffer, MatchLen);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001398 // With a group of CHECK-DAGs, a single mismatching means the match on
1399 // that group of CHECK-DAGs fails immediately.
1400 if (MatchPosBuf == StringRef::npos) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001401 PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001402 Req.VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001403 return StringRef::npos;
1404 }
1405 // Re-calc it as the offset relative to the start of the original string.
1406 MatchPos += MatchPosBuf;
1407 if (Req.VerboseVerbose)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001408 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1409 MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001410 MatchRange M{MatchPos, MatchPos + MatchLen};
1411 if (Req.AllowDeprecatedDagOverlap) {
1412 // We don't need to track all matches in this mode, so we just maintain
1413 // one match range that encompasses the current CHECK-DAG group's
1414 // matches.
1415 if (MatchRanges.empty())
1416 MatchRanges.insert(MatchRanges.end(), M);
1417 else {
1418 auto Block = MatchRanges.begin();
1419 Block->Pos = std::min(Block->Pos, M.Pos);
1420 Block->End = std::max(Block->End, M.End);
1421 }
1422 break;
1423 }
1424 // Iterate previous matches until overlapping match or insertion point.
1425 bool Overlap = false;
1426 for (; MI != ME; ++MI) {
1427 if (M.Pos < MI->End) {
1428 // !Overlap => New match has no overlap and is before this old match.
1429 // Overlap => New match overlaps this old match.
1430 Overlap = MI->Pos < M.End;
1431 break;
1432 }
1433 }
1434 if (!Overlap) {
1435 // Insert non-overlapping match into list.
1436 MatchRanges.insert(MI, M);
1437 break;
1438 }
1439 if (Req.VerboseVerbose) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001440 // Due to their verbosity, we don't print verbose diagnostics here if
1441 // we're gathering them for a different rendering, but we always print
1442 // other diagnostics.
1443 if (!Diags) {
1444 SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
1445 SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
1446 SMRange OldRange(OldStart, OldEnd);
1447 SM.PrintMessage(OldStart, SourceMgr::DK_Note,
1448 "match discarded, overlaps earlier DAG match here",
1449 {OldRange});
1450 } else
Joel E. Dennye2afb612018-12-18 00:03:51 +00001451 Diags->rbegin()->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001452 }
1453 MatchPos = MI->End;
1454 }
1455 if (!Req.VerboseVerbose)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001456 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1457 MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001458
1459 // Handle the end of a CHECK-DAG group.
1460 if (std::next(PatItr) == PatEnd ||
1461 std::next(PatItr)->getCheckTy() == Check::CheckNot) {
1462 if (!NotStrings.empty()) {
1463 // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
1464 // CHECK-DAG, verify that there are no 'not' strings occurred in that
1465 // region.
1466 StringRef SkippedRegion =
1467 Buffer.slice(StartPos, MatchRanges.begin()->Pos);
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001468 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001469 return StringRef::npos;
1470 // Clear "not strings".
1471 NotStrings.clear();
1472 }
1473 // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
1474 // end of this CHECK-DAG group's match range.
1475 StartPos = MatchRanges.rbegin()->End;
1476 // Don't waste time checking for (impossible) overlaps before that.
1477 MatchRanges.clear();
1478 }
1479 }
1480
1481 return StartPos;
1482}
1483
1484// A check prefix must contain only alphanumeric, hyphens and underscores.
1485static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1486 Regex Validator("^[a-zA-Z0-9_-]*$");
1487 return Validator.match(CheckPrefix);
1488}
1489
1490bool llvm::FileCheck::ValidateCheckPrefixes() {
1491 StringSet<> PrefixSet;
1492
1493 for (StringRef Prefix : Req.CheckPrefixes) {
1494 // Reject empty prefixes.
1495 if (Prefix == "")
1496 return false;
1497
1498 if (!PrefixSet.insert(Prefix).second)
1499 return false;
1500
1501 if (!ValidateCheckPrefix(Prefix))
1502 return false;
1503 }
1504
1505 return true;
1506}
1507
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001508Regex llvm::FileCheck::buildCheckPrefixRegex() {
1509 // I don't think there's a way to specify an initial value for cl::list,
1510 // so if nothing was specified, add the default
1511 if (Req.CheckPrefixes.empty())
1512 Req.CheckPrefixes.push_back("CHECK");
1513
1514 // We already validated the contents of CheckPrefixes so just concatenate
1515 // them as alternatives.
1516 SmallString<32> PrefixRegexStr;
1517 for (StringRef Prefix : Req.CheckPrefixes) {
1518 if (Prefix != Req.CheckPrefixes.front())
1519 PrefixRegexStr.push_back('|');
1520
1521 PrefixRegexStr.append(Prefix);
1522 }
1523
1524 return Regex(PrefixRegexStr);
1525}
1526
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001527bool FileCheckPatternContext::defineCmdlineVariables(
1528 std::vector<std::string> &CmdlineDefines, SourceMgr &SM) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001529 assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001530 "Overriding defined variable with command-line variable definitions");
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001531
1532 if (CmdlineDefines.empty())
1533 return false;
1534
1535 // Create a string representing the vector of command-line definitions. Each
1536 // definition is on its own line and prefixed with a definition number to
1537 // clarify which definition a given diagnostic corresponds to.
1538 unsigned I = 0;
1539 bool ErrorFound = false;
1540 std::string CmdlineDefsDiag;
1541 StringRef Prefix1 = "Global define #";
1542 StringRef Prefix2 = ": ";
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001543 for (StringRef CmdlineDef : CmdlineDefines)
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001544 CmdlineDefsDiag +=
1545 (Prefix1 + Twine(++I) + Prefix2 + CmdlineDef + "\n").str();
1546
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001547 // Create a buffer with fake command line content in order to display
1548 // parsing diagnostic with location information and point to the
1549 // global definition with invalid syntax.
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001550 std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
1551 MemoryBuffer::getMemBufferCopy(CmdlineDefsDiag, "Global defines");
1552 StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
1553 SM.AddNewSourceBuffer(std::move(CmdLineDefsDiagBuffer), SMLoc());
1554
1555 SmallVector<StringRef, 4> CmdlineDefsDiagVec;
1556 CmdlineDefsDiagRef.split(CmdlineDefsDiagVec, '\n', -1 /*MaxSplit*/,
1557 false /*KeepEmpty*/);
1558 for (StringRef CmdlineDefDiag : CmdlineDefsDiagVec) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001559 unsigned DefStart = CmdlineDefDiag.find(Prefix2) + Prefix2.size();
1560 StringRef CmdlineDef = CmdlineDefDiag.substr(DefStart);
1561 if (CmdlineDef.find('=') == StringRef::npos) {
1562 SM.PrintMessage(SMLoc::getFromPointer(CmdlineDef.data()),
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001563 SourceMgr::DK_Error,
1564 "Missing equal sign in global definition");
1565 ErrorFound = true;
1566 continue;
1567 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001568
1569 // Numeric variable definition.
1570 if (CmdlineDef[0] == '#') {
1571 bool IsPseudo;
1572 unsigned TrailIdx;
1573 size_t EqIdx = CmdlineDef.find('=');
1574 StringRef CmdlineName = CmdlineDef.substr(1, EqIdx - 1);
1575 if (FileCheckPattern::parseVariable(CmdlineName, IsPseudo, TrailIdx) ||
1576 IsPseudo || TrailIdx != CmdlineName.size() || CmdlineName.empty()) {
1577 SM.PrintMessage(SMLoc::getFromPointer(CmdlineName.data()),
1578 SourceMgr::DK_Error,
1579 "invalid name in numeric variable definition '" +
1580 CmdlineName + "'");
1581 ErrorFound = true;
1582 continue;
1583 }
1584
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001585 // Detect collisions between string and numeric variables when the latter
1586 // is created later than the former.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001587 if (DefinedVariableTable.find(CmdlineName) !=
1588 DefinedVariableTable.end()) {
1589 SM.PrintMessage(
1590 SMLoc::getFromPointer(CmdlineName.data()), SourceMgr::DK_Error,
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001591 "string variable with name '" + CmdlineName + "' already exists");
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001592 ErrorFound = true;
1593 continue;
1594 }
1595
1596 StringRef CmdlineVal = CmdlineDef.substr(EqIdx + 1);
1597 uint64_t Val;
1598 if (CmdlineVal.getAsInteger(10, Val)) {
1599 SM.PrintMessage(SMLoc::getFromPointer(CmdlineVal.data()),
1600 SourceMgr::DK_Error,
1601 "invalid value in numeric variable definition '" +
1602 CmdlineVal + "'");
1603 ErrorFound = true;
1604 continue;
1605 }
1606 auto DefinedNumericVariable = makeNumericVariable(CmdlineName, Val);
1607
1608 // Record this variable definition.
1609 GlobalNumericVariableTable[CmdlineName] = DefinedNumericVariable;
1610 } else {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001611 // String variable definition.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001612 std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.split('=');
1613 StringRef Name = CmdlineNameVal.first;
1614 bool IsPseudo;
1615 unsigned TrailIdx;
1616 if (FileCheckPattern::parseVariable(Name, IsPseudo, TrailIdx) ||
1617 IsPseudo || TrailIdx != Name.size() || Name.empty()) {
1618 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001619 "invalid name in string variable definition '" + Name +
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001620 "'");
1621 ErrorFound = true;
1622 continue;
1623 }
1624
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001625 // Detect collisions between string and numeric variables when the former
1626 // is created later than the latter.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001627 if (GlobalNumericVariableTable.find(Name) !=
1628 GlobalNumericVariableTable.end()) {
1629 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
1630 "numeric variable with name '" + Name +
1631 "' already exists");
1632 ErrorFound = true;
1633 continue;
1634 }
1635 GlobalVariableTable.insert(CmdlineNameVal);
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001636 // Mark the string variable as defined to detect collisions between
1637 // string and numeric variables in DefineCmdlineVariables when the latter
1638 // is created later than the former. We cannot reuse GlobalVariableTable
1639 // for that by populating it with an empty string since we would then
1640 // lose the ability to detect the use of an undefined variable in
1641 // match().
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001642 DefinedVariableTable[Name] = true;
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001643 }
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001644 }
1645
1646 return ErrorFound;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001647}
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001648
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001649void FileCheckPatternContext::clearLocalVars() {
1650 SmallVector<StringRef, 16> LocalPatternVars, LocalNumericVars;
1651 for (const StringMapEntry<StringRef> &Var : GlobalVariableTable)
1652 if (Var.first()[0] != '$')
1653 LocalPatternVars.push_back(Var.first());
1654
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001655 // Numeric substitution reads the value of a variable directly, not via
1656 // GlobalNumericVariableTable. Therefore, we clear local variables by
1657 // clearing their value which will lead to a numeric substitution failure. We
1658 // also mark the variable for removal from GlobalNumericVariableTable since
1659 // this is what defineCmdlineVariables checks to decide that no global
1660 // variable has been defined.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001661 for (const auto &Var : GlobalNumericVariableTable)
1662 if (Var.first()[0] != '$') {
1663 Var.getValue()->clearValue();
1664 LocalNumericVars.push_back(Var.first());
1665 }
1666
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001667 for (const auto &Var : LocalPatternVars)
1668 GlobalVariableTable.erase(Var);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001669 for (const auto &Var : LocalNumericVars)
1670 GlobalNumericVariableTable.erase(Var);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001671}
1672
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001673bool llvm::FileCheck::CheckInput(SourceMgr &SM, StringRef Buffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001674 ArrayRef<FileCheckString> CheckStrings,
1675 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001676 bool ChecksFailed = false;
1677
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001678 unsigned i = 0, j = 0, e = CheckStrings.size();
1679 while (true) {
1680 StringRef CheckRegion;
1681 if (j == e) {
1682 CheckRegion = Buffer;
1683 } else {
1684 const FileCheckString &CheckLabelStr = CheckStrings[j];
1685 if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
1686 ++j;
1687 continue;
1688 }
1689
1690 // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1691 size_t MatchLabelLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001692 size_t MatchLabelPos =
1693 CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001694 if (MatchLabelPos == StringRef::npos)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001695 // Immediately bail if CHECK-LABEL fails, nothing else we can do.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001696 return false;
1697
1698 CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1699 Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1700 ++j;
1701 }
1702
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001703 // Do not clear the first region as it's the one before the first
1704 // CHECK-LABEL and it would clear variables defined on the command-line
1705 // before they get used.
1706 if (i != 0 && Req.EnableVarScope)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001707 PatternContext.clearLocalVars();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001708
1709 for (; i != j; ++i) {
1710 const FileCheckString &CheckStr = CheckStrings[i];
1711
1712 // Check each string within the scanned region, including a second check
1713 // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1714 size_t MatchLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001715 size_t MatchPos =
1716 CheckStr.Check(SM, CheckRegion, false, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001717
1718 if (MatchPos == StringRef::npos) {
1719 ChecksFailed = true;
1720 i = j;
1721 break;
1722 }
1723
1724 CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1725 }
1726
1727 if (j == e)
1728 break;
1729 }
1730
1731 // Success if no checks failed.
1732 return !ChecksFailed;
1733}