blob: effb643b9ddcd0889c1c60e6072876a28b76d5b0 [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'homme288ed912019-05-02 00:04:38 +000055llvm::Optional<std::string> FileCheckPatternSubstitution::getResult() const {
56 if (IsNumExpr) {
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
70StringRef FileCheckPatternSubstitution::getUndefVarName() const {
Thomas Preud'homme288ed912019-05-02 00:04:38 +000071 if (IsNumExpr)
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'homme7b4ecdd2019-05-14 11:58:30 +0000132FileCheckPattern::parseNumericExpression(StringRef Name, bool IsPseudo,
133 StringRef Trailer,
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000134 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'homme288ed912019-05-02 00:04:38 +0000291 // Pattern and numeric expression matches. Pattern expressions come in two
292 // forms: [[foo:.*]] and [[foo]]. The former matches .* (or some other
293 // regex) and assigns it to the FileCheck variable 'foo'. The latter
294 // substitutes foo's value. Numeric expressions start with a '#' sign after
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000295 // the double brackets and only have the substitution form. Both pattern
296 // and numeric variables must satisfy the regular expression
297 // "[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);
305 bool IsNumExpr = MatchStr.consume_front("#");
306 const char *RefTypeStr =
307 IsNumExpr ? "numeric expression" : "pattern variable";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000308
309 if (End == StringRef::npos) {
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000310 SM.PrintMessage(
311 SMLoc::getFromPointer(PatternStr.data()), SourceMgr::DK_Error,
312 Twine("Invalid ") + RefTypeStr + " reference, no ]] found");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000313 return true;
314 }
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000315 // Strip the subtitution we are parsing. End points to the start of the
316 // "]]" closing the expression so account for it in computing the index
317 // of the first unparsed character.
318 PatternStr = UnparsedPatternStr.substr(End + 2);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000319
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000320 size_t VarEndIdx = MatchStr.find(":");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000321 if (IsNumExpr)
322 MatchStr = MatchStr.ltrim(SpaceChars);
323 else {
324 size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
325 if (SpacePos != StringRef::npos) {
326 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
327 SourceMgr::DK_Error, "unexpected whitespace");
328 return true;
329 }
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000330 }
331
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000332 // Get the regex name (e.g. "foo") and verify it is well formed.
333 bool IsPseudo;
334 unsigned TrailIdx;
335 if (parseVariable(MatchStr, IsPseudo, TrailIdx)) {
336 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data()),
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000337 SourceMgr::DK_Error, "invalid variable name");
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000338 return true;
339 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000340
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000341 size_t SubstInsertIdx = RegExStr.size();
342 FileCheckNumExpr *NumExpr;
343
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000344 StringRef Name = MatchStr.substr(0, TrailIdx);
345 StringRef Trailer = MatchStr.substr(TrailIdx);
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000346 bool IsVarDef = (VarEndIdx != StringRef::npos);
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000347
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000348 if (IsVarDef) {
349 if (IsPseudo || !Trailer.consume_front(":")) {
350 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data()),
351 SourceMgr::DK_Error,
352 "invalid name in pattern variable definition");
353 return true;
354 }
355
356 // Detect collisions between pattern and numeric variables when the
357 // former is created later than the latter.
358 if (Context->GlobalNumericVariableTable.find(Name) !=
359 Context->GlobalNumericVariableTable.end()) {
360 SM.PrintMessage(
361 SMLoc::getFromPointer(MatchStr.data()), SourceMgr::DK_Error,
362 "numeric variable with name '" + Name + "' already exists");
363 return true;
364 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000365 }
366
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000367 if (IsNumExpr || (!IsVarDef && IsPseudo)) {
368 NumExpr = parseNumericExpression(Name, IsPseudo, Trailer, SM);
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000369 if (NumExpr == nullptr)
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000370 return true;
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000371 IsNumExpr = true;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000372 }
373
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000374 // Handle variable use: [[foo]] and [[#<foo expr>]].
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000375 if (!IsVarDef) {
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000376 // Handle use of pattern variables that were defined earlier on the
377 // same line by emitting a backreference.
378 if (!IsNumExpr && VariableDefs.find(Name) != VariableDefs.end()) {
379 unsigned CaptureParen = VariableDefs[Name];
380 if (CaptureParen < 1 || CaptureParen > 9) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000381 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
382 SourceMgr::DK_Error,
383 "Can't back-reference more than 9 variables");
384 return true;
385 }
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000386 AddBackrefToRegEx(CaptureParen);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000387 } else {
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000388 // Handle use of pattern variables ([[<var>]]) defined in previous
389 // CHECK pattern or use of a numeric expression.
390 FileCheckPatternSubstitution Substitution =
391 IsNumExpr ? FileCheckPatternSubstitution(Context, MatchStr,
392 NumExpr, SubstInsertIdx)
393 : FileCheckPatternSubstitution(Context, MatchStr,
394 SubstInsertIdx);
395 Substitutions.push_back(Substitution);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000396 }
397 continue;
398 }
399
400 // Handle [[foo:.*]].
401 VariableDefs[Name] = CurParen;
402 RegExStr += '(';
403 ++CurParen;
404
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000405 if (AddRegExToRegEx(Trailer, CurParen, SM))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000406 return true;
407
408 RegExStr += ')';
409 }
410
411 // Handle fixed string matches.
412 // Find the end, which is the start of the next regex.
413 size_t FixedMatchEnd = PatternStr.find("{{");
414 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
415 RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
416 PatternStr = PatternStr.substr(FixedMatchEnd);
417 }
418
419 if (MatchFullLinesHere) {
420 if (!Req.NoCanonicalizeWhiteSpace)
421 RegExStr += " *";
422 RegExStr += '$';
423 }
424
425 return false;
426}
427
428bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
429 Regex R(RS);
430 std::string Error;
431 if (!R.isValid(Error)) {
432 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
433 "invalid regex: " + Error);
434 return true;
435 }
436
437 RegExStr += RS.str();
438 CurParen += R.getNumMatches();
439 return false;
440}
441
442void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
443 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
444 std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
445 RegExStr += Backref;
446}
447
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000448size_t FileCheckPattern::match(StringRef Buffer, size_t &MatchLen) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000449 // If this is the EOF pattern, match it immediately.
450 if (CheckTy == Check::CheckEOF) {
451 MatchLen = 0;
452 return Buffer.size();
453 }
454
455 // If this is a fixed string pattern, just match it now.
456 if (!FixedStr.empty()) {
457 MatchLen = FixedStr.size();
458 return Buffer.find(FixedStr);
459 }
460
461 // Regex match.
462
463 // If there are variable uses, we need to create a temporary string with the
464 // actual value.
465 StringRef RegExToMatch = RegExStr;
466 std::string TmpStr;
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000467 if (!Substitutions.empty()) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000468 TmpStr = RegExStr;
469
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000470 size_t InsertOffset = 0;
471 // Substitute all pattern variables and numeric expressions whose value is
472 // known just now. Use of pattern variables defined on the same line are
473 // handled by back-references.
474 for (const auto &Substitution : Substitutions) {
475 // Substitute and check for failure (e.g. use of undefined variable).
476 llvm::Optional<std::string> Value = Substitution.getResult();
477 if (!Value)
478 return StringRef::npos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000479
480 // Plop it into the regex at the adjusted offset.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000481 TmpStr.insert(TmpStr.begin() + Substitution.getIndex() + InsertOffset,
482 Value->begin(), Value->end());
483 InsertOffset += Value->size();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000484 }
485
486 // Match the newly constructed regex.
487 RegExToMatch = TmpStr;
488 }
489
490 SmallVector<StringRef, 4> MatchInfo;
491 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
492 return StringRef::npos;
493
494 // Successful regex match.
495 assert(!MatchInfo.empty() && "Didn't get any match");
496 StringRef FullMatch = MatchInfo[0];
497
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000498 // If this defines any pattern variables, remember their values.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000499 for (const auto &VariableDef : VariableDefs) {
500 assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000501 Context->GlobalVariableTable[VariableDef.first] =
502 MatchInfo[VariableDef.second];
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000503 }
504
505 // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
506 // the required preceding newline, which is consumed by the pattern in the
507 // case of CHECK-EMPTY but not CHECK-NEXT.
508 size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
509 MatchLen = FullMatch.size() - MatchStartSkip;
510 return FullMatch.data() - Buffer.data() + MatchStartSkip;
511}
512
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000513unsigned FileCheckPattern::computeMatchDistance(StringRef Buffer) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000514 // Just compute the number of matching characters. For regular expressions, we
515 // just compare against the regex itself and hope for the best.
516 //
517 // FIXME: One easy improvement here is have the regex lib generate a single
518 // example regular expression which matches, and use that as the example
519 // string.
520 StringRef ExampleString(FixedStr);
521 if (ExampleString.empty())
522 ExampleString = RegExStr;
523
524 // Only compare up to the first line in the buffer, or the string size.
525 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
526 BufferPrefix = BufferPrefix.split('\n').first;
527 return BufferPrefix.edit_distance(ExampleString);
528}
529
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000530void FileCheckPattern::printSubstitutions(const SourceMgr &SM, StringRef Buffer,
531 SMRange MatchRange) const {
532 // Print what we know about substitutions. This covers both uses of pattern
533 // variables and numeric subsitutions.
534 if (!Substitutions.empty()) {
535 for (const auto &Substitution : Substitutions) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000536 SmallString<256> Msg;
537 raw_svector_ostream OS(Msg);
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000538 bool IsNumExpr = Substitution.isNumExpr();
539 llvm::Optional<std::string> MatchedValue = Substitution.getResult();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000540
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000541 // Substitution failed or is not known at match time, print the undefined
542 // variable it uses.
543 if (!MatchedValue) {
544 StringRef UndefVarName = Substitution.getUndefVarName();
545 if (UndefVarName.empty())
546 continue;
547 OS << "uses undefined variable \"";
548 OS.write_escaped(UndefVarName) << "\"";
549 } else {
550 // Substitution succeeded. Print substituted value.
551 if (IsNumExpr)
552 OS << "with numeric expression \"";
553 else
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000554 OS << "with variable \"";
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000555 OS.write_escaped(Substitution.getFromString()) << "\" equal to \"";
556 OS.write_escaped(*MatchedValue) << "\"";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000557 }
558
559 if (MatchRange.isValid())
560 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
561 {MatchRange});
562 else
563 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
564 SourceMgr::DK_Note, OS.str());
565 }
566 }
567}
568
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000569static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
570 const SourceMgr &SM, SMLoc Loc,
571 Check::FileCheckType CheckTy,
572 StringRef Buffer, size_t Pos, size_t Len,
Joel E. Denny7df86962018-12-18 00:03:03 +0000573 std::vector<FileCheckDiag> *Diags,
574 bool AdjustPrevDiag = false) {
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000575 SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
576 SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
577 SMRange Range(Start, End);
Joel E. Denny96f0e842018-12-18 00:03:36 +0000578 if (Diags) {
Joel E. Denny7df86962018-12-18 00:03:03 +0000579 if (AdjustPrevDiag)
580 Diags->rbegin()->MatchTy = MatchTy;
581 else
582 Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
583 }
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000584 return Range;
585}
586
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000587void FileCheckPattern::printFuzzyMatch(
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000588 const SourceMgr &SM, StringRef Buffer,
Joel E. Denny2c007c82018-12-18 00:02:04 +0000589 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000590 // Attempt to find the closest/best fuzzy match. Usually an error happens
591 // because some string in the output didn't exactly match. In these cases, we
592 // would like to show the user a best guess at what "should have" matched, to
593 // save them having to actually check the input manually.
594 size_t NumLinesForward = 0;
595 size_t Best = StringRef::npos;
596 double BestQuality = 0;
597
598 // Use an arbitrary 4k limit on how far we will search.
599 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
600 if (Buffer[i] == '\n')
601 ++NumLinesForward;
602
603 // Patterns have leading whitespace stripped, so skip whitespace when
604 // looking for something which looks like a pattern.
605 if (Buffer[i] == ' ' || Buffer[i] == '\t')
606 continue;
607
608 // Compute the "quality" of this match as an arbitrary combination of the
609 // match distance and the number of lines skipped to get to this match.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000610 unsigned Distance = computeMatchDistance(Buffer.substr(i));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000611 double Quality = Distance + (NumLinesForward / 100.);
612
613 if (Quality < BestQuality || Best == StringRef::npos) {
614 Best = i;
615 BestQuality = Quality;
616 }
617 }
618
619 // Print the "possible intended match here" line if we found something
620 // reasonable and not equal to what we showed in the "scanning from here"
621 // line.
622 if (Best && Best != StringRef::npos && BestQuality < 50) {
Joel E. Denny2c007c82018-12-18 00:02:04 +0000623 SMRange MatchRange =
624 ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
625 getCheckTy(), Buffer, Best, 0, Diags);
626 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
627 "possible intended match here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000628
629 // FIXME: If we wanted to be really friendly we would show why the match
630 // failed, as it can be hard to spot simple one character differences.
631 }
632}
633
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000634llvm::Optional<StringRef>
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000635FileCheckPatternContext::getPatternVarValue(StringRef VarName) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000636 auto VarIter = GlobalVariableTable.find(VarName);
637 if (VarIter == GlobalVariableTable.end())
638 return llvm::None;
639
640 return VarIter->second;
641}
642
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000643FileCheckNumExpr *
644FileCheckPatternContext::makeNumExpr(binop_eval_t EvalBinop,
645 FileCheckNumericVariable *OperandLeft,
646 uint64_t OperandRight) {
647 NumExprs.push_back(llvm::make_unique<FileCheckNumExpr>(EvalBinop, OperandLeft,
648 OperandRight));
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000649 return NumExprs.back().get();
650}
651
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000652FileCheckNumericVariable *
653FileCheckPatternContext::makeNumericVariable(StringRef Name, uint64_t Value) {
654 NumericVariables.push_back(
655 llvm::make_unique<FileCheckNumericVariable>(Name, Value));
656 return NumericVariables.back().get();
657}
658
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000659size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
660 // Offset keeps track of the current offset within the input Str
661 size_t Offset = 0;
662 // [...] Nesting depth
663 size_t BracketDepth = 0;
664
665 while (!Str.empty()) {
666 if (Str.startswith("]]") && BracketDepth == 0)
667 return Offset;
668 if (Str[0] == '\\') {
669 // Backslash escapes the next char within regexes, so skip them both.
670 Str = Str.substr(2);
671 Offset += 2;
672 } else {
673 switch (Str[0]) {
674 default:
675 break;
676 case '[':
677 BracketDepth++;
678 break;
679 case ']':
680 if (BracketDepth == 0) {
681 SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
682 SourceMgr::DK_Error,
683 "missing closing \"]\" for regex variable");
684 exit(1);
685 }
686 BracketDepth--;
687 break;
688 }
689 Str = Str.substr(1);
690 Offset++;
691 }
692 }
693
694 return StringRef::npos;
695}
696
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000697StringRef
698llvm::FileCheck::CanonicalizeFile(MemoryBuffer &MB,
699 SmallVectorImpl<char> &OutputBuffer) {
700 OutputBuffer.reserve(MB.getBufferSize());
701
702 for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
703 Ptr != End; ++Ptr) {
704 // Eliminate trailing dosish \r.
705 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
706 continue;
707 }
708
709 // If current char is not a horizontal whitespace or if horizontal
710 // whitespace canonicalization is disabled, dump it to output as is.
711 if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
712 OutputBuffer.push_back(*Ptr);
713 continue;
714 }
715
716 // Otherwise, add one space and advance over neighboring space.
717 OutputBuffer.push_back(' ');
718 while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
719 ++Ptr;
720 }
721
722 // Add a null byte and then return all but that byte.
723 OutputBuffer.push_back('\0');
724 return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
725}
726
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000727FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
728 const Check::FileCheckType &CheckTy,
729 SMLoc CheckLoc, MatchType MatchTy,
730 SMRange InputRange)
731 : CheckTy(CheckTy), MatchTy(MatchTy) {
732 auto Start = SM.getLineAndColumn(InputRange.Start);
733 auto End = SM.getLineAndColumn(InputRange.End);
734 InputStartLine = Start.first;
735 InputStartCol = Start.second;
736 InputEndLine = End.first;
737 InputEndCol = End.second;
738 Start = SM.getLineAndColumn(CheckLoc);
739 CheckLine = Start.first;
740 CheckCol = Start.second;
741}
742
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000743static bool IsPartOfWord(char c) {
744 return (isalnum(c) || c == '-' || c == '_');
745}
746
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000747Check::FileCheckType &Check::FileCheckType::setCount(int C) {
Fedor Sergeev8477a3e2018-11-13 01:09:53 +0000748 assert(Count > 0 && "zero and negative counts are not supported");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000749 assert((C == 1 || Kind == CheckPlain) &&
750 "count supported only for plain CHECK directives");
751 Count = C;
752 return *this;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000753}
754
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000755std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
756 switch (Kind) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000757 case Check::CheckNone:
758 return "invalid";
759 case Check::CheckPlain:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000760 if (Count > 1)
761 return Prefix.str() + "-COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000762 return Prefix;
763 case Check::CheckNext:
764 return Prefix.str() + "-NEXT";
765 case Check::CheckSame:
766 return Prefix.str() + "-SAME";
767 case Check::CheckNot:
768 return Prefix.str() + "-NOT";
769 case Check::CheckDAG:
770 return Prefix.str() + "-DAG";
771 case Check::CheckLabel:
772 return Prefix.str() + "-LABEL";
773 case Check::CheckEmpty:
774 return Prefix.str() + "-EMPTY";
775 case Check::CheckEOF:
776 return "implicit EOF";
777 case Check::CheckBadNot:
778 return "bad NOT";
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000779 case Check::CheckBadCount:
780 return "bad COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000781 }
782 llvm_unreachable("unknown FileCheckType");
783}
784
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000785static std::pair<Check::FileCheckType, StringRef>
786FindCheckType(StringRef Buffer, StringRef Prefix) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000787 if (Buffer.size() <= Prefix.size())
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000788 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000789
790 char NextChar = Buffer[Prefix.size()];
791
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000792 StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000793 // Verify that the : is present after the prefix.
794 if (NextChar == ':')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000795 return {Check::CheckPlain, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000796
797 if (NextChar != '-')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000798 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000799
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000800 if (Rest.consume_front("COUNT-")) {
801 int64_t Count;
802 if (Rest.consumeInteger(10, Count))
803 // Error happened in parsing integer.
804 return {Check::CheckBadCount, Rest};
805 if (Count <= 0 || Count > INT32_MAX)
806 return {Check::CheckBadCount, Rest};
807 if (!Rest.consume_front(":"))
808 return {Check::CheckBadCount, Rest};
809 return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
810 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000811
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000812 if (Rest.consume_front("NEXT:"))
813 return {Check::CheckNext, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000814
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000815 if (Rest.consume_front("SAME:"))
816 return {Check::CheckSame, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000817
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000818 if (Rest.consume_front("NOT:"))
819 return {Check::CheckNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000820
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000821 if (Rest.consume_front("DAG:"))
822 return {Check::CheckDAG, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000823
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000824 if (Rest.consume_front("LABEL:"))
825 return {Check::CheckLabel, Rest};
826
827 if (Rest.consume_front("EMPTY:"))
828 return {Check::CheckEmpty, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000829
830 // You can't combine -NOT with another suffix.
831 if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
832 Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
833 Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
834 Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000835 return {Check::CheckBadNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000836
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000837 return {Check::CheckNone, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000838}
839
840// From the given position, find the next character after the word.
841static size_t SkipWord(StringRef Str, size_t Loc) {
842 while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
843 ++Loc;
844 return Loc;
845}
846
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +0000847/// Searches the buffer for the first prefix in the prefix regular expression.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000848///
849/// This searches the buffer using the provided regular expression, however it
850/// enforces constraints beyond that:
851/// 1) The found prefix must not be a suffix of something that looks like
852/// a valid prefix.
853/// 2) The found prefix must be followed by a valid check type suffix using \c
854/// FindCheckType above.
855///
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +0000856/// \returns a pair of StringRefs into the Buffer, which combines:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000857/// - the first match of the regular expression to satisfy these two is
858/// returned,
859/// otherwise an empty StringRef is returned to indicate failure.
860/// - buffer rewound to the location right after parsed suffix, for parsing
861/// to continue from
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000862///
863/// If this routine returns a valid prefix, it will also shrink \p Buffer to
864/// start at the beginning of the returned prefix, increment \p LineNumber for
865/// each new line consumed from \p Buffer, and set \p CheckTy to the type of
866/// check found by examining the suffix.
867///
868/// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
869/// is unspecified.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000870static std::pair<StringRef, StringRef>
871FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer,
872 unsigned &LineNumber, Check::FileCheckType &CheckTy) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000873 SmallVector<StringRef, 2> Matches;
874
875 while (!Buffer.empty()) {
876 // Find the first (longest) match using the RE.
877 if (!PrefixRE.match(Buffer, &Matches))
878 // No match at all, bail.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000879 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000880
881 StringRef Prefix = Matches[0];
882 Matches.clear();
883
884 assert(Prefix.data() >= Buffer.data() &&
885 Prefix.data() < Buffer.data() + Buffer.size() &&
886 "Prefix doesn't start inside of buffer!");
887 size_t Loc = Prefix.data() - Buffer.data();
888 StringRef Skipped = Buffer.substr(0, Loc);
889 Buffer = Buffer.drop_front(Loc);
890 LineNumber += Skipped.count('\n');
891
892 // Check that the matched prefix isn't a suffix of some other check-like
893 // word.
894 // FIXME: This is a very ad-hoc check. it would be better handled in some
895 // other way. Among other things it seems hard to distinguish between
896 // intentional and unintentional uses of this feature.
897 if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
898 // Now extract the type.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000899 StringRef AfterSuffix;
900 std::tie(CheckTy, AfterSuffix) = FindCheckType(Buffer, Prefix);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000901
902 // If we've found a valid check type for this prefix, we're done.
903 if (CheckTy != Check::CheckNone)
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000904 return {Prefix, AfterSuffix};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000905 }
906
907 // If we didn't successfully find a prefix, we need to skip this invalid
908 // prefix and continue scanning. We directly skip the prefix that was
909 // matched and any additional parts of that check-like word.
910 Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
911 }
912
913 // We ran out of buffer while skipping partial matches so give up.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000914 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000915}
916
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000917bool llvm::FileCheck::ReadCheckFile(
918 SourceMgr &SM, StringRef Buffer, Regex &PrefixRE,
919 std::vector<FileCheckString> &CheckStrings) {
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000920 if (PatternContext.defineCmdlineVariables(Req.GlobalDefines, SM))
921 return true;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000922
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000923 std::vector<FileCheckPattern> ImplicitNegativeChecks;
924 for (const auto &PatternString : Req.ImplicitCheckNot) {
925 // Create a buffer with fake command line content in order to display the
926 // command line option responsible for the specific implicit CHECK-NOT.
927 std::string Prefix = "-implicit-check-not='";
928 std::string Suffix = "'";
929 std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
930 Prefix + PatternString + Suffix, "command line");
931
932 StringRef PatternInBuffer =
933 CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
934 SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
935
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000936 ImplicitNegativeChecks.push_back(
937 FileCheckPattern(Check::CheckNot, &PatternContext));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000938 ImplicitNegativeChecks.back().ParsePattern(PatternInBuffer,
939 "IMPLICIT-CHECK", SM, 0, Req);
940 }
941
942 std::vector<FileCheckPattern> DagNotMatches = ImplicitNegativeChecks;
943
944 // LineNumber keeps track of the line on which CheckPrefix instances are
945 // found.
946 unsigned LineNumber = 1;
947
948 while (1) {
949 Check::FileCheckType CheckTy;
950
951 // See if a prefix occurs in the memory buffer.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000952 StringRef UsedPrefix;
953 StringRef AfterSuffix;
954 std::tie(UsedPrefix, AfterSuffix) =
955 FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, CheckTy);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000956 if (UsedPrefix.empty())
957 break;
958 assert(UsedPrefix.data() == Buffer.data() &&
959 "Failed to move Buffer's start forward, or pointed prefix outside "
960 "of the buffer!");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000961 assert(AfterSuffix.data() >= Buffer.data() &&
962 AfterSuffix.data() < Buffer.data() + Buffer.size() &&
963 "Parsing after suffix doesn't start inside of buffer!");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000964
965 // Location to use for error messages.
966 const char *UsedPrefixStart = UsedPrefix.data();
967
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000968 // Skip the buffer to the end of parsed suffix (or just prefix, if no good
969 // suffix was processed).
970 Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
971 : AfterSuffix;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000972
973 // Complain about useful-looking but unsupported suffixes.
974 if (CheckTy == Check::CheckBadNot) {
975 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
976 "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
977 return true;
978 }
979
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000980 // Complain about invalid count specification.
981 if (CheckTy == Check::CheckBadCount) {
982 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
983 "invalid count in -COUNT specification on prefix '" +
984 UsedPrefix + "'");
985 return true;
986 }
987
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000988 // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
989 // leading whitespace.
990 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
991 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
992
993 // Scan ahead to the end of line.
994 size_t EOL = Buffer.find_first_of("\n\r");
995
996 // Remember the location of the start of the pattern, for diagnostics.
997 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
998
999 // Parse the pattern.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001000 FileCheckPattern P(CheckTy, &PatternContext);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001001 if (P.ParsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, LineNumber, Req))
1002 return true;
1003
1004 // Verify that CHECK-LABEL lines do not define or use variables
1005 if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
1006 SM.PrintMessage(
1007 SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
1008 "found '" + UsedPrefix + "-LABEL:'"
1009 " with variable definition or use");
1010 return true;
1011 }
1012
1013 Buffer = Buffer.substr(EOL);
1014
1015 // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
1016 if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
1017 CheckTy == Check::CheckEmpty) &&
1018 CheckStrings.empty()) {
1019 StringRef Type = CheckTy == Check::CheckNext
1020 ? "NEXT"
1021 : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
1022 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
1023 SourceMgr::DK_Error,
1024 "found '" + UsedPrefix + "-" + Type +
1025 "' without previous '" + UsedPrefix + ": line");
1026 return true;
1027 }
1028
1029 // Handle CHECK-DAG/-NOT.
1030 if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
1031 DagNotMatches.push_back(P);
1032 continue;
1033 }
1034
1035 // Okay, add the string we captured to the output vector and move on.
1036 CheckStrings.emplace_back(P, UsedPrefix, PatternLoc);
1037 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1038 DagNotMatches = ImplicitNegativeChecks;
1039 }
1040
1041 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
1042 // prefix as a filler for the error message.
1043 if (!DagNotMatches.empty()) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001044 CheckStrings.emplace_back(
1045 FileCheckPattern(Check::CheckEOF, &PatternContext),
1046 *Req.CheckPrefixes.begin(), SMLoc::getFromPointer(Buffer.data()));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001047 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1048 }
1049
1050 if (CheckStrings.empty()) {
1051 errs() << "error: no check strings found with prefix"
1052 << (Req.CheckPrefixes.size() > 1 ? "es " : " ");
1053 auto I = Req.CheckPrefixes.begin();
1054 auto E = Req.CheckPrefixes.end();
1055 if (I != E) {
1056 errs() << "\'" << *I << ":'";
1057 ++I;
1058 }
1059 for (; I != E; ++I)
1060 errs() << ", \'" << *I << ":'";
1061
1062 errs() << '\n';
1063 return true;
1064 }
1065
1066 return false;
1067}
1068
1069static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
1070 StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001071 int MatchedCount, StringRef Buffer, size_t MatchPos,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001072 size_t MatchLen, const FileCheckRequest &Req,
1073 std::vector<FileCheckDiag> *Diags) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001074 bool PrintDiag = true;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001075 if (ExpectedMatch) {
1076 if (!Req.Verbose)
1077 return;
1078 if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
1079 return;
Joel E. Denny352695c2019-01-22 21:41:42 +00001080 // Due to their verbosity, we don't print verbose diagnostics here if we're
1081 // gathering them for a different rendering, but we always print other
1082 // diagnostics.
1083 PrintDiag = !Diags;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001084 }
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001085 SMRange MatchRange = ProcessMatchResult(
Joel E. Dennye2afb612018-12-18 00:03:51 +00001086 ExpectedMatch ? FileCheckDiag::MatchFoundAndExpected
1087 : FileCheckDiag::MatchFoundButExcluded,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001088 SM, Loc, Pat.getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
Joel E. Denny352695c2019-01-22 21:41:42 +00001089 if (!PrintDiag)
1090 return;
1091
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001092 std::string Message = formatv("{0}: {1} string found in input",
1093 Pat.getCheckTy().getDescription(Prefix),
1094 (ExpectedMatch ? "expected" : "excluded"))
1095 .str();
1096 if (Pat.getCount() > 1)
1097 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
1098
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001099 SM.PrintMessage(
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001100 Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001101 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
1102 {MatchRange});
Thomas Preud'homme288ed912019-05-02 00:04:38 +00001103 Pat.printSubstitutions(SM, Buffer, MatchRange);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001104}
1105
1106static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001107 const FileCheckString &CheckStr, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001108 StringRef Buffer, size_t MatchPos, size_t MatchLen,
1109 FileCheckRequest &Req,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001110 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001111 PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001112 MatchedCount, Buffer, MatchPos, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001113}
1114
1115static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001116 StringRef Prefix, SMLoc Loc,
1117 const FileCheckPattern &Pat, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001118 StringRef Buffer, bool VerboseVerbose,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001119 std::vector<FileCheckDiag> *Diags) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001120 bool PrintDiag = true;
1121 if (!ExpectedMatch) {
1122 if (!VerboseVerbose)
1123 return;
1124 // Due to their verbosity, we don't print verbose diagnostics here if we're
1125 // gathering them for a different rendering, but we always print other
1126 // diagnostics.
1127 PrintDiag = !Diags;
1128 }
1129
1130 // If the current position is at the end of a line, advance to the start of
1131 // the next line.
1132 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
1133 SMRange SearchRange = ProcessMatchResult(
1134 ExpectedMatch ? FileCheckDiag::MatchNoneButExpected
1135 : FileCheckDiag::MatchNoneAndExcluded,
1136 SM, Loc, Pat.getCheckTy(), Buffer, 0, Buffer.size(), Diags);
1137 if (!PrintDiag)
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001138 return;
1139
Joel E. Denny352695c2019-01-22 21:41:42 +00001140 // Print "not found" diagnostic.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001141 std::string Message = formatv("{0}: {1} string not found in input",
1142 Pat.getCheckTy().getDescription(Prefix),
1143 (ExpectedMatch ? "expected" : "excluded"))
1144 .str();
1145 if (Pat.getCount() > 1)
1146 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001147 SM.PrintMessage(
1148 Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001149
Joel E. Denny352695c2019-01-22 21:41:42 +00001150 // Print the "scanning from here" line.
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001151 SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001152
1153 // Allow the pattern to print additional information if desired.
Thomas Preud'homme288ed912019-05-02 00:04:38 +00001154 Pat.printSubstitutions(SM, Buffer);
Joel E. Denny96f0e842018-12-18 00:03:36 +00001155
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001156 if (ExpectedMatch)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001157 Pat.printFuzzyMatch(SM, Buffer, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001158}
1159
1160static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001161 const FileCheckString &CheckStr, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001162 StringRef Buffer, bool VerboseVerbose,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001163 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001164 PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001165 MatchedCount, Buffer, VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001166}
1167
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +00001168/// Counts the number of newlines in the specified range.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001169static unsigned CountNumNewlinesBetween(StringRef Range,
1170 const char *&FirstNewLine) {
1171 unsigned NumNewLines = 0;
1172 while (1) {
1173 // Scan for newline.
1174 Range = Range.substr(Range.find_first_of("\n\r"));
1175 if (Range.empty())
1176 return NumNewLines;
1177
1178 ++NumNewLines;
1179
1180 // Handle \n\r and \r\n as a single newline.
1181 if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
1182 (Range[0] != Range[1]))
1183 Range = Range.substr(1);
1184 Range = Range.substr(1);
1185
1186 if (NumNewLines == 1)
1187 FirstNewLine = Range.begin();
1188 }
1189}
1190
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001191size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001192 bool IsLabelScanMode, size_t &MatchLen,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001193 FileCheckRequest &Req,
1194 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001195 size_t LastPos = 0;
1196 std::vector<const FileCheckPattern *> NotStrings;
1197
1198 // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
1199 // bounds; we have not processed variable definitions within the bounded block
1200 // yet so cannot handle any final CHECK-DAG yet; this is handled when going
1201 // over the block again (including the last CHECK-LABEL) in normal mode.
1202 if (!IsLabelScanMode) {
1203 // Match "dag strings" (with mixed "not strings" if any).
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001204 LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001205 if (LastPos == StringRef::npos)
1206 return StringRef::npos;
1207 }
1208
1209 // Match itself from the last position after matching CHECK-DAG.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001210 size_t LastMatchEnd = LastPos;
1211 size_t FirstMatchPos = 0;
1212 // Go match the pattern Count times. Majority of patterns only match with
1213 // count 1 though.
1214 assert(Pat.getCount() != 0 && "pattern count can not be zero");
1215 for (int i = 1; i <= Pat.getCount(); i++) {
1216 StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
1217 size_t CurrentMatchLen;
1218 // get a match at current start point
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001219 size_t MatchPos = Pat.match(MatchBuffer, CurrentMatchLen);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001220 if (i == 1)
1221 FirstMatchPos = LastPos + MatchPos;
1222
1223 // report
1224 if (MatchPos == StringRef::npos) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001225 PrintNoMatch(true, SM, *this, i, MatchBuffer, Req.VerboseVerbose, Diags);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001226 return StringRef::npos;
1227 }
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001228 PrintMatch(true, SM, *this, i, MatchBuffer, MatchPos, CurrentMatchLen, Req,
1229 Diags);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001230
1231 // move start point after the match
1232 LastMatchEnd += MatchPos + CurrentMatchLen;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001233 }
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001234 // Full match len counts from first match pos.
1235 MatchLen = LastMatchEnd - FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001236
1237 // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1238 // or CHECK-NOT
1239 if (!IsLabelScanMode) {
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001240 size_t MatchPos = FirstMatchPos - LastPos;
1241 StringRef MatchBuffer = Buffer.substr(LastPos);
1242 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001243
1244 // If this check is a "CHECK-NEXT", verify that the previous match was on
1245 // the previous line (i.e. that there is one newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001246 if (CheckNext(SM, SkippedRegion)) {
Joel E. Dennye2afb612018-12-18 00:03:51 +00001247 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001248 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001249 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001250 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001251 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001252
1253 // If this check is a "CHECK-SAME", verify that the previous match was on
1254 // the same line (i.e. that there is no newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001255 if (CheckSame(SM, SkippedRegion)) {
Joel E. Dennye2afb612018-12-18 00:03:51 +00001256 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001257 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001258 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001259 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001260 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001261
1262 // If this match had "not strings", verify that they don't exist in the
1263 // skipped region.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001264 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001265 return StringRef::npos;
1266 }
1267
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001268 return FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001269}
1270
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001271bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1272 if (Pat.getCheckTy() != Check::CheckNext &&
1273 Pat.getCheckTy() != Check::CheckEmpty)
1274 return false;
1275
1276 Twine CheckName =
1277 Prefix +
1278 Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
1279
1280 // Count the number of newlines between the previous match and this one.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001281 const char *FirstNewLine = nullptr;
1282 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1283
1284 if (NumNewLines == 0) {
1285 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1286 CheckName + ": is on the same line as previous match");
1287 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1288 "'next' match was here");
1289 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1290 "previous match ended here");
1291 return true;
1292 }
1293
1294 if (NumNewLines != 1) {
1295 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1296 CheckName +
1297 ": is not on the line after the previous match");
1298 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1299 "'next' match was here");
1300 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1301 "previous match ended here");
1302 SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
1303 "non-matching line after previous match is here");
1304 return true;
1305 }
1306
1307 return false;
1308}
1309
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001310bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
1311 if (Pat.getCheckTy() != Check::CheckSame)
1312 return false;
1313
1314 // Count the number of newlines between the previous match and this one.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001315 const char *FirstNewLine = nullptr;
1316 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1317
1318 if (NumNewLines != 0) {
1319 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1320 Prefix +
1321 "-SAME: is not on the same line as the previous match");
1322 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1323 "'next' match was here");
1324 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1325 "previous match ended here");
1326 return true;
1327 }
1328
1329 return false;
1330}
1331
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001332bool FileCheckString::CheckNot(
1333 const SourceMgr &SM, StringRef Buffer,
1334 const std::vector<const FileCheckPattern *> &NotStrings,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001335 const FileCheckRequest &Req, std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001336 for (const FileCheckPattern *Pat : NotStrings) {
1337 assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1338
1339 size_t MatchLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001340 size_t Pos = Pat->match(Buffer, MatchLen);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001341
1342 if (Pos == StringRef::npos) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001343 PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001344 Req.VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001345 continue;
1346 }
1347
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001348 PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, Pos, MatchLen,
1349 Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001350
1351 return true;
1352 }
1353
1354 return false;
1355}
1356
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001357size_t
1358FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1359 std::vector<const FileCheckPattern *> &NotStrings,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001360 const FileCheckRequest &Req,
1361 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001362 if (DagNotStrings.empty())
1363 return 0;
1364
1365 // The start of the search range.
1366 size_t StartPos = 0;
1367
1368 struct MatchRange {
1369 size_t Pos;
1370 size_t End;
1371 };
1372 // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
1373 // ranges are erased from this list once they are no longer in the search
1374 // range.
1375 std::list<MatchRange> MatchRanges;
1376
1377 // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
1378 // group, so we don't use a range-based for loop here.
1379 for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
1380 PatItr != PatEnd; ++PatItr) {
1381 const FileCheckPattern &Pat = *PatItr;
1382 assert((Pat.getCheckTy() == Check::CheckDAG ||
1383 Pat.getCheckTy() == Check::CheckNot) &&
1384 "Invalid CHECK-DAG or CHECK-NOT!");
1385
1386 if (Pat.getCheckTy() == Check::CheckNot) {
1387 NotStrings.push_back(&Pat);
1388 continue;
1389 }
1390
1391 assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1392
1393 // CHECK-DAG always matches from the start.
1394 size_t MatchLen = 0, MatchPos = StartPos;
1395
1396 // Search for a match that doesn't overlap a previous match in this
1397 // CHECK-DAG group.
1398 for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
1399 StringRef MatchBuffer = Buffer.substr(MatchPos);
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001400 size_t MatchPosBuf = Pat.match(MatchBuffer, MatchLen);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001401 // With a group of CHECK-DAGs, a single mismatching means the match on
1402 // that group of CHECK-DAGs fails immediately.
1403 if (MatchPosBuf == StringRef::npos) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001404 PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001405 Req.VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001406 return StringRef::npos;
1407 }
1408 // Re-calc it as the offset relative to the start of the original string.
1409 MatchPos += MatchPosBuf;
1410 if (Req.VerboseVerbose)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001411 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1412 MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001413 MatchRange M{MatchPos, MatchPos + MatchLen};
1414 if (Req.AllowDeprecatedDagOverlap) {
1415 // We don't need to track all matches in this mode, so we just maintain
1416 // one match range that encompasses the current CHECK-DAG group's
1417 // matches.
1418 if (MatchRanges.empty())
1419 MatchRanges.insert(MatchRanges.end(), M);
1420 else {
1421 auto Block = MatchRanges.begin();
1422 Block->Pos = std::min(Block->Pos, M.Pos);
1423 Block->End = std::max(Block->End, M.End);
1424 }
1425 break;
1426 }
1427 // Iterate previous matches until overlapping match or insertion point.
1428 bool Overlap = false;
1429 for (; MI != ME; ++MI) {
1430 if (M.Pos < MI->End) {
1431 // !Overlap => New match has no overlap and is before this old match.
1432 // Overlap => New match overlaps this old match.
1433 Overlap = MI->Pos < M.End;
1434 break;
1435 }
1436 }
1437 if (!Overlap) {
1438 // Insert non-overlapping match into list.
1439 MatchRanges.insert(MI, M);
1440 break;
1441 }
1442 if (Req.VerboseVerbose) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001443 // Due to their verbosity, we don't print verbose diagnostics here if
1444 // we're gathering them for a different rendering, but we always print
1445 // other diagnostics.
1446 if (!Diags) {
1447 SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
1448 SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
1449 SMRange OldRange(OldStart, OldEnd);
1450 SM.PrintMessage(OldStart, SourceMgr::DK_Note,
1451 "match discarded, overlaps earlier DAG match here",
1452 {OldRange});
1453 } else
Joel E. Dennye2afb612018-12-18 00:03:51 +00001454 Diags->rbegin()->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001455 }
1456 MatchPos = MI->End;
1457 }
1458 if (!Req.VerboseVerbose)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001459 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1460 MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001461
1462 // Handle the end of a CHECK-DAG group.
1463 if (std::next(PatItr) == PatEnd ||
1464 std::next(PatItr)->getCheckTy() == Check::CheckNot) {
1465 if (!NotStrings.empty()) {
1466 // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
1467 // CHECK-DAG, verify that there are no 'not' strings occurred in that
1468 // region.
1469 StringRef SkippedRegion =
1470 Buffer.slice(StartPos, MatchRanges.begin()->Pos);
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001471 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001472 return StringRef::npos;
1473 // Clear "not strings".
1474 NotStrings.clear();
1475 }
1476 // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
1477 // end of this CHECK-DAG group's match range.
1478 StartPos = MatchRanges.rbegin()->End;
1479 // Don't waste time checking for (impossible) overlaps before that.
1480 MatchRanges.clear();
1481 }
1482 }
1483
1484 return StartPos;
1485}
1486
1487// A check prefix must contain only alphanumeric, hyphens and underscores.
1488static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1489 Regex Validator("^[a-zA-Z0-9_-]*$");
1490 return Validator.match(CheckPrefix);
1491}
1492
1493bool llvm::FileCheck::ValidateCheckPrefixes() {
1494 StringSet<> PrefixSet;
1495
1496 for (StringRef Prefix : Req.CheckPrefixes) {
1497 // Reject empty prefixes.
1498 if (Prefix == "")
1499 return false;
1500
1501 if (!PrefixSet.insert(Prefix).second)
1502 return false;
1503
1504 if (!ValidateCheckPrefix(Prefix))
1505 return false;
1506 }
1507
1508 return true;
1509}
1510
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001511Regex llvm::FileCheck::buildCheckPrefixRegex() {
1512 // I don't think there's a way to specify an initial value for cl::list,
1513 // so if nothing was specified, add the default
1514 if (Req.CheckPrefixes.empty())
1515 Req.CheckPrefixes.push_back("CHECK");
1516
1517 // We already validated the contents of CheckPrefixes so just concatenate
1518 // them as alternatives.
1519 SmallString<32> PrefixRegexStr;
1520 for (StringRef Prefix : Req.CheckPrefixes) {
1521 if (Prefix != Req.CheckPrefixes.front())
1522 PrefixRegexStr.push_back('|');
1523
1524 PrefixRegexStr.append(Prefix);
1525 }
1526
1527 return Regex(PrefixRegexStr);
1528}
1529
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001530bool FileCheckPatternContext::defineCmdlineVariables(
1531 std::vector<std::string> &CmdlineDefines, SourceMgr &SM) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001532 assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001533 "Overriding defined variable with command-line variable definitions");
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001534
1535 if (CmdlineDefines.empty())
1536 return false;
1537
1538 // Create a string representing the vector of command-line definitions. Each
1539 // definition is on its own line and prefixed with a definition number to
1540 // clarify which definition a given diagnostic corresponds to.
1541 unsigned I = 0;
1542 bool ErrorFound = false;
1543 std::string CmdlineDefsDiag;
1544 StringRef Prefix1 = "Global define #";
1545 StringRef Prefix2 = ": ";
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001546 for (StringRef CmdlineDef : CmdlineDefines)
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001547 CmdlineDefsDiag +=
1548 (Prefix1 + Twine(++I) + Prefix2 + CmdlineDef + "\n").str();
1549
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001550 // Create a buffer with fake command line content in order to display
1551 // parsing diagnostic with location information and point to the
1552 // global definition with invalid syntax.
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001553 std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
1554 MemoryBuffer::getMemBufferCopy(CmdlineDefsDiag, "Global defines");
1555 StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
1556 SM.AddNewSourceBuffer(std::move(CmdLineDefsDiagBuffer), SMLoc());
1557
1558 SmallVector<StringRef, 4> CmdlineDefsDiagVec;
1559 CmdlineDefsDiagRef.split(CmdlineDefsDiagVec, '\n', -1 /*MaxSplit*/,
1560 false /*KeepEmpty*/);
1561 for (StringRef CmdlineDefDiag : CmdlineDefsDiagVec) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001562 unsigned DefStart = CmdlineDefDiag.find(Prefix2) + Prefix2.size();
1563 StringRef CmdlineDef = CmdlineDefDiag.substr(DefStart);
1564 if (CmdlineDef.find('=') == StringRef::npos) {
1565 SM.PrintMessage(SMLoc::getFromPointer(CmdlineDef.data()),
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001566 SourceMgr::DK_Error,
1567 "Missing equal sign in global definition");
1568 ErrorFound = true;
1569 continue;
1570 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001571
1572 // Numeric variable definition.
1573 if (CmdlineDef[0] == '#') {
1574 bool IsPseudo;
1575 unsigned TrailIdx;
1576 size_t EqIdx = CmdlineDef.find('=');
1577 StringRef CmdlineName = CmdlineDef.substr(1, EqIdx - 1);
1578 if (FileCheckPattern::parseVariable(CmdlineName, IsPseudo, TrailIdx) ||
1579 IsPseudo || TrailIdx != CmdlineName.size() || CmdlineName.empty()) {
1580 SM.PrintMessage(SMLoc::getFromPointer(CmdlineName.data()),
1581 SourceMgr::DK_Error,
1582 "invalid name in numeric variable definition '" +
1583 CmdlineName + "'");
1584 ErrorFound = true;
1585 continue;
1586 }
1587
1588 // Detect collisions between pattern and numeric variables when the
1589 // latter is created later than the former.
1590 if (DefinedVariableTable.find(CmdlineName) !=
1591 DefinedVariableTable.end()) {
1592 SM.PrintMessage(
1593 SMLoc::getFromPointer(CmdlineName.data()), SourceMgr::DK_Error,
1594 "pattern variable with name '" + CmdlineName + "' already exists");
1595 ErrorFound = true;
1596 continue;
1597 }
1598
1599 StringRef CmdlineVal = CmdlineDef.substr(EqIdx + 1);
1600 uint64_t Val;
1601 if (CmdlineVal.getAsInteger(10, Val)) {
1602 SM.PrintMessage(SMLoc::getFromPointer(CmdlineVal.data()),
1603 SourceMgr::DK_Error,
1604 "invalid value in numeric variable definition '" +
1605 CmdlineVal + "'");
1606 ErrorFound = true;
1607 continue;
1608 }
1609 auto DefinedNumericVariable = makeNumericVariable(CmdlineName, Val);
1610
1611 // Record this variable definition.
1612 GlobalNumericVariableTable[CmdlineName] = DefinedNumericVariable;
1613 } else {
1614 // Pattern variable definition.
1615 std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.split('=');
1616 StringRef Name = CmdlineNameVal.first;
1617 bool IsPseudo;
1618 unsigned TrailIdx;
1619 if (FileCheckPattern::parseVariable(Name, IsPseudo, TrailIdx) ||
1620 IsPseudo || TrailIdx != Name.size() || Name.empty()) {
1621 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
1622 "invalid name in pattern variable definition '" + Name +
1623 "'");
1624 ErrorFound = true;
1625 continue;
1626 }
1627
1628 // Detect collisions between pattern and numeric variables when the
1629 // former is created later than the latter.
1630 if (GlobalNumericVariableTable.find(Name) !=
1631 GlobalNumericVariableTable.end()) {
1632 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
1633 "numeric variable with name '" + Name +
1634 "' already exists");
1635 ErrorFound = true;
1636 continue;
1637 }
1638 GlobalVariableTable.insert(CmdlineNameVal);
1639 // Mark the pattern variable as defined to detect collisions between
1640 // pattern and numeric variables in DefineCmdlineVariables when the
1641 // latter is created later than the former. We cannot reuse
1642 // GlobalVariableTable for that by populating it with an empty string
1643 // since we would then lose the ability to detect the use of an undefined
1644 // variable in Match().
1645 DefinedVariableTable[Name] = true;
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001646 }
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001647 }
1648
1649 return ErrorFound;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001650}
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001651
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001652void FileCheckPatternContext::clearLocalVars() {
1653 SmallVector<StringRef, 16> LocalPatternVars, LocalNumericVars;
1654 for (const StringMapEntry<StringRef> &Var : GlobalVariableTable)
1655 if (Var.first()[0] != '$')
1656 LocalPatternVars.push_back(Var.first());
1657
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001658 // Numeric expression substitution reads the value of a variable directly,
1659 // not via GlobalNumericVariableTable. Therefore, we clear local variables by
1660 // clearing their value which will lead to a numeric expression substitution
1661 // failure. We also mark the variable for removal from
1662 // GlobalNumericVariableTable since this is what defineCmdlineVariables
1663 // checks to decide that no global variable has been defined.
1664 for (const auto &Var : GlobalNumericVariableTable)
1665 if (Var.first()[0] != '$') {
1666 Var.getValue()->clearValue();
1667 LocalNumericVars.push_back(Var.first());
1668 }
1669
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001670 for (const auto &Var : LocalPatternVars)
1671 GlobalVariableTable.erase(Var);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001672 for (const auto &Var : LocalNumericVars)
1673 GlobalNumericVariableTable.erase(Var);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001674}
1675
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001676bool llvm::FileCheck::CheckInput(SourceMgr &SM, StringRef Buffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001677 ArrayRef<FileCheckString> CheckStrings,
1678 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001679 bool ChecksFailed = false;
1680
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001681 unsigned i = 0, j = 0, e = CheckStrings.size();
1682 while (true) {
1683 StringRef CheckRegion;
1684 if (j == e) {
1685 CheckRegion = Buffer;
1686 } else {
1687 const FileCheckString &CheckLabelStr = CheckStrings[j];
1688 if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
1689 ++j;
1690 continue;
1691 }
1692
1693 // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1694 size_t MatchLabelLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001695 size_t MatchLabelPos =
1696 CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001697 if (MatchLabelPos == StringRef::npos)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001698 // Immediately bail if CHECK-LABEL fails, nothing else we can do.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001699 return false;
1700
1701 CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1702 Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1703 ++j;
1704 }
1705
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001706 // Do not clear the first region as it's the one before the first
1707 // CHECK-LABEL and it would clear variables defined on the command-line
1708 // before they get used.
1709 if (i != 0 && Req.EnableVarScope)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001710 PatternContext.clearLocalVars();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001711
1712 for (; i != j; ++i) {
1713 const FileCheckString &CheckStr = CheckStrings[i];
1714
1715 // Check each string within the scanned region, including a second check
1716 // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1717 size_t MatchLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001718 size_t MatchPos =
1719 CheckStr.Check(SM, CheckRegion, false, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001720
1721 if (MatchPos == StringRef::npos) {
1722 ChecksFailed = true;
1723 i = j;
1724 break;
1725 }
1726
1727 CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1728 }
1729
1730 if (j == e)
1731 break;
1732 }
1733
1734 // Success if no checks failed.
1735 return !ChecksFailed;
1736}