blob: 9fb4d798849d704942b74ecf04dc189ed34b1a2c [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'homme2bf04f22019-07-10 12:49:28 +000027void FileCheckNumericVariable::setValue(uint64_t NewValue) {
28 assert(!Value && "Overwriting numeric variable's value is not allowed");
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000029 Value = NewValue;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000030}
31
Thomas Preud'homme2bf04f22019-07-10 12:49:28 +000032void FileCheckNumericVariable::clearValue() {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000033 if (!Value)
Thomas Preud'homme2bf04f22019-07-10 12:49:28 +000034 return;
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +000035 Value = None;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000036}
37
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +000038Expected<uint64_t> FileCheckNumericVariableUse::eval() const {
39 Optional<uint64_t> Value = NumericVariable->getValue();
40 if (Value)
41 return *Value;
42 return make_error<FileCheckUndefVarError>(Name);
43}
44
45Expected<uint64_t> FileCheckASTBinop::eval() const {
46 Expected<uint64_t> LeftOp = LeftOperand->eval();
47 Expected<uint64_t> RightOp = RightOperand->eval();
48
49 // Bubble up any error (e.g. undefined variables) in the recursive
50 // evaluation.
51 if (!LeftOp || !RightOp) {
52 Error Err = Error::success();
53 if (!LeftOp)
54 Err = joinErrors(std::move(Err), LeftOp.takeError());
55 if (!RightOp)
56 Err = joinErrors(std::move(Err), RightOp.takeError());
57 return std::move(Err);
58 }
59
60 return EvalBinop(*LeftOp, *RightOp);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000061}
62
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000063Expected<std::string> FileCheckNumericSubstitution::getResult() const {
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +000064 Expected<uint64_t> EvaluatedValue = ExpressionAST->eval();
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +000065 if (!EvaluatedValue)
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000066 return EvaluatedValue.takeError();
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +000067 return utostr(*EvaluatedValue);
68}
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000069
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000070Expected<std::string> FileCheckStringSubstitution::getResult() const {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000071 // Look up the value and escape it so that we can put it into the regex.
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000072 Expected<StringRef> VarVal = Context->getPatternVarValue(FromStr);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000073 if (!VarVal)
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000074 return VarVal.takeError();
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000075 return Regex::escape(*VarVal);
Thomas Preud'homme288ed912019-05-02 00:04:38 +000076}
77
Thomas Preud'homme5a330472019-04-29 13:32:36 +000078bool FileCheckPattern::isValidVarNameStart(char C) {
79 return C == '_' || isalpha(C);
80}
81
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +000082Expected<FileCheckPattern::VariableProperties>
83FileCheckPattern::parseVariable(StringRef &Str, const SourceMgr &SM) {
Thomas Preud'homme5a330472019-04-29 13:32:36 +000084 if (Str.empty())
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000085 return FileCheckErrorDiagnostic::get(SM, Str, "empty variable name");
Thomas Preud'homme5a330472019-04-29 13:32:36 +000086
87 bool ParsedOneChar = false;
88 unsigned I = 0;
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +000089 bool IsPseudo = Str[0] == '@';
Thomas Preud'homme5a330472019-04-29 13:32:36 +000090
91 // Global vars start with '$'.
92 if (Str[0] == '$' || IsPseudo)
93 ++I;
94
95 for (unsigned E = Str.size(); I != E; ++I) {
96 if (!ParsedOneChar && !isValidVarNameStart(Str[I]))
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000097 return FileCheckErrorDiagnostic::get(SM, Str, "invalid variable name");
Thomas Preud'homme5a330472019-04-29 13:32:36 +000098
99 // Variable names are composed of alphanumeric characters and underscores.
100 if (Str[I] != '_' && !isalnum(Str[I]))
101 break;
102 ParsedOneChar = true;
103 }
104
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000105 StringRef Name = Str.take_front(I);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000106 Str = Str.substr(I);
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000107 return VariableProperties {Name, IsPseudo};
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000108}
109
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000110// StringRef holding all characters considered as horizontal whitespaces by
111// FileCheck input canonicalization.
112StringRef SpaceChars = " \t";
113
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000114// Parsing helper function that strips the first character in S and returns it.
115static char popFront(StringRef &S) {
116 char C = S.front();
117 S = S.drop_front();
118 return C;
119}
120
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000121char FileCheckUndefVarError::ID = 0;
122char FileCheckErrorDiagnostic::ID = 0;
123char FileCheckNotFoundError::ID = 0;
124
Thomas Preud'homme56f63082019-07-05 16:25:46 +0000125Expected<FileCheckNumericVariable *>
126FileCheckPattern::parseNumericVariableDefinition(
127 StringRef &Expr, FileCheckPatternContext *Context, size_t LineNumber,
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000128 const SourceMgr &SM) {
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000129 Expected<VariableProperties> ParseVarResult = parseVariable(Expr, SM);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000130 if (!ParseVarResult)
131 return ParseVarResult.takeError();
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000132 StringRef Name = ParseVarResult->Name;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000133
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000134 if (ParseVarResult->IsPseudo)
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000135 return FileCheckErrorDiagnostic::get(
136 SM, Name, "definition of pseudo numeric variable unsupported");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000137
138 // Detect collisions between string and numeric variables when the latter
139 // is created later than the former.
140 if (Context->DefinedVariableTable.find(Name) !=
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000141 Context->DefinedVariableTable.end())
142 return FileCheckErrorDiagnostic::get(
143 SM, Name, "string variable with name '" + Name + "' already exists");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000144
Thomas Preud'homme28196a52019-07-05 12:01:06 +0000145 Expr = Expr.ltrim(SpaceChars);
146 if (!Expr.empty())
147 return FileCheckErrorDiagnostic::get(
148 SM, Expr, "unexpected characters after numeric variable name");
149
Thomas Preud'homme56f63082019-07-05 16:25:46 +0000150 FileCheckNumericVariable *DefinedNumericVariable;
151 auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
152 if (VarTableIter != Context->GlobalNumericVariableTable.end())
153 DefinedNumericVariable = VarTableIter->second;
154 else
155 DefinedNumericVariable = Context->makeNumericVariable(LineNumber, Name);
156
157 return DefinedNumericVariable;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000158}
159
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000160Expected<std::unique_ptr<FileCheckNumericVariableUse>>
161FileCheckPattern::parseNumericVariableUse(StringRef Name, bool IsPseudo,
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000162 const SourceMgr &SM) const {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000163 if (IsPseudo && !Name.equals("@LINE"))
164 return FileCheckErrorDiagnostic::get(
165 SM, Name, "invalid pseudo numeric variable '" + Name + "'");
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000166
Thomas Preud'homme41f2bea2019-07-05 12:01:12 +0000167 // Numeric variable definitions and uses are parsed in the order in which
168 // they appear in the CHECK patterns. For each definition, the pointer to the
169 // class instance of the corresponding numeric variable definition is stored
Thomas Preud'homme56f63082019-07-05 16:25:46 +0000170 // in GlobalNumericVariableTable in parsePattern. Therefore, if the pointer
171 // we get below is null, it means no such variable was defined before. When
172 // that happens, we create a dummy variable so that parsing can continue. All
173 // uses of undefined variables, whether string or numeric, are then diagnosed
174 // in printSubstitutions() after failing to match.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000175 auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
Thomas Preud'hommefe7ac172019-07-05 16:25:33 +0000176 FileCheckNumericVariable *NumericVariable;
177 if (VarTableIter != Context->GlobalNumericVariableTable.end())
178 NumericVariable = VarTableIter->second;
179 else {
180 NumericVariable = Context->makeNumericVariable(0, Name);
181 Context->GlobalNumericVariableTable[Name] = NumericVariable;
182 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000183
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000184 if (!IsPseudo && NumericVariable->getDefLineNumber() == LineNumber)
185 return FileCheckErrorDiagnostic::get(
186 SM, Name,
187 "numeric variable '" + Name + "' defined on the same line as used");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000188
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000189 return llvm::make_unique<FileCheckNumericVariableUse>(Name, NumericVariable);
190}
191
192Expected<std::unique_ptr<FileCheckExpressionAST>>
193FileCheckPattern::parseNumericOperand(StringRef &Expr, AllowedOperand AO,
194 const SourceMgr &SM) const {
195 if (AO == AllowedOperand::LineVar || AO == AllowedOperand::Any) {
196 // Try to parse as a numeric variable use.
197 Expected<FileCheckPattern::VariableProperties> ParseVarResult =
198 parseVariable(Expr, SM);
199 if (ParseVarResult)
200 return parseNumericVariableUse(ParseVarResult->Name,
201 ParseVarResult->IsPseudo, SM);
202 if (AO == AllowedOperand::LineVar)
203 return ParseVarResult.takeError();
204 // Ignore the error and retry parsing as a literal.
205 consumeError(ParseVarResult.takeError());
206 }
207
208 // Otherwise, parse it as a literal.
209 uint64_t LiteralValue;
210 if (!Expr.consumeInteger(/*Radix=*/10, LiteralValue))
211 return llvm::make_unique<FileCheckExpressionLiteral>(LiteralValue);
212
213 return FileCheckErrorDiagnostic::get(SM, Expr,
214 "invalid operand format '" + Expr + "'");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000215}
216
217static uint64_t add(uint64_t LeftOp, uint64_t RightOp) {
218 return LeftOp + RightOp;
219}
220
221static uint64_t sub(uint64_t LeftOp, uint64_t RightOp) {
222 return LeftOp - RightOp;
223}
224
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000225Expected<std::unique_ptr<FileCheckExpressionAST>>
226FileCheckPattern::parseBinop(StringRef &Expr,
227 std::unique_ptr<FileCheckExpressionAST> LeftOp,
228 bool IsLegacyLineExpr, const SourceMgr &SM) const {
229 Expr = Expr.ltrim(SpaceChars);
230 if (Expr.empty())
231 return std::move(LeftOp);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000232
233 // Check if this is a supported operation and select a function to perform
234 // it.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000235 SMLoc OpLoc = SMLoc::getFromPointer(Expr.data());
236 char Operator = popFront(Expr);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000237 binop_eval_t EvalBinop;
238 switch (Operator) {
239 case '+':
240 EvalBinop = add;
241 break;
242 case '-':
243 EvalBinop = sub;
244 break;
245 default:
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000246 return FileCheckErrorDiagnostic::get(
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000247 SM, OpLoc, Twine("unsupported operation '") + Twine(Operator) + "'");
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000248 }
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000249
250 // Parse right operand.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000251 Expr = Expr.ltrim(SpaceChars);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000252 if (Expr.empty())
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000253 return FileCheckErrorDiagnostic::get(SM, Expr,
254 "missing operand in expression");
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000255 // The second operand in a legacy @LINE expression is always a literal.
256 AllowedOperand AO =
257 IsLegacyLineExpr ? AllowedOperand::Literal : AllowedOperand::Any;
258 Expected<std::unique_ptr<FileCheckExpressionAST>> RightOpResult =
259 parseNumericOperand(Expr, AO, SM);
260 if (!RightOpResult)
261 return RightOpResult;
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000262
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000263 Expr = Expr.ltrim(SpaceChars);
264 return llvm::make_unique<FileCheckASTBinop>(EvalBinop, std::move(LeftOp),
265 std::move(*RightOpResult));
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000266}
267
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000268Expected<std::unique_ptr<FileCheckExpressionAST>>
269FileCheckPattern::parseNumericSubstitutionBlock(
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000270 StringRef Expr,
271 Optional<FileCheckNumericVariable *> &DefinedNumericVariable,
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000272 bool IsLegacyLineExpr, const SourceMgr &SM) const {
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000273 // Parse the numeric variable definition.
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000274 DefinedNumericVariable = None;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000275 size_t DefEnd = Expr.find(':');
276 if (DefEnd != StringRef::npos) {
277 StringRef DefExpr = Expr.substr(0, DefEnd);
Thomas Preud'homme28196a52019-07-05 12:01:06 +0000278 StringRef UseExpr = Expr.substr(DefEnd + 1);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000279
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000280 UseExpr = UseExpr.ltrim(SpaceChars);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000281 if (!UseExpr.empty())
282 return FileCheckErrorDiagnostic::get(
283 SM, UseExpr,
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000284 "unexpected string after variable definition: '" + UseExpr + "'");
Thomas Preud'homme28196a52019-07-05 12:01:06 +0000285
286 DefExpr = DefExpr.ltrim(SpaceChars);
Thomas Preud'homme56f63082019-07-05 16:25:46 +0000287 Expected<FileCheckNumericVariable *> ParseResult =
288 parseNumericVariableDefinition(DefExpr, Context, LineNumber, SM);
289 if (!ParseResult)
290 return ParseResult.takeError();
291 DefinedNumericVariable = *ParseResult;
Thomas Preud'homme28196a52019-07-05 12:01:06 +0000292
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000293 return nullptr;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000294 }
295
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000296 // Parse the expression itself.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000297 Expr = Expr.ltrim(SpaceChars);
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000298 // The first operand in a legacy @LINE expression is always the @LINE pseudo
299 // variable.
300 AllowedOperand AO =
301 IsLegacyLineExpr ? AllowedOperand::LineVar : AllowedOperand::Any;
302 Expected<std::unique_ptr<FileCheckExpressionAST>> ParseResult =
303 parseNumericOperand(Expr, AO, SM);
304 while (ParseResult && !Expr.empty()) {
305 ParseResult =
306 parseBinop(Expr, std::move(*ParseResult), IsLegacyLineExpr, SM);
307 // Legacy @LINE expressions only allow 2 operands.
308 if (ParseResult && IsLegacyLineExpr && !Expr.empty())
309 return FileCheckErrorDiagnostic::get(
310 SM, Expr,
311 "unexpected characters at end of expression '" + Expr + "'");
312 }
313 if (!ParseResult)
314 return ParseResult;
315 return std::move(*ParseResult);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000316}
317
318bool FileCheckPattern::parsePattern(StringRef PatternStr, StringRef Prefix,
319 SourceMgr &SM,
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000320 const FileCheckRequest &Req) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000321 bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
322
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000323 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
324
325 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
326 // Ignore trailing whitespace.
327 while (!PatternStr.empty() &&
328 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
329 PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
330
331 // Check that there is something on the line.
332 if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
333 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
334 "found empty check string with prefix '" + Prefix + ":'");
335 return true;
336 }
337
338 if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
339 SM.PrintMessage(
340 PatternLoc, SourceMgr::DK_Error,
341 "found non-empty check string for empty check with prefix '" + Prefix +
342 ":'");
343 return true;
344 }
345
346 if (CheckTy == Check::CheckEmpty) {
347 RegExStr = "(\n$)";
348 return false;
349 }
350
351 // Check to see if this is a fixed string, or if it has regex pieces.
352 if (!MatchFullLinesHere &&
353 (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
354 PatternStr.find("[[") == StringRef::npos))) {
355 FixedStr = PatternStr;
356 return false;
357 }
358
359 if (MatchFullLinesHere) {
360 RegExStr += '^';
361 if (!Req.NoCanonicalizeWhiteSpace)
362 RegExStr += " *";
363 }
364
365 // Paren value #0 is for the fully matched string. Any new parenthesized
366 // values add from there.
367 unsigned CurParen = 1;
368
369 // Otherwise, there is at least one regex piece. Build up the regex pattern
370 // by escaping scary characters in fixed strings, building up one big regex.
371 while (!PatternStr.empty()) {
372 // RegEx matches.
373 if (PatternStr.startswith("{{")) {
374 // This is the start of a regex match. Scan for the }}.
375 size_t End = PatternStr.find("}}");
376 if (End == StringRef::npos) {
377 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
378 SourceMgr::DK_Error,
379 "found start of regex string with no end '}}'");
380 return true;
381 }
382
383 // Enclose {{}} patterns in parens just like [[]] even though we're not
384 // capturing the result for any purpose. This is required in case the
385 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
386 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
387 RegExStr += '(';
388 ++CurParen;
389
390 if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
391 return true;
392 RegExStr += ')';
393
394 PatternStr = PatternStr.substr(End + 2);
395 continue;
396 }
397
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000398 // String and numeric substitution blocks. String substitution blocks come
399 // in two forms: [[foo:.*]] and [[foo]]. The former matches .* (or some
400 // other regex) and assigns it to the string variable 'foo'. The latter
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000401 // substitutes foo's value. Numeric substitution blocks work the same way
402 // as string ones, but start with a '#' sign after the double brackets.
403 // Both string and numeric variable names must satisfy the regular
404 // expression "[a-zA-Z_][0-9a-zA-Z_]*" to be valid, as this helps catch
405 // some common errors.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000406 if (PatternStr.startswith("[[")) {
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000407 StringRef UnparsedPatternStr = PatternStr.substr(2);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000408 // Find the closing bracket pair ending the match. End is going to be an
409 // offset relative to the beginning of the match string.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000410 size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
411 StringRef MatchStr = UnparsedPatternStr.substr(0, End);
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000412 bool IsNumBlock = MatchStr.consume_front("#");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000413
414 if (End == StringRef::npos) {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000415 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
416 SourceMgr::DK_Error,
417 "Invalid substitution block, no ]] found");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000418 return true;
419 }
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000420 // Strip the substitution block we are parsing. End points to the start
421 // of the "]]" closing the expression so account for it in computing the
422 // index of the first unparsed character.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000423 PatternStr = UnparsedPatternStr.substr(End + 2);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000424
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000425 bool IsDefinition = false;
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000426 // Whether the substitution block is a legacy use of @LINE with string
427 // substitution block syntax.
428 bool IsLegacyLineExpr = false;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000429 StringRef DefName;
430 StringRef SubstStr;
431 StringRef MatchRegexp;
432 size_t SubstInsertIdx = RegExStr.size();
433
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000434 // Parse string variable or legacy @LINE expression.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000435 if (!IsNumBlock) {
436 size_t VarEndIdx = MatchStr.find(":");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000437 size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
438 if (SpacePos != StringRef::npos) {
439 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
440 SourceMgr::DK_Error, "unexpected whitespace");
441 return true;
442 }
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000443
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000444 // Get the name (e.g. "foo") and verify it is well formed.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000445 StringRef OrigMatchStr = MatchStr;
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000446 Expected<FileCheckPattern::VariableProperties> ParseVarResult =
447 parseVariable(MatchStr, SM);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000448 if (!ParseVarResult) {
449 logAllUnhandledErrors(ParseVarResult.takeError(), errs());
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000450 return true;
451 }
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000452 StringRef Name = ParseVarResult->Name;
453 bool IsPseudo = ParseVarResult->IsPseudo;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000454
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000455 IsDefinition = (VarEndIdx != StringRef::npos);
456 if (IsDefinition) {
457 if ((IsPseudo || !MatchStr.consume_front(":"))) {
458 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
459 SourceMgr::DK_Error,
460 "invalid name in string variable definition");
461 return true;
462 }
463
464 // Detect collisions between string and numeric variables when the
465 // former is created later than the latter.
466 if (Context->GlobalNumericVariableTable.find(Name) !=
467 Context->GlobalNumericVariableTable.end()) {
468 SM.PrintMessage(
469 SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
470 "numeric variable with name '" + Name + "' already exists");
471 return true;
472 }
473 DefName = Name;
474 MatchRegexp = MatchStr;
475 } else {
476 if (IsPseudo) {
477 MatchStr = OrigMatchStr;
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000478 IsLegacyLineExpr = IsNumBlock = true;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000479 } else
480 SubstStr = Name;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000481 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000482 }
483
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000484 // Parse numeric substitution block.
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000485 std::unique_ptr<FileCheckExpressionAST> ExpressionAST;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000486 Optional<FileCheckNumericVariable *> DefinedNumericVariable;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000487 if (IsNumBlock) {
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000488 Expected<std::unique_ptr<FileCheckExpressionAST>> ParseResult =
489 parseNumericSubstitutionBlock(MatchStr, DefinedNumericVariable,
490 IsLegacyLineExpr, SM);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000491 if (!ParseResult) {
492 logAllUnhandledErrors(ParseResult.takeError(), errs());
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000493 return true;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000494 }
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000495 ExpressionAST = std::move(*ParseResult);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000496 if (DefinedNumericVariable) {
497 IsDefinition = true;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000498 DefName = (*DefinedNumericVariable)->getName();
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000499 MatchRegexp = StringRef("[0-9]+");
500 } else
501 SubstStr = MatchStr;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000502 }
503
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000504 // Handle substitutions: [[foo]] and [[#<foo expr>]].
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000505 if (!IsDefinition) {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000506 // Handle substitution of string variables that were defined earlier on
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000507 // the same line by emitting a backreference. Expressions do not
508 // support substituting a numeric variable defined on the same line.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000509 if (!IsNumBlock && VariableDefs.find(SubstStr) != VariableDefs.end()) {
510 unsigned CaptureParenGroup = VariableDefs[SubstStr];
511 if (CaptureParenGroup < 1 || CaptureParenGroup > 9) {
512 SM.PrintMessage(SMLoc::getFromPointer(SubstStr.data()),
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000513 SourceMgr::DK_Error,
514 "Can't back-reference more than 9 variables");
515 return true;
516 }
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000517 AddBackrefToRegEx(CaptureParenGroup);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000518 } else {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000519 // Handle substitution of string variables ([[<var>]]) defined in
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000520 // previous CHECK patterns, and substitution of expressions.
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000521 FileCheckSubstitution *Substitution =
522 IsNumBlock
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000523 ? Context->makeNumericSubstitution(
524 SubstStr, std::move(ExpressionAST), SubstInsertIdx)
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000525 : Context->makeStringSubstitution(SubstStr, SubstInsertIdx);
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000526 Substitutions.push_back(Substitution);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000527 }
528 continue;
529 }
530
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000531 // Handle variable definitions: [[<def>:(...)]] and
532 // [[#(...)<def>:(...)]].
533 if (IsNumBlock) {
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000534 FileCheckNumericVariableMatch NumericVariableDefinition = {
535 *DefinedNumericVariable, CurParen};
536 NumericVariableDefs[DefName] = NumericVariableDefinition;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000537 // This store is done here rather than in match() to allow
538 // parseNumericVariableUse() to get the pointer to the class instance
539 // of the right variable definition corresponding to a given numeric
540 // variable use.
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000541 Context->GlobalNumericVariableTable[DefName] = *DefinedNumericVariable;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000542 } else {
543 VariableDefs[DefName] = CurParen;
544 // Mark the string variable as defined to detect collisions between
545 // string and numeric variables in parseNumericVariableUse() and
546 // DefineCmdlineVariables() when the latter is created later than the
547 // former. We cannot reuse GlobalVariableTable for this by populating
548 // it with an empty string since we would then lose the ability to
549 // detect the use of an undefined variable in match().
550 Context->DefinedVariableTable[DefName] = true;
551 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000552 RegExStr += '(';
553 ++CurParen;
554
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000555 if (AddRegExToRegEx(MatchRegexp, CurParen, SM))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000556 return true;
557
558 RegExStr += ')';
559 }
560
561 // Handle fixed string matches.
562 // Find the end, which is the start of the next regex.
563 size_t FixedMatchEnd = PatternStr.find("{{");
564 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
565 RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
566 PatternStr = PatternStr.substr(FixedMatchEnd);
567 }
568
569 if (MatchFullLinesHere) {
570 if (!Req.NoCanonicalizeWhiteSpace)
571 RegExStr += " *";
572 RegExStr += '$';
573 }
574
575 return false;
576}
577
578bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
579 Regex R(RS);
580 std::string Error;
581 if (!R.isValid(Error)) {
582 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
583 "invalid regex: " + Error);
584 return true;
585 }
586
587 RegExStr += RS.str();
588 CurParen += R.getNumMatches();
589 return false;
590}
591
592void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
593 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
594 std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
595 RegExStr += Backref;
596}
597
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000598Expected<size_t> FileCheckPattern::match(StringRef Buffer, size_t &MatchLen,
599 const SourceMgr &SM) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000600 // If this is the EOF pattern, match it immediately.
601 if (CheckTy == Check::CheckEOF) {
602 MatchLen = 0;
603 return Buffer.size();
604 }
605
606 // If this is a fixed string pattern, just match it now.
607 if (!FixedStr.empty()) {
608 MatchLen = FixedStr.size();
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000609 size_t Pos = Buffer.find(FixedStr);
610 if (Pos == StringRef::npos)
611 return make_error<FileCheckNotFoundError>();
612 return Pos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000613 }
614
615 // Regex match.
616
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000617 // If there are substitutions, we need to create a temporary string with the
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000618 // actual value.
619 StringRef RegExToMatch = RegExStr;
620 std::string TmpStr;
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000621 if (!Substitutions.empty()) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000622 TmpStr = RegExStr;
Thomas Preud'homme56f63082019-07-05 16:25:46 +0000623 Context->LineVariable->setValue(LineNumber);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000624
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000625 size_t InsertOffset = 0;
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000626 // Substitute all string variables and expressions whose values are only
627 // now known. Use of string variables defined on the same line are handled
628 // by back-references.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000629 for (const auto &Substitution : Substitutions) {
630 // Substitute and check for failure (e.g. use of undefined variable).
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000631 Expected<std::string> Value = Substitution->getResult();
Thomas Preud'hommef6ea43b2019-07-10 12:49:17 +0000632 if (!Value) {
633 Context->LineVariable->clearValue();
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000634 return Value.takeError();
Thomas Preud'hommef6ea43b2019-07-10 12:49:17 +0000635 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000636
637 // Plop it into the regex at the adjusted offset.
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000638 TmpStr.insert(TmpStr.begin() + Substitution->getIndex() + InsertOffset,
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000639 Value->begin(), Value->end());
640 InsertOffset += Value->size();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000641 }
642
643 // Match the newly constructed regex.
644 RegExToMatch = TmpStr;
Thomas Preud'homme56f63082019-07-05 16:25:46 +0000645 Context->LineVariable->clearValue();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000646 }
647
648 SmallVector<StringRef, 4> MatchInfo;
649 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000650 return make_error<FileCheckNotFoundError>();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000651
652 // Successful regex match.
653 assert(!MatchInfo.empty() && "Didn't get any match");
654 StringRef FullMatch = MatchInfo[0];
655
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000656 // If this defines any string variables, remember their values.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000657 for (const auto &VariableDef : VariableDefs) {
658 assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000659 Context->GlobalVariableTable[VariableDef.first] =
660 MatchInfo[VariableDef.second];
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000661 }
662
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000663 // If this defines any numeric variables, remember their values.
664 for (const auto &NumericVariableDef : NumericVariableDefs) {
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000665 const FileCheckNumericVariableMatch &NumericVariableMatch =
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000666 NumericVariableDef.getValue();
667 unsigned CaptureParenGroup = NumericVariableMatch.CaptureParenGroup;
668 assert(CaptureParenGroup < MatchInfo.size() && "Internal paren error");
669 FileCheckNumericVariable *DefinedNumericVariable =
670 NumericVariableMatch.DefinedNumericVariable;
671
672 StringRef MatchedValue = MatchInfo[CaptureParenGroup];
673 uint64_t Val;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000674 if (MatchedValue.getAsInteger(10, Val))
675 return FileCheckErrorDiagnostic::get(SM, MatchedValue,
676 "Unable to represent numeric value");
Thomas Preud'homme2bf04f22019-07-10 12:49:28 +0000677 DefinedNumericVariable->setValue(Val);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000678 }
679
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000680 // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
681 // the required preceding newline, which is consumed by the pattern in the
682 // case of CHECK-EMPTY but not CHECK-NEXT.
683 size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
684 MatchLen = FullMatch.size() - MatchStartSkip;
685 return FullMatch.data() - Buffer.data() + MatchStartSkip;
686}
687
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000688unsigned FileCheckPattern::computeMatchDistance(StringRef Buffer) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000689 // Just compute the number of matching characters. For regular expressions, we
690 // just compare against the regex itself and hope for the best.
691 //
692 // FIXME: One easy improvement here is have the regex lib generate a single
693 // example regular expression which matches, and use that as the example
694 // string.
695 StringRef ExampleString(FixedStr);
696 if (ExampleString.empty())
697 ExampleString = RegExStr;
698
699 // Only compare up to the first line in the buffer, or the string size.
700 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
701 BufferPrefix = BufferPrefix.split('\n').first;
702 return BufferPrefix.edit_distance(ExampleString);
703}
704
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000705void FileCheckPattern::printSubstitutions(const SourceMgr &SM, StringRef Buffer,
706 SMRange MatchRange) const {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000707 // Print what we know about substitutions.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000708 if (!Substitutions.empty()) {
709 for (const auto &Substitution : Substitutions) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000710 SmallString<256> Msg;
711 raw_svector_ostream OS(Msg);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000712 Expected<std::string> MatchedValue = Substitution->getResult();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000713
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000714 // Substitution failed or is not known at match time, print the undefined
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000715 // variables it uses.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000716 if (!MatchedValue) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000717 bool UndefSeen = false;
718 handleAllErrors(MatchedValue.takeError(),
719 [](const FileCheckNotFoundError &E) {},
Thomas Preud'hommea188ad22019-07-05 12:00:56 +0000720 // Handled in PrintNoMatch().
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000721 [](const FileCheckErrorDiagnostic &E) {},
722 [&](const FileCheckUndefVarError &E) {
723 if (!UndefSeen) {
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000724 OS << "uses undefined variable(s):";
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000725 UndefSeen = true;
726 }
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000727 OS << " ";
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000728 E.log(OS);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000729 });
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000730 } else {
731 // Substitution succeeded. Print substituted value.
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000732 OS << "with \"";
733 OS.write_escaped(Substitution->getFromString()) << "\" equal to \"";
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000734 OS.write_escaped(*MatchedValue) << "\"";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000735 }
736
737 if (MatchRange.isValid())
738 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
739 {MatchRange});
740 else
741 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
742 SourceMgr::DK_Note, OS.str());
743 }
744 }
745}
746
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000747static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
748 const SourceMgr &SM, SMLoc Loc,
749 Check::FileCheckType CheckTy,
750 StringRef Buffer, size_t Pos, size_t Len,
Joel E. Denny7df86962018-12-18 00:03:03 +0000751 std::vector<FileCheckDiag> *Diags,
752 bool AdjustPrevDiag = false) {
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000753 SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
754 SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
755 SMRange Range(Start, End);
Joel E. Denny96f0e842018-12-18 00:03:36 +0000756 if (Diags) {
Joel E. Denny7df86962018-12-18 00:03:03 +0000757 if (AdjustPrevDiag)
758 Diags->rbegin()->MatchTy = MatchTy;
759 else
760 Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
761 }
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000762 return Range;
763}
764
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000765void FileCheckPattern::printFuzzyMatch(
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000766 const SourceMgr &SM, StringRef Buffer,
Joel E. Denny2c007c82018-12-18 00:02:04 +0000767 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000768 // Attempt to find the closest/best fuzzy match. Usually an error happens
769 // because some string in the output didn't exactly match. In these cases, we
770 // would like to show the user a best guess at what "should have" matched, to
771 // save them having to actually check the input manually.
772 size_t NumLinesForward = 0;
773 size_t Best = StringRef::npos;
774 double BestQuality = 0;
775
776 // Use an arbitrary 4k limit on how far we will search.
777 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
778 if (Buffer[i] == '\n')
779 ++NumLinesForward;
780
781 // Patterns have leading whitespace stripped, so skip whitespace when
782 // looking for something which looks like a pattern.
783 if (Buffer[i] == ' ' || Buffer[i] == '\t')
784 continue;
785
786 // Compute the "quality" of this match as an arbitrary combination of the
787 // match distance and the number of lines skipped to get to this match.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000788 unsigned Distance = computeMatchDistance(Buffer.substr(i));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000789 double Quality = Distance + (NumLinesForward / 100.);
790
791 if (Quality < BestQuality || Best == StringRef::npos) {
792 Best = i;
793 BestQuality = Quality;
794 }
795 }
796
797 // Print the "possible intended match here" line if we found something
798 // reasonable and not equal to what we showed in the "scanning from here"
799 // line.
800 if (Best && Best != StringRef::npos && BestQuality < 50) {
Joel E. Denny2c007c82018-12-18 00:02:04 +0000801 SMRange MatchRange =
802 ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
803 getCheckTy(), Buffer, Best, 0, Diags);
804 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
805 "possible intended match here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000806
807 // FIXME: If we wanted to be really friendly we would show why the match
808 // failed, as it can be hard to spot simple one character differences.
809 }
810}
811
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000812Expected<StringRef>
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000813FileCheckPatternContext::getPatternVarValue(StringRef VarName) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000814 auto VarIter = GlobalVariableTable.find(VarName);
815 if (VarIter == GlobalVariableTable.end())
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000816 return make_error<FileCheckUndefVarError>(VarName);
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000817
818 return VarIter->second;
819}
820
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000821template <class... Types>
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000822FileCheckNumericVariable *
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000823FileCheckPatternContext::makeNumericVariable(Types... args) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000824 NumericVariables.push_back(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000825 llvm::make_unique<FileCheckNumericVariable>(args...));
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000826 return NumericVariables.back().get();
827}
828
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000829FileCheckSubstitution *
830FileCheckPatternContext::makeStringSubstitution(StringRef VarName,
831 size_t InsertIdx) {
832 Substitutions.push_back(
833 llvm::make_unique<FileCheckStringSubstitution>(this, VarName, InsertIdx));
834 return Substitutions.back().get();
835}
836
837FileCheckSubstitution *FileCheckPatternContext::makeNumericSubstitution(
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000838 StringRef ExpressionStr,
839 std::unique_ptr<FileCheckExpressionAST> ExpressionAST, size_t InsertIdx) {
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000840 Substitutions.push_back(llvm::make_unique<FileCheckNumericSubstitution>(
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +0000841 this, ExpressionStr, std::move(ExpressionAST), InsertIdx));
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000842 return Substitutions.back().get();
843}
844
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000845size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
846 // Offset keeps track of the current offset within the input Str
847 size_t Offset = 0;
848 // [...] Nesting depth
849 size_t BracketDepth = 0;
850
851 while (!Str.empty()) {
852 if (Str.startswith("]]") && BracketDepth == 0)
853 return Offset;
854 if (Str[0] == '\\') {
855 // Backslash escapes the next char within regexes, so skip them both.
856 Str = Str.substr(2);
857 Offset += 2;
858 } else {
859 switch (Str[0]) {
860 default:
861 break;
862 case '[':
863 BracketDepth++;
864 break;
865 case ']':
866 if (BracketDepth == 0) {
867 SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
868 SourceMgr::DK_Error,
869 "missing closing \"]\" for regex variable");
870 exit(1);
871 }
872 BracketDepth--;
873 break;
874 }
875 Str = Str.substr(1);
876 Offset++;
877 }
878 }
879
880 return StringRef::npos;
881}
882
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +0000883StringRef FileCheck::CanonicalizeFile(MemoryBuffer &MB,
884 SmallVectorImpl<char> &OutputBuffer) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000885 OutputBuffer.reserve(MB.getBufferSize());
886
887 for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
888 Ptr != End; ++Ptr) {
889 // Eliminate trailing dosish \r.
890 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
891 continue;
892 }
893
894 // If current char is not a horizontal whitespace or if horizontal
895 // whitespace canonicalization is disabled, dump it to output as is.
896 if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
897 OutputBuffer.push_back(*Ptr);
898 continue;
899 }
900
901 // Otherwise, add one space and advance over neighboring space.
902 OutputBuffer.push_back(' ');
903 while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
904 ++Ptr;
905 }
906
907 // Add a null byte and then return all but that byte.
908 OutputBuffer.push_back('\0');
909 return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
910}
911
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000912FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
913 const Check::FileCheckType &CheckTy,
914 SMLoc CheckLoc, MatchType MatchTy,
915 SMRange InputRange)
916 : CheckTy(CheckTy), MatchTy(MatchTy) {
917 auto Start = SM.getLineAndColumn(InputRange.Start);
918 auto End = SM.getLineAndColumn(InputRange.End);
919 InputStartLine = Start.first;
920 InputStartCol = Start.second;
921 InputEndLine = End.first;
922 InputEndCol = End.second;
923 Start = SM.getLineAndColumn(CheckLoc);
924 CheckLine = Start.first;
925 CheckCol = Start.second;
926}
927
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000928static bool IsPartOfWord(char c) {
929 return (isalnum(c) || c == '-' || c == '_');
930}
931
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000932Check::FileCheckType &Check::FileCheckType::setCount(int C) {
Fedor Sergeev8477a3e2018-11-13 01:09:53 +0000933 assert(Count > 0 && "zero and negative counts are not supported");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000934 assert((C == 1 || Kind == CheckPlain) &&
935 "count supported only for plain CHECK directives");
936 Count = C;
937 return *this;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000938}
939
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000940std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
941 switch (Kind) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000942 case Check::CheckNone:
943 return "invalid";
944 case Check::CheckPlain:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000945 if (Count > 1)
946 return Prefix.str() + "-COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000947 return Prefix;
948 case Check::CheckNext:
949 return Prefix.str() + "-NEXT";
950 case Check::CheckSame:
951 return Prefix.str() + "-SAME";
952 case Check::CheckNot:
953 return Prefix.str() + "-NOT";
954 case Check::CheckDAG:
955 return Prefix.str() + "-DAG";
956 case Check::CheckLabel:
957 return Prefix.str() + "-LABEL";
958 case Check::CheckEmpty:
959 return Prefix.str() + "-EMPTY";
960 case Check::CheckEOF:
961 return "implicit EOF";
962 case Check::CheckBadNot:
963 return "bad NOT";
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000964 case Check::CheckBadCount:
965 return "bad COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000966 }
967 llvm_unreachable("unknown FileCheckType");
968}
969
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000970static std::pair<Check::FileCheckType, StringRef>
971FindCheckType(StringRef Buffer, StringRef Prefix) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000972 if (Buffer.size() <= Prefix.size())
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000973 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000974
975 char NextChar = Buffer[Prefix.size()];
976
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000977 StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000978 // Verify that the : is present after the prefix.
979 if (NextChar == ':')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000980 return {Check::CheckPlain, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000981
982 if (NextChar != '-')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000983 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000984
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000985 if (Rest.consume_front("COUNT-")) {
986 int64_t Count;
987 if (Rest.consumeInteger(10, Count))
988 // Error happened in parsing integer.
989 return {Check::CheckBadCount, Rest};
990 if (Count <= 0 || Count > INT32_MAX)
991 return {Check::CheckBadCount, Rest};
992 if (!Rest.consume_front(":"))
993 return {Check::CheckBadCount, Rest};
994 return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
995 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000996
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000997 if (Rest.consume_front("NEXT:"))
998 return {Check::CheckNext, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000999
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001000 if (Rest.consume_front("SAME:"))
1001 return {Check::CheckSame, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001002
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001003 if (Rest.consume_front("NOT:"))
1004 return {Check::CheckNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001005
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001006 if (Rest.consume_front("DAG:"))
1007 return {Check::CheckDAG, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001008
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001009 if (Rest.consume_front("LABEL:"))
1010 return {Check::CheckLabel, Rest};
1011
1012 if (Rest.consume_front("EMPTY:"))
1013 return {Check::CheckEmpty, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001014
1015 // You can't combine -NOT with another suffix.
1016 if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
1017 Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
1018 Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
1019 Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001020 return {Check::CheckBadNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001021
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001022 return {Check::CheckNone, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001023}
1024
1025// From the given position, find the next character after the word.
1026static size_t SkipWord(StringRef Str, size_t Loc) {
1027 while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
1028 ++Loc;
1029 return Loc;
1030}
1031
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +00001032/// Searches the buffer for the first prefix in the prefix regular expression.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001033///
1034/// This searches the buffer using the provided regular expression, however it
1035/// enforces constraints beyond that:
1036/// 1) The found prefix must not be a suffix of something that looks like
1037/// a valid prefix.
1038/// 2) The found prefix must be followed by a valid check type suffix using \c
1039/// FindCheckType above.
1040///
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +00001041/// \returns a pair of StringRefs into the Buffer, which combines:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001042/// - the first match of the regular expression to satisfy these two is
1043/// returned,
1044/// otherwise an empty StringRef is returned to indicate failure.
1045/// - buffer rewound to the location right after parsed suffix, for parsing
1046/// to continue from
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001047///
1048/// If this routine returns a valid prefix, it will also shrink \p Buffer to
1049/// start at the beginning of the returned prefix, increment \p LineNumber for
1050/// each new line consumed from \p Buffer, and set \p CheckTy to the type of
1051/// check found by examining the suffix.
1052///
1053/// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
1054/// is unspecified.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001055static std::pair<StringRef, StringRef>
1056FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer,
1057 unsigned &LineNumber, Check::FileCheckType &CheckTy) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001058 SmallVector<StringRef, 2> Matches;
1059
1060 while (!Buffer.empty()) {
1061 // Find the first (longest) match using the RE.
1062 if (!PrefixRE.match(Buffer, &Matches))
1063 // No match at all, bail.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001064 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001065
1066 StringRef Prefix = Matches[0];
1067 Matches.clear();
1068
1069 assert(Prefix.data() >= Buffer.data() &&
1070 Prefix.data() < Buffer.data() + Buffer.size() &&
1071 "Prefix doesn't start inside of buffer!");
1072 size_t Loc = Prefix.data() - Buffer.data();
1073 StringRef Skipped = Buffer.substr(0, Loc);
1074 Buffer = Buffer.drop_front(Loc);
1075 LineNumber += Skipped.count('\n');
1076
1077 // Check that the matched prefix isn't a suffix of some other check-like
1078 // word.
1079 // FIXME: This is a very ad-hoc check. it would be better handled in some
1080 // other way. Among other things it seems hard to distinguish between
1081 // intentional and unintentional uses of this feature.
1082 if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
1083 // Now extract the type.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001084 StringRef AfterSuffix;
1085 std::tie(CheckTy, AfterSuffix) = FindCheckType(Buffer, Prefix);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001086
1087 // If we've found a valid check type for this prefix, we're done.
1088 if (CheckTy != Check::CheckNone)
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001089 return {Prefix, AfterSuffix};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001090 }
1091
1092 // If we didn't successfully find a prefix, we need to skip this invalid
1093 // prefix and continue scanning. We directly skip the prefix that was
1094 // matched and any additional parts of that check-like word.
1095 Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
1096 }
1097
1098 // We ran out of buffer while skipping partial matches so give up.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001099 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001100}
1101
Thomas Preud'homme56f63082019-07-05 16:25:46 +00001102void FileCheckPatternContext::createLineVariable() {
1103 assert(!LineVariable && "@LINE pseudo numeric variable already created");
1104 StringRef LineName = "@LINE";
1105 LineVariable = makeNumericVariable(0, LineName);
1106 GlobalNumericVariableTable[LineName] = LineVariable;
1107}
1108
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001109bool FileCheck::ReadCheckFile(SourceMgr &SM, StringRef Buffer, Regex &PrefixRE,
1110 std::vector<FileCheckString> &CheckStrings) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001111 Error DefineError =
1112 PatternContext.defineCmdlineVariables(Req.GlobalDefines, SM);
1113 if (DefineError) {
1114 logAllUnhandledErrors(std::move(DefineError), errs());
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001115 return true;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001116 }
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001117
Thomas Preud'homme56f63082019-07-05 16:25:46 +00001118 PatternContext.createLineVariable();
1119
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001120 std::vector<FileCheckPattern> ImplicitNegativeChecks;
1121 for (const auto &PatternString : Req.ImplicitCheckNot) {
1122 // Create a buffer with fake command line content in order to display the
1123 // command line option responsible for the specific implicit CHECK-NOT.
1124 std::string Prefix = "-implicit-check-not='";
1125 std::string Suffix = "'";
1126 std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
1127 Prefix + PatternString + Suffix, "command line");
1128
1129 StringRef PatternInBuffer =
1130 CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
1131 SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
1132
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001133 ImplicitNegativeChecks.push_back(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001134 FileCheckPattern(Check::CheckNot, &PatternContext, 0));
1135 ImplicitNegativeChecks.back().parsePattern(PatternInBuffer,
1136 "IMPLICIT-CHECK", SM, Req);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001137 }
1138
1139 std::vector<FileCheckPattern> DagNotMatches = ImplicitNegativeChecks;
1140
1141 // LineNumber keeps track of the line on which CheckPrefix instances are
1142 // found.
1143 unsigned LineNumber = 1;
1144
1145 while (1) {
1146 Check::FileCheckType CheckTy;
1147
1148 // See if a prefix occurs in the memory buffer.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001149 StringRef UsedPrefix;
1150 StringRef AfterSuffix;
1151 std::tie(UsedPrefix, AfterSuffix) =
1152 FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, CheckTy);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001153 if (UsedPrefix.empty())
1154 break;
1155 assert(UsedPrefix.data() == Buffer.data() &&
1156 "Failed to move Buffer's start forward, or pointed prefix outside "
1157 "of the buffer!");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001158 assert(AfterSuffix.data() >= Buffer.data() &&
1159 AfterSuffix.data() < Buffer.data() + Buffer.size() &&
1160 "Parsing after suffix doesn't start inside of buffer!");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001161
1162 // Location to use for error messages.
1163 const char *UsedPrefixStart = UsedPrefix.data();
1164
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001165 // Skip the buffer to the end of parsed suffix (or just prefix, if no good
1166 // suffix was processed).
1167 Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
1168 : AfterSuffix;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001169
1170 // Complain about useful-looking but unsupported suffixes.
1171 if (CheckTy == Check::CheckBadNot) {
1172 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
1173 "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
1174 return true;
1175 }
1176
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001177 // Complain about invalid count specification.
1178 if (CheckTy == Check::CheckBadCount) {
1179 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
1180 "invalid count in -COUNT specification on prefix '" +
1181 UsedPrefix + "'");
1182 return true;
1183 }
1184
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001185 // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
1186 // leading whitespace.
1187 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
1188 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
1189
1190 // Scan ahead to the end of line.
1191 size_t EOL = Buffer.find_first_of("\n\r");
1192
1193 // Remember the location of the start of the pattern, for diagnostics.
1194 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
1195
1196 // Parse the pattern.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001197 FileCheckPattern P(CheckTy, &PatternContext, LineNumber);
1198 if (P.parsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, Req))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001199 return true;
1200
1201 // Verify that CHECK-LABEL lines do not define or use variables
1202 if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
1203 SM.PrintMessage(
1204 SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
1205 "found '" + UsedPrefix + "-LABEL:'"
1206 " with variable definition or use");
1207 return true;
1208 }
1209
1210 Buffer = Buffer.substr(EOL);
1211
1212 // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
1213 if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
1214 CheckTy == Check::CheckEmpty) &&
1215 CheckStrings.empty()) {
1216 StringRef Type = CheckTy == Check::CheckNext
1217 ? "NEXT"
1218 : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
1219 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
1220 SourceMgr::DK_Error,
1221 "found '" + UsedPrefix + "-" + Type +
1222 "' without previous '" + UsedPrefix + ": line");
1223 return true;
1224 }
1225
1226 // Handle CHECK-DAG/-NOT.
1227 if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
1228 DagNotMatches.push_back(P);
1229 continue;
1230 }
1231
1232 // Okay, add the string we captured to the output vector and move on.
1233 CheckStrings.emplace_back(P, UsedPrefix, PatternLoc);
1234 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1235 DagNotMatches = ImplicitNegativeChecks;
1236 }
1237
1238 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
1239 // prefix as a filler for the error message.
1240 if (!DagNotMatches.empty()) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001241 CheckStrings.emplace_back(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001242 FileCheckPattern(Check::CheckEOF, &PatternContext, LineNumber + 1),
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001243 *Req.CheckPrefixes.begin(), SMLoc::getFromPointer(Buffer.data()));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001244 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1245 }
1246
1247 if (CheckStrings.empty()) {
1248 errs() << "error: no check strings found with prefix"
1249 << (Req.CheckPrefixes.size() > 1 ? "es " : " ");
1250 auto I = Req.CheckPrefixes.begin();
1251 auto E = Req.CheckPrefixes.end();
1252 if (I != E) {
1253 errs() << "\'" << *I << ":'";
1254 ++I;
1255 }
1256 for (; I != E; ++I)
1257 errs() << ", \'" << *I << ":'";
1258
1259 errs() << '\n';
1260 return true;
1261 }
1262
1263 return false;
1264}
1265
1266static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
1267 StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001268 int MatchedCount, StringRef Buffer, size_t MatchPos,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001269 size_t MatchLen, const FileCheckRequest &Req,
1270 std::vector<FileCheckDiag> *Diags) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001271 bool PrintDiag = true;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001272 if (ExpectedMatch) {
1273 if (!Req.Verbose)
1274 return;
1275 if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
1276 return;
Joel E. Denny352695c2019-01-22 21:41:42 +00001277 // Due to their verbosity, we don't print verbose diagnostics here if we're
1278 // gathering them for a different rendering, but we always print other
1279 // diagnostics.
1280 PrintDiag = !Diags;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001281 }
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001282 SMRange MatchRange = ProcessMatchResult(
Joel E. Dennye2afb612018-12-18 00:03:51 +00001283 ExpectedMatch ? FileCheckDiag::MatchFoundAndExpected
1284 : FileCheckDiag::MatchFoundButExcluded,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001285 SM, Loc, Pat.getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
Joel E. Denny352695c2019-01-22 21:41:42 +00001286 if (!PrintDiag)
1287 return;
1288
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001289 std::string Message = formatv("{0}: {1} string found in input",
1290 Pat.getCheckTy().getDescription(Prefix),
1291 (ExpectedMatch ? "expected" : "excluded"))
1292 .str();
1293 if (Pat.getCount() > 1)
1294 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
1295
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001296 SM.PrintMessage(
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001297 Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001298 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
1299 {MatchRange});
Thomas Preud'homme288ed912019-05-02 00:04:38 +00001300 Pat.printSubstitutions(SM, Buffer, MatchRange);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001301}
1302
1303static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001304 const FileCheckString &CheckStr, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001305 StringRef Buffer, size_t MatchPos, size_t MatchLen,
1306 FileCheckRequest &Req,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001307 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001308 PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001309 MatchedCount, Buffer, MatchPos, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001310}
1311
1312static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001313 StringRef Prefix, SMLoc Loc,
1314 const FileCheckPattern &Pat, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001315 StringRef Buffer, bool VerboseVerbose,
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001316 std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
1317 assert(MatchErrors && "Called on successful match");
Joel E. Denny352695c2019-01-22 21:41:42 +00001318 bool PrintDiag = true;
1319 if (!ExpectedMatch) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001320 if (!VerboseVerbose) {
1321 consumeError(std::move(MatchErrors));
Joel E. Denny352695c2019-01-22 21:41:42 +00001322 return;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001323 }
Joel E. Denny352695c2019-01-22 21:41:42 +00001324 // Due to their verbosity, we don't print verbose diagnostics here if we're
1325 // gathering them for a different rendering, but we always print other
1326 // diagnostics.
1327 PrintDiag = !Diags;
1328 }
1329
1330 // If the current position is at the end of a line, advance to the start of
1331 // the next line.
1332 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
1333 SMRange SearchRange = ProcessMatchResult(
1334 ExpectedMatch ? FileCheckDiag::MatchNoneButExpected
1335 : FileCheckDiag::MatchNoneAndExcluded,
1336 SM, Loc, Pat.getCheckTy(), Buffer, 0, Buffer.size(), Diags);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001337 if (!PrintDiag) {
1338 consumeError(std::move(MatchErrors));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001339 return;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001340 }
1341
1342 MatchErrors =
1343 handleErrors(std::move(MatchErrors),
1344 [](const FileCheckErrorDiagnostic &E) { E.log(errs()); });
1345
1346 // No problem matching the string per se.
1347 if (!MatchErrors)
1348 return;
1349 consumeError(std::move(MatchErrors));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001350
Joel E. Denny352695c2019-01-22 21:41:42 +00001351 // Print "not found" diagnostic.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001352 std::string Message = formatv("{0}: {1} string not found in input",
1353 Pat.getCheckTy().getDescription(Prefix),
1354 (ExpectedMatch ? "expected" : "excluded"))
1355 .str();
1356 if (Pat.getCount() > 1)
1357 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001358 SM.PrintMessage(
1359 Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001360
Joel E. Denny352695c2019-01-22 21:41:42 +00001361 // Print the "scanning from here" line.
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001362 SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001363
1364 // Allow the pattern to print additional information if desired.
Thomas Preud'homme288ed912019-05-02 00:04:38 +00001365 Pat.printSubstitutions(SM, Buffer);
Joel E. Denny96f0e842018-12-18 00:03:36 +00001366
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001367 if (ExpectedMatch)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001368 Pat.printFuzzyMatch(SM, Buffer, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001369}
1370
1371static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001372 const FileCheckString &CheckStr, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001373 StringRef Buffer, bool VerboseVerbose,
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001374 std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001375 PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001376 MatchedCount, Buffer, VerboseVerbose, Diags,
1377 std::move(MatchErrors));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001378}
1379
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +00001380/// Counts the number of newlines in the specified range.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001381static unsigned CountNumNewlinesBetween(StringRef Range,
1382 const char *&FirstNewLine) {
1383 unsigned NumNewLines = 0;
1384 while (1) {
1385 // Scan for newline.
1386 Range = Range.substr(Range.find_first_of("\n\r"));
1387 if (Range.empty())
1388 return NumNewLines;
1389
1390 ++NumNewLines;
1391
1392 // Handle \n\r and \r\n as a single newline.
1393 if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
1394 (Range[0] != Range[1]))
1395 Range = Range.substr(1);
1396 Range = Range.substr(1);
1397
1398 if (NumNewLines == 1)
1399 FirstNewLine = Range.begin();
1400 }
1401}
1402
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001403size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001404 bool IsLabelScanMode, size_t &MatchLen,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001405 FileCheckRequest &Req,
1406 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001407 size_t LastPos = 0;
1408 std::vector<const FileCheckPattern *> NotStrings;
1409
1410 // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
1411 // bounds; we have not processed variable definitions within the bounded block
1412 // yet so cannot handle any final CHECK-DAG yet; this is handled when going
1413 // over the block again (including the last CHECK-LABEL) in normal mode.
1414 if (!IsLabelScanMode) {
1415 // Match "dag strings" (with mixed "not strings" if any).
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001416 LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001417 if (LastPos == StringRef::npos)
1418 return StringRef::npos;
1419 }
1420
1421 // Match itself from the last position after matching CHECK-DAG.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001422 size_t LastMatchEnd = LastPos;
1423 size_t FirstMatchPos = 0;
1424 // Go match the pattern Count times. Majority of patterns only match with
1425 // count 1 though.
1426 assert(Pat.getCount() != 0 && "pattern count can not be zero");
1427 for (int i = 1; i <= Pat.getCount(); i++) {
1428 StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
1429 size_t CurrentMatchLen;
1430 // get a match at current start point
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001431 Expected<size_t> MatchResult = Pat.match(MatchBuffer, CurrentMatchLen, SM);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001432
1433 // report
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001434 if (!MatchResult) {
1435 PrintNoMatch(true, SM, *this, i, MatchBuffer, Req.VerboseVerbose, Diags,
1436 MatchResult.takeError());
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001437 return StringRef::npos;
1438 }
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001439 size_t MatchPos = *MatchResult;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001440 PrintMatch(true, SM, *this, i, MatchBuffer, MatchPos, CurrentMatchLen, Req,
1441 Diags);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001442 if (i == 1)
1443 FirstMatchPos = LastPos + MatchPos;
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001444
1445 // move start point after the match
1446 LastMatchEnd += MatchPos + CurrentMatchLen;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001447 }
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001448 // Full match len counts from first match pos.
1449 MatchLen = LastMatchEnd - FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001450
1451 // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1452 // or CHECK-NOT
1453 if (!IsLabelScanMode) {
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001454 size_t MatchPos = FirstMatchPos - LastPos;
1455 StringRef MatchBuffer = Buffer.substr(LastPos);
1456 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001457
1458 // If this check is a "CHECK-NEXT", verify that the previous match was on
1459 // the previous line (i.e. that there is one newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001460 if (CheckNext(SM, SkippedRegion)) {
Joel E. Dennye2afb612018-12-18 00:03:51 +00001461 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001462 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001463 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001464 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001465 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001466
1467 // If this check is a "CHECK-SAME", verify that the previous match was on
1468 // the same line (i.e. that there is no newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001469 if (CheckSame(SM, SkippedRegion)) {
Joel E. Dennye2afb612018-12-18 00:03:51 +00001470 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001471 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001472 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001473 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001474 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001475
1476 // If this match had "not strings", verify that they don't exist in the
1477 // skipped region.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001478 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001479 return StringRef::npos;
1480 }
1481
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001482 return FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001483}
1484
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001485bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1486 if (Pat.getCheckTy() != Check::CheckNext &&
1487 Pat.getCheckTy() != Check::CheckEmpty)
1488 return false;
1489
1490 Twine CheckName =
1491 Prefix +
1492 Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
1493
1494 // Count the number of newlines between the previous match and this one.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001495 const char *FirstNewLine = nullptr;
1496 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1497
1498 if (NumNewLines == 0) {
1499 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1500 CheckName + ": is on the same line as previous match");
1501 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1502 "'next' match was here");
1503 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1504 "previous match ended here");
1505 return true;
1506 }
1507
1508 if (NumNewLines != 1) {
1509 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1510 CheckName +
1511 ": is not on the line after the previous match");
1512 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1513 "'next' match was here");
1514 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1515 "previous match ended here");
1516 SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
1517 "non-matching line after previous match is here");
1518 return true;
1519 }
1520
1521 return false;
1522}
1523
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001524bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
1525 if (Pat.getCheckTy() != Check::CheckSame)
1526 return false;
1527
1528 // Count the number of newlines between the previous match and this one.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001529 const char *FirstNewLine = nullptr;
1530 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1531
1532 if (NumNewLines != 0) {
1533 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1534 Prefix +
1535 "-SAME: is not on the same line as the previous match");
1536 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1537 "'next' match was here");
1538 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1539 "previous match ended here");
1540 return true;
1541 }
1542
1543 return false;
1544}
1545
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001546bool FileCheckString::CheckNot(
1547 const SourceMgr &SM, StringRef Buffer,
1548 const std::vector<const FileCheckPattern *> &NotStrings,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001549 const FileCheckRequest &Req, std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001550 for (const FileCheckPattern *Pat : NotStrings) {
1551 assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1552
1553 size_t MatchLen = 0;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001554 Expected<size_t> MatchResult = Pat->match(Buffer, MatchLen, SM);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001555
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001556 if (!MatchResult) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001557 PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001558 Req.VerboseVerbose, Diags, MatchResult.takeError());
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001559 continue;
1560 }
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001561 size_t Pos = *MatchResult;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001562
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001563 PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, Pos, MatchLen,
1564 Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001565
1566 return true;
1567 }
1568
1569 return false;
1570}
1571
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001572size_t
1573FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1574 std::vector<const FileCheckPattern *> &NotStrings,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001575 const FileCheckRequest &Req,
1576 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001577 if (DagNotStrings.empty())
1578 return 0;
1579
1580 // The start of the search range.
1581 size_t StartPos = 0;
1582
1583 struct MatchRange {
1584 size_t Pos;
1585 size_t End;
1586 };
1587 // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
1588 // ranges are erased from this list once they are no longer in the search
1589 // range.
1590 std::list<MatchRange> MatchRanges;
1591
1592 // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
1593 // group, so we don't use a range-based for loop here.
1594 for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
1595 PatItr != PatEnd; ++PatItr) {
1596 const FileCheckPattern &Pat = *PatItr;
1597 assert((Pat.getCheckTy() == Check::CheckDAG ||
1598 Pat.getCheckTy() == Check::CheckNot) &&
1599 "Invalid CHECK-DAG or CHECK-NOT!");
1600
1601 if (Pat.getCheckTy() == Check::CheckNot) {
1602 NotStrings.push_back(&Pat);
1603 continue;
1604 }
1605
1606 assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1607
1608 // CHECK-DAG always matches from the start.
1609 size_t MatchLen = 0, MatchPos = StartPos;
1610
1611 // Search for a match that doesn't overlap a previous match in this
1612 // CHECK-DAG group.
1613 for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
1614 StringRef MatchBuffer = Buffer.substr(MatchPos);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001615 Expected<size_t> MatchResult = Pat.match(MatchBuffer, MatchLen, SM);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001616 // With a group of CHECK-DAGs, a single mismatching means the match on
1617 // that group of CHECK-DAGs fails immediately.
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001618 if (!MatchResult) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001619 PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001620 Req.VerboseVerbose, Diags, MatchResult.takeError());
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001621 return StringRef::npos;
1622 }
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001623 size_t MatchPosBuf = *MatchResult;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001624 // Re-calc it as the offset relative to the start of the original string.
1625 MatchPos += MatchPosBuf;
1626 if (Req.VerboseVerbose)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001627 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1628 MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001629 MatchRange M{MatchPos, MatchPos + MatchLen};
1630 if (Req.AllowDeprecatedDagOverlap) {
1631 // We don't need to track all matches in this mode, so we just maintain
1632 // one match range that encompasses the current CHECK-DAG group's
1633 // matches.
1634 if (MatchRanges.empty())
1635 MatchRanges.insert(MatchRanges.end(), M);
1636 else {
1637 auto Block = MatchRanges.begin();
1638 Block->Pos = std::min(Block->Pos, M.Pos);
1639 Block->End = std::max(Block->End, M.End);
1640 }
1641 break;
1642 }
1643 // Iterate previous matches until overlapping match or insertion point.
1644 bool Overlap = false;
1645 for (; MI != ME; ++MI) {
1646 if (M.Pos < MI->End) {
1647 // !Overlap => New match has no overlap and is before this old match.
1648 // Overlap => New match overlaps this old match.
1649 Overlap = MI->Pos < M.End;
1650 break;
1651 }
1652 }
1653 if (!Overlap) {
1654 // Insert non-overlapping match into list.
1655 MatchRanges.insert(MI, M);
1656 break;
1657 }
1658 if (Req.VerboseVerbose) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001659 // Due to their verbosity, we don't print verbose diagnostics here if
1660 // we're gathering them for a different rendering, but we always print
1661 // other diagnostics.
1662 if (!Diags) {
1663 SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
1664 SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
1665 SMRange OldRange(OldStart, OldEnd);
1666 SM.PrintMessage(OldStart, SourceMgr::DK_Note,
1667 "match discarded, overlaps earlier DAG match here",
1668 {OldRange});
1669 } else
Joel E. Dennye2afb612018-12-18 00:03:51 +00001670 Diags->rbegin()->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001671 }
1672 MatchPos = MI->End;
1673 }
1674 if (!Req.VerboseVerbose)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001675 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1676 MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001677
1678 // Handle the end of a CHECK-DAG group.
1679 if (std::next(PatItr) == PatEnd ||
1680 std::next(PatItr)->getCheckTy() == Check::CheckNot) {
1681 if (!NotStrings.empty()) {
1682 // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
1683 // CHECK-DAG, verify that there are no 'not' strings occurred in that
1684 // region.
1685 StringRef SkippedRegion =
1686 Buffer.slice(StartPos, MatchRanges.begin()->Pos);
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001687 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001688 return StringRef::npos;
1689 // Clear "not strings".
1690 NotStrings.clear();
1691 }
1692 // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
1693 // end of this CHECK-DAG group's match range.
1694 StartPos = MatchRanges.rbegin()->End;
1695 // Don't waste time checking for (impossible) overlaps before that.
1696 MatchRanges.clear();
1697 }
1698 }
1699
1700 return StartPos;
1701}
1702
1703// A check prefix must contain only alphanumeric, hyphens and underscores.
1704static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1705 Regex Validator("^[a-zA-Z0-9_-]*$");
1706 return Validator.match(CheckPrefix);
1707}
1708
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001709bool FileCheck::ValidateCheckPrefixes() {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001710 StringSet<> PrefixSet;
1711
1712 for (StringRef Prefix : Req.CheckPrefixes) {
1713 // Reject empty prefixes.
1714 if (Prefix == "")
1715 return false;
1716
1717 if (!PrefixSet.insert(Prefix).second)
1718 return false;
1719
1720 if (!ValidateCheckPrefix(Prefix))
1721 return false;
1722 }
1723
1724 return true;
1725}
1726
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001727Regex FileCheck::buildCheckPrefixRegex() {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001728 // I don't think there's a way to specify an initial value for cl::list,
1729 // so if nothing was specified, add the default
1730 if (Req.CheckPrefixes.empty())
1731 Req.CheckPrefixes.push_back("CHECK");
1732
1733 // We already validated the contents of CheckPrefixes so just concatenate
1734 // them as alternatives.
1735 SmallString<32> PrefixRegexStr;
1736 for (StringRef Prefix : Req.CheckPrefixes) {
1737 if (Prefix != Req.CheckPrefixes.front())
1738 PrefixRegexStr.push_back('|');
1739
1740 PrefixRegexStr.append(Prefix);
1741 }
1742
1743 return Regex(PrefixRegexStr);
1744}
1745
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001746Error FileCheckPatternContext::defineCmdlineVariables(
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001747 std::vector<std::string> &CmdlineDefines, SourceMgr &SM) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001748 assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001749 "Overriding defined variable with command-line variable definitions");
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001750
1751 if (CmdlineDefines.empty())
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001752 return Error::success();
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001753
1754 // Create a string representing the vector of command-line definitions. Each
1755 // definition is on its own line and prefixed with a definition number to
1756 // clarify which definition a given diagnostic corresponds to.
1757 unsigned I = 0;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001758 Error Errs = Error::success();
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001759 std::string CmdlineDefsDiag;
1760 StringRef Prefix1 = "Global define #";
1761 StringRef Prefix2 = ": ";
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001762 for (StringRef CmdlineDef : CmdlineDefines)
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001763 CmdlineDefsDiag +=
1764 (Prefix1 + Twine(++I) + Prefix2 + CmdlineDef + "\n").str();
1765
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001766 // Create a buffer with fake command line content in order to display
1767 // parsing diagnostic with location information and point to the
1768 // global definition with invalid syntax.
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001769 std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
1770 MemoryBuffer::getMemBufferCopy(CmdlineDefsDiag, "Global defines");
1771 StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
1772 SM.AddNewSourceBuffer(std::move(CmdLineDefsDiagBuffer), SMLoc());
1773
1774 SmallVector<StringRef, 4> CmdlineDefsDiagVec;
1775 CmdlineDefsDiagRef.split(CmdlineDefsDiagVec, '\n', -1 /*MaxSplit*/,
1776 false /*KeepEmpty*/);
1777 for (StringRef CmdlineDefDiag : CmdlineDefsDiagVec) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001778 unsigned DefStart = CmdlineDefDiag.find(Prefix2) + Prefix2.size();
1779 StringRef CmdlineDef = CmdlineDefDiag.substr(DefStart);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001780 size_t EqIdx = CmdlineDef.find('=');
1781 if (EqIdx == StringRef::npos) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001782 Errs = joinErrors(
1783 std::move(Errs),
1784 FileCheckErrorDiagnostic::get(
1785 SM, CmdlineDef, "missing equal sign in global definition"));
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001786 continue;
1787 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001788
1789 // Numeric variable definition.
1790 if (CmdlineDef[0] == '#') {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001791 StringRef CmdlineName = CmdlineDef.substr(1, EqIdx - 1);
Thomas Preud'homme56f63082019-07-05 16:25:46 +00001792 Expected<FileCheckNumericVariable *> ParseResult =
1793 FileCheckPattern::parseNumericVariableDefinition(CmdlineName, this, 0,
1794 SM);
1795 if (!ParseResult) {
1796 Errs = joinErrors(std::move(Errs), ParseResult.takeError());
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001797 continue;
1798 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001799
1800 StringRef CmdlineVal = CmdlineDef.substr(EqIdx + 1);
1801 uint64_t Val;
1802 if (CmdlineVal.getAsInteger(10, Val)) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001803 Errs = joinErrors(std::move(Errs),
1804 FileCheckErrorDiagnostic::get(
1805 SM, CmdlineVal,
1806 "invalid value in numeric variable definition '" +
1807 CmdlineVal + "'"));
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001808 continue;
1809 }
Thomas Preud'homme56f63082019-07-05 16:25:46 +00001810 FileCheckNumericVariable *DefinedNumericVariable = *ParseResult;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001811 DefinedNumericVariable->setValue(Val);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001812
1813 // Record this variable definition.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001814 GlobalNumericVariableTable[DefinedNumericVariable->getName()] =
1815 DefinedNumericVariable;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001816 } else {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001817 // String variable definition.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001818 std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.split('=');
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001819 StringRef CmdlineName = CmdlineNameVal.first;
1820 StringRef OrigCmdlineName = CmdlineName;
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +00001821 Expected<FileCheckPattern::VariableProperties> ParseVarResult =
1822 FileCheckPattern::parseVariable(CmdlineName, SM);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001823 if (!ParseVarResult) {
1824 Errs = joinErrors(std::move(Errs), ParseVarResult.takeError());
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001825 continue;
1826 }
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001827 // Check that CmdlineName does not denote a pseudo variable is only
1828 // composed of the parsed numeric variable. This catches cases like
1829 // "FOO+2" in a "FOO+2=10" definition.
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +00001830 if (ParseVarResult->IsPseudo || !CmdlineName.empty()) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001831 Errs = joinErrors(std::move(Errs),
1832 FileCheckErrorDiagnostic::get(
1833 SM, OrigCmdlineName,
1834 "invalid name in string variable definition '" +
1835 OrigCmdlineName + "'"));
1836 continue;
1837 }
Thomas Preud'homme2a7f5202019-07-13 13:24:30 +00001838 StringRef Name = ParseVarResult->Name;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001839
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001840 // Detect collisions between string and numeric variables when the former
1841 // is created later than the latter.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001842 if (GlobalNumericVariableTable.find(Name) !=
1843 GlobalNumericVariableTable.end()) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001844 Errs = joinErrors(std::move(Errs), FileCheckErrorDiagnostic::get(
1845 SM, Name,
1846 "numeric variable with name '" +
1847 Name + "' already exists"));
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001848 continue;
1849 }
1850 GlobalVariableTable.insert(CmdlineNameVal);
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001851 // Mark the string variable as defined to detect collisions between
1852 // string and numeric variables in DefineCmdlineVariables when the latter
1853 // is created later than the former. We cannot reuse GlobalVariableTable
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001854 // for this by populating it with an empty string since we would then
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001855 // lose the ability to detect the use of an undefined variable in
1856 // match().
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001857 DefinedVariableTable[Name] = true;
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001858 }
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001859 }
1860
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001861 return Errs;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001862}
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001863
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001864void FileCheckPatternContext::clearLocalVars() {
1865 SmallVector<StringRef, 16> LocalPatternVars, LocalNumericVars;
1866 for (const StringMapEntry<StringRef> &Var : GlobalVariableTable)
1867 if (Var.first()[0] != '$')
1868 LocalPatternVars.push_back(Var.first());
1869
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001870 // Numeric substitution reads the value of a variable directly, not via
1871 // GlobalNumericVariableTable. Therefore, we clear local variables by
1872 // clearing their value which will lead to a numeric substitution failure. We
1873 // also mark the variable for removal from GlobalNumericVariableTable since
1874 // this is what defineCmdlineVariables checks to decide that no global
1875 // variable has been defined.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001876 for (const auto &Var : GlobalNumericVariableTable)
1877 if (Var.first()[0] != '$') {
1878 Var.getValue()->clearValue();
1879 LocalNumericVars.push_back(Var.first());
1880 }
1881
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001882 for (const auto &Var : LocalPatternVars)
1883 GlobalVariableTable.erase(Var);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001884 for (const auto &Var : LocalNumericVars)
1885 GlobalNumericVariableTable.erase(Var);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001886}
1887
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001888bool FileCheck::CheckInput(SourceMgr &SM, StringRef Buffer,
1889 ArrayRef<FileCheckString> CheckStrings,
1890 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001891 bool ChecksFailed = false;
1892
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001893 unsigned i = 0, j = 0, e = CheckStrings.size();
1894 while (true) {
1895 StringRef CheckRegion;
1896 if (j == e) {
1897 CheckRegion = Buffer;
1898 } else {
1899 const FileCheckString &CheckLabelStr = CheckStrings[j];
1900 if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
1901 ++j;
1902 continue;
1903 }
1904
1905 // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1906 size_t MatchLabelLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001907 size_t MatchLabelPos =
1908 CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001909 if (MatchLabelPos == StringRef::npos)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001910 // Immediately bail if CHECK-LABEL fails, nothing else we can do.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001911 return false;
1912
1913 CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1914 Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1915 ++j;
1916 }
1917
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001918 // Do not clear the first region as it's the one before the first
1919 // CHECK-LABEL and it would clear variables defined on the command-line
1920 // before they get used.
1921 if (i != 0 && Req.EnableVarScope)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001922 PatternContext.clearLocalVars();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001923
1924 for (; i != j; ++i) {
1925 const FileCheckString &CheckStr = CheckStrings[i];
1926
1927 // Check each string within the scanned region, including a second check
1928 // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1929 size_t MatchLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001930 size_t MatchPos =
1931 CheckStr.Check(SM, CheckRegion, false, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001932
1933 if (MatchPos == StringRef::npos) {
1934 ChecksFailed = true;
1935 i = j;
1936 break;
1937 }
1938
1939 CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1940 }
1941
1942 if (j == e)
1943 break;
1944 }
1945
1946 // Success if no checks failed.
1947 return !ChecksFailed;
1948}