blob: 4d3862243d0199589b5dad2bd8819b78f35f62c3 [file] [log] [blame]
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00006//
7//===----------------------------------------------------------------------===//
8//
9// FileCheck does a line-by line check of a file that validates whether it
10// contains the expected content. This is useful for regression tests etc.
11//
12// This file implements most of the API that will be used by the FileCheck utility
13// as well as various unittests.
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Support/FileCheck.h"
17#include "llvm/ADT/StringSet.h"
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +000018#include "llvm/Support/FormatVariadic.h"
19#include <cstdint>
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +000020#include <list>
21#include <map>
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +000022#include <tuple>
23#include <utility>
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +000024
25using namespace llvm;
26
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000027bool FileCheckNumericVariable::setValue(uint64_t NewValue) {
28 if (Value)
29 return true;
30 Value = NewValue;
31 return false;
32}
33
34bool FileCheckNumericVariable::clearValue() {
35 if (!Value)
36 return true;
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +000037 Value = None;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000038 return false;
39}
40
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +000041Optional<uint64_t> FileCheckNumExpr::eval() const {
Thomas Preud'homme71d3f222019-06-06 13:21:06 +000042 assert(LeftOp && "Evaluating an empty numeric expression");
43 Optional<uint64_t> LeftOpValue = LeftOp->getValue();
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000044 // Variable is undefined.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +000045 if (!LeftOpValue)
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +000046 return None;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +000047 return EvalBinop(*LeftOpValue, RightOp);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000048}
49
50StringRef FileCheckNumExpr::getUndefVarName() const {
51 if (!LeftOp->getValue())
52 return LeftOp->getName();
53 return StringRef();
54}
55
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +000056Optional<std::string> FileCheckNumericSubstitution::getResult() const {
57 Optional<uint64_t> EvaluatedValue = NumExpr->eval();
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +000058 if (!EvaluatedValue)
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +000059 return None;
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +000060 return utostr(*EvaluatedValue);
61}
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000062
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +000063Optional<std::string> FileCheckStringSubstitution::getResult() const {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000064 // Look up the value and escape it so that we can put it into the regex.
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +000065 Optional<StringRef> VarVal = Context->getPatternVarValue(FromStr);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000066 if (!VarVal)
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +000067 return None;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000068 return Regex::escape(*VarVal);
Thomas Preud'homme288ed912019-05-02 00:04:38 +000069}
70
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +000071StringRef FileCheckNumericSubstitution::getUndefVarName() const {
72 // Although a use of an undefined numeric variable is detected at parse
73 // time, a numeric variable can be undefined later by ClearLocalVariables.
74 return NumExpr->getUndefVarName();
75}
Thomas Preud'homme288ed912019-05-02 00:04:38 +000076
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +000077StringRef FileCheckStringSubstitution::getUndefVarName() const {
Thomas Preud'homme288ed912019-05-02 00:04:38 +000078 if (!Context->getPatternVarValue(FromStr))
79 return FromStr;
80
81 return StringRef();
82}
83
Thomas Preud'homme5a330472019-04-29 13:32:36 +000084bool FileCheckPattern::isValidVarNameStart(char C) {
85 return C == '_' || isalpha(C);
86}
87
Thomas Preud'homme71d3f222019-06-06 13:21:06 +000088bool FileCheckPattern::parseVariable(StringRef &Str, StringRef &Name,
89 bool &IsPseudo) {
Thomas Preud'homme5a330472019-04-29 13:32:36 +000090 if (Str.empty())
91 return true;
92
93 bool ParsedOneChar = false;
94 unsigned I = 0;
95 IsPseudo = Str[0] == '@';
96
97 // Global vars start with '$'.
98 if (Str[0] == '$' || IsPseudo)
99 ++I;
100
101 for (unsigned E = Str.size(); I != E; ++I) {
102 if (!ParsedOneChar && !isValidVarNameStart(Str[I]))
103 return true;
104
105 // Variable names are composed of alphanumeric characters and underscores.
106 if (Str[I] != '_' && !isalnum(Str[I]))
107 break;
108 ParsedOneChar = true;
109 }
110
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000111 Name = Str.take_front(I);
112 Str = Str.substr(I);
Thomas Preud'homme5a330472019-04-29 13:32:36 +0000113 return false;
114}
115
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000116// StringRef holding all characters considered as horizontal whitespaces by
117// FileCheck input canonicalization.
118StringRef SpaceChars = " \t";
119
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000120// Parsing helper function that strips the first character in S and returns it.
121static char popFront(StringRef &S) {
122 char C = S.front();
123 S = S.drop_front();
124 return C;
125}
126
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000127bool FileCheckPattern::parseNumericVariableDefinition(
128 StringRef &Expr, StringRef &Name, FileCheckPatternContext *Context,
129 const SourceMgr &SM) {
130 bool IsPseudo;
131 if (parseVariable(Expr, Name, IsPseudo)) {
132 SM.PrintMessage(SMLoc::getFromPointer(Expr.data()), SourceMgr::DK_Error,
133 "invalid variable name");
134 return true;
135 }
136
137 if (IsPseudo) {
138 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
139 "definition of pseudo numeric variable unsupported");
140 return true;
141 }
142
143 // Detect collisions between string and numeric variables when the latter
144 // is created later than the former.
145 if (Context->DefinedVariableTable.find(Name) !=
146 Context->DefinedVariableTable.end()) {
147 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
148 "string variable with name '" + Name + "' already exists");
149 return true;
150 }
151
152 return false;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000153}
154
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000155FileCheckNumericVariable *
156FileCheckPattern::parseNumericVariableUse(StringRef &Expr,
157 const SourceMgr &SM) const {
158 bool IsPseudo;
159 StringRef Name;
160 if (parseVariable(Expr, Name, IsPseudo)) {
161 SM.PrintMessage(SMLoc::getFromPointer(Expr.data()), SourceMgr::DK_Error,
162 "invalid variable name");
163 return nullptr;
164 }
165
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000166 if (IsPseudo && !Name.equals("@LINE")) {
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000167 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000168 "invalid pseudo numeric variable '" + Name + "'");
169 return nullptr;
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000170 }
171
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000172 // This method is indirectly called from parsePattern for all numeric
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000173 // variable definitions and uses in the order in which they appear in the
174 // CHECK pattern. For each definition, the pointer to the class instance of
175 // the corresponding numeric variable definition is stored in
176 // GlobalNumericVariableTable. Therefore, the pointer we get below is for the
177 // class instance corresponding to the last definition of this variable use.
178 auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
179 if (VarTableIter == Context->GlobalNumericVariableTable.end()) {
180 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
181 "using undefined numeric variable '" + Name + "'");
182 return nullptr;
183 }
184
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000185 FileCheckNumericVariable *NumericVariable = VarTableIter->second;
186 if (!IsPseudo && NumericVariable->getDefLineNumber() == LineNumber) {
187 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
188 "numeric variable '" + Name +
189 "' defined on the same line as used");
190 return nullptr;
191 }
192
193 return NumericVariable;
194}
195
196static uint64_t add(uint64_t LeftOp, uint64_t RightOp) {
197 return LeftOp + RightOp;
198}
199
200static uint64_t sub(uint64_t LeftOp, uint64_t RightOp) {
201 return LeftOp - RightOp;
202}
203
204FileCheckNumExpr *FileCheckPattern::parseBinop(StringRef &Expr,
205 const SourceMgr &SM) const {
206 FileCheckNumericVariable *LeftOp = parseNumericVariableUse(Expr, SM);
207 if (!LeftOp) {
208 // Error reporting done in parseNumericVariableUse().
209 return nullptr;
210 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000211
212 // Check if this is a supported operation and select a function to perform
213 // it.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000214 Expr = Expr.ltrim(SpaceChars);
215 if (Expr.empty())
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000216 return Context->makeNumExpr(add, LeftOp, 0);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000217 SMLoc OpLoc = SMLoc::getFromPointer(Expr.data());
218 char Operator = popFront(Expr);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000219 binop_eval_t EvalBinop;
220 switch (Operator) {
221 case '+':
222 EvalBinop = add;
223 break;
224 case '-':
225 EvalBinop = sub;
226 break;
227 default:
228 SM.PrintMessage(OpLoc, SourceMgr::DK_Error,
229 Twine("unsupported numeric operation '") + Twine(Operator) +
230 "'");
231 return nullptr;
232 }
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000233
234 // Parse right operand.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000235 Expr = Expr.ltrim(SpaceChars);
236 if (Expr.empty()) {
237 SM.PrintMessage(SMLoc::getFromPointer(Expr.data()), SourceMgr::DK_Error,
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000238 "missing operand in numeric expression");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000239 return nullptr;
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000240 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000241 uint64_t RightOp;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000242 if (Expr.consumeInteger(10, RightOp)) {
243 SM.PrintMessage(SMLoc::getFromPointer(Expr.data()), SourceMgr::DK_Error,
244 "invalid offset in numeric expression '" + Expr + "'");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000245 return nullptr;
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000246 }
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000247 Expr = Expr.ltrim(SpaceChars);
248 if (!Expr.empty()) {
249 SM.PrintMessage(SMLoc::getFromPointer(Expr.data()), SourceMgr::DK_Error,
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000250 "unexpected characters at end of numeric expression '" +
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000251 Expr + "'");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000252 return nullptr;
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000253 }
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000254
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000255 return Context->makeNumExpr(EvalBinop, LeftOp, RightOp);
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000256}
257
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000258FileCheckNumExpr *FileCheckPattern::parseNumericSubstitutionBlock(
259 StringRef Expr, FileCheckNumericVariable *&DefinedNumericVariable,
260 const SourceMgr &SM) const {
261 // Parse the numeric variable definition.
262 DefinedNumericVariable = nullptr;
263 size_t DefEnd = Expr.find(':');
264 if (DefEnd != StringRef::npos) {
265 StringRef DefExpr = Expr.substr(0, DefEnd);
266 StringRef UseExpr = Expr = Expr.substr(DefEnd + 1);
267
268 DefExpr = DefExpr.ltrim(SpaceChars);
269 StringRef Name;
270 if (parseNumericVariableDefinition(DefExpr, Name, Context, SM)) {
271 // Invalid variable definition. Error reporting done in parsing function.
272 return nullptr;
273 }
274
275 DefinedNumericVariable =
276 Context->makeNumericVariable(this->LineNumber, Name);
277
278 DefExpr = DefExpr.ltrim(SpaceChars);
279 if (!DefExpr.empty()) {
280 SM.PrintMessage(SMLoc::getFromPointer(DefExpr.data()),
281 SourceMgr::DK_Error,
282 "invalid numeric variable definition");
283 return nullptr;
284 }
285 UseExpr = UseExpr.ltrim(SpaceChars);
286 if (!UseExpr.empty()) {
287 SM.PrintMessage(
288 SMLoc::getFromPointer(UseExpr.data()), SourceMgr::DK_Error,
289 "unexpected string after variable definition: '" + UseExpr + "'");
290 return nullptr;
291 }
292 return Context->makeNumExpr(add, nullptr, 0);
293 }
294
295 // Parse the numeric expression itself.
296 Expr = Expr.ltrim(SpaceChars);
297 return parseBinop(Expr, SM);
298}
299
300bool FileCheckPattern::parsePattern(StringRef PatternStr, StringRef Prefix,
301 SourceMgr &SM,
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000302 const FileCheckRequest &Req) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000303 bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
304
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000305 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
306
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000307 // Create fake @LINE pseudo variable definition.
308 StringRef LinePseudo = "@LINE";
309 uint64_t LineNumber64 = LineNumber;
310 FileCheckNumericVariable *LinePseudoVar =
311 Context->makeNumericVariable(LinePseudo, LineNumber64);
312 Context->GlobalNumericVariableTable[LinePseudo] = LinePseudoVar;
313
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000314 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
315 // Ignore trailing whitespace.
316 while (!PatternStr.empty() &&
317 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
318 PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
319
320 // Check that there is something on the line.
321 if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
322 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
323 "found empty check string with prefix '" + Prefix + ":'");
324 return true;
325 }
326
327 if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
328 SM.PrintMessage(
329 PatternLoc, SourceMgr::DK_Error,
330 "found non-empty check string for empty check with prefix '" + Prefix +
331 ":'");
332 return true;
333 }
334
335 if (CheckTy == Check::CheckEmpty) {
336 RegExStr = "(\n$)";
337 return false;
338 }
339
340 // Check to see if this is a fixed string, or if it has regex pieces.
341 if (!MatchFullLinesHere &&
342 (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
343 PatternStr.find("[[") == StringRef::npos))) {
344 FixedStr = PatternStr;
345 return false;
346 }
347
348 if (MatchFullLinesHere) {
349 RegExStr += '^';
350 if (!Req.NoCanonicalizeWhiteSpace)
351 RegExStr += " *";
352 }
353
354 // Paren value #0 is for the fully matched string. Any new parenthesized
355 // values add from there.
356 unsigned CurParen = 1;
357
358 // Otherwise, there is at least one regex piece. Build up the regex pattern
359 // by escaping scary characters in fixed strings, building up one big regex.
360 while (!PatternStr.empty()) {
361 // RegEx matches.
362 if (PatternStr.startswith("{{")) {
363 // This is the start of a regex match. Scan for the }}.
364 size_t End = PatternStr.find("}}");
365 if (End == StringRef::npos) {
366 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
367 SourceMgr::DK_Error,
368 "found start of regex string with no end '}}'");
369 return true;
370 }
371
372 // Enclose {{}} patterns in parens just like [[]] even though we're not
373 // capturing the result for any purpose. This is required in case the
374 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
375 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
376 RegExStr += '(';
377 ++CurParen;
378
379 if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
380 return true;
381 RegExStr += ')';
382
383 PatternStr = PatternStr.substr(End + 2);
384 continue;
385 }
386
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000387 // String and numeric substitution blocks. String substitution blocks come
388 // in two forms: [[foo:.*]] and [[foo]]. The former matches .* (or some
389 // other regex) and assigns it to the string variable 'foo'. The latter
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000390 // substitutes foo's value. Numeric substitution blocks work the same way
391 // as string ones, but start with a '#' sign after the double brackets.
392 // Both string and numeric variable names must satisfy the regular
393 // expression "[a-zA-Z_][0-9a-zA-Z_]*" to be valid, as this helps catch
394 // some common errors.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000395 if (PatternStr.startswith("[[")) {
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000396 StringRef UnparsedPatternStr = PatternStr.substr(2);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000397 // Find the closing bracket pair ending the match. End is going to be an
398 // offset relative to the beginning of the match string.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000399 size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
400 StringRef MatchStr = UnparsedPatternStr.substr(0, End);
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000401 bool IsNumBlock = MatchStr.consume_front("#");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000402
403 if (End == StringRef::npos) {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000404 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
405 SourceMgr::DK_Error,
406 "Invalid substitution block, no ]] found");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000407 return true;
408 }
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000409 // Strip the substitution block we are parsing. End points to the start
410 // of the "]]" closing the expression so account for it in computing the
411 // index of the first unparsed character.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000412 PatternStr = UnparsedPatternStr.substr(End + 2);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000413
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000414 bool IsDefinition = false;
415 StringRef DefName;
416 StringRef SubstStr;
417 StringRef MatchRegexp;
418 size_t SubstInsertIdx = RegExStr.size();
419
420 // Parse string variable or legacy numeric expression.
421 if (!IsNumBlock) {
422 size_t VarEndIdx = MatchStr.find(":");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000423 size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
424 if (SpacePos != StringRef::npos) {
425 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
426 SourceMgr::DK_Error, "unexpected whitespace");
427 return true;
428 }
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000429
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000430 // Get the name (e.g. "foo") and verify it is well formed.
431 bool IsPseudo;
432 StringRef Name;
433 StringRef OrigMatchStr = MatchStr;
434 if (parseVariable(MatchStr, Name, IsPseudo)) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000435 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data()),
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000436 SourceMgr::DK_Error, "invalid variable name");
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000437 return true;
438 }
439
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000440 IsDefinition = (VarEndIdx != StringRef::npos);
441 if (IsDefinition) {
442 if ((IsPseudo || !MatchStr.consume_front(":"))) {
443 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
444 SourceMgr::DK_Error,
445 "invalid name in string variable definition");
446 return true;
447 }
448
449 // Detect collisions between string and numeric variables when the
450 // former is created later than the latter.
451 if (Context->GlobalNumericVariableTable.find(Name) !=
452 Context->GlobalNumericVariableTable.end()) {
453 SM.PrintMessage(
454 SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
455 "numeric variable with name '" + Name + "' already exists");
456 return true;
457 }
458 DefName = Name;
459 MatchRegexp = MatchStr;
460 } else {
461 if (IsPseudo) {
462 MatchStr = OrigMatchStr;
463 IsNumBlock = true;
464 } else
465 SubstStr = Name;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000466 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000467 }
468
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000469 // Parse numeric substitution block.
470 FileCheckNumExpr *NumExpr;
471 FileCheckNumericVariable *DefinedNumericVariable;
472 if (IsNumBlock) {
473 NumExpr =
474 parseNumericSubstitutionBlock(MatchStr, DefinedNumericVariable, SM);
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000475 if (NumExpr == nullptr)
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000476 return true;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000477 if (DefinedNumericVariable) {
478 IsDefinition = true;
479 DefName = DefinedNumericVariable->getName();
480 MatchRegexp = StringRef("[0-9]+");
481 } else
482 SubstStr = MatchStr;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000483 }
484
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000485 // Handle substitutions: [[foo]] and [[#<foo expr>]].
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000486 if (!IsDefinition) {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000487 // Handle substitution of string variables that were defined earlier on
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000488 // the same line by emitting a backreference. Numeric expressions do
489 // not support substituting a numeric variable defined on the same
490 // line.
491 if (!IsNumBlock && VariableDefs.find(SubstStr) != VariableDefs.end()) {
492 unsigned CaptureParenGroup = VariableDefs[SubstStr];
493 if (CaptureParenGroup < 1 || CaptureParenGroup > 9) {
494 SM.PrintMessage(SMLoc::getFromPointer(SubstStr.data()),
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000495 SourceMgr::DK_Error,
496 "Can't back-reference more than 9 variables");
497 return true;
498 }
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000499 AddBackrefToRegEx(CaptureParenGroup);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000500 } else {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000501 // Handle substitution of string variables ([[<var>]]) defined in
502 // previous CHECK patterns, and substitution of numeric expressions.
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000503 FileCheckSubstitution *Substitution =
504 IsNumBlock
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000505 ? Context->makeNumericSubstitution(SubstStr, NumExpr,
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000506 SubstInsertIdx)
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000507 : Context->makeStringSubstitution(SubstStr, SubstInsertIdx);
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000508 Substitutions.push_back(Substitution);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000509 }
510 continue;
511 }
512
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000513 // Handle variable definitions: [[<def>:(...)]] and
514 // [[#(...)<def>:(...)]].
515 if (IsNumBlock) {
516 FileCheckNumExprMatch NumExprDef = {DefinedNumericVariable, CurParen};
517 NumericVariableDefs[DefName] = NumExprDef;
518 // This store is done here rather than in match() to allow
519 // parseNumericVariableUse() to get the pointer to the class instance
520 // of the right variable definition corresponding to a given numeric
521 // variable use.
522 Context->GlobalNumericVariableTable[DefName] = DefinedNumericVariable;
523 } else {
524 VariableDefs[DefName] = CurParen;
525 // Mark the string variable as defined to detect collisions between
526 // string and numeric variables in parseNumericVariableUse() and
527 // DefineCmdlineVariables() when the latter is created later than the
528 // former. We cannot reuse GlobalVariableTable for this by populating
529 // it with an empty string since we would then lose the ability to
530 // detect the use of an undefined variable in match().
531 Context->DefinedVariableTable[DefName] = true;
532 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000533 RegExStr += '(';
534 ++CurParen;
535
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000536 if (AddRegExToRegEx(MatchRegexp, CurParen, SM))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000537 return true;
538
539 RegExStr += ')';
540 }
541
542 // Handle fixed string matches.
543 // Find the end, which is the start of the next regex.
544 size_t FixedMatchEnd = PatternStr.find("{{");
545 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
546 RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
547 PatternStr = PatternStr.substr(FixedMatchEnd);
548 }
549
550 if (MatchFullLinesHere) {
551 if (!Req.NoCanonicalizeWhiteSpace)
552 RegExStr += " *";
553 RegExStr += '$';
554 }
555
556 return false;
557}
558
559bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
560 Regex R(RS);
561 std::string Error;
562 if (!R.isValid(Error)) {
563 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
564 "invalid regex: " + Error);
565 return true;
566 }
567
568 RegExStr += RS.str();
569 CurParen += R.getNumMatches();
570 return false;
571}
572
573void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
574 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
575 std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
576 RegExStr += Backref;
577}
578
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000579size_t FileCheckPattern::match(StringRef Buffer, size_t &MatchLen,
580 const SourceMgr &SM) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000581 // If this is the EOF pattern, match it immediately.
582 if (CheckTy == Check::CheckEOF) {
583 MatchLen = 0;
584 return Buffer.size();
585 }
586
587 // If this is a fixed string pattern, just match it now.
588 if (!FixedStr.empty()) {
589 MatchLen = FixedStr.size();
590 return Buffer.find(FixedStr);
591 }
592
593 // Regex match.
594
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000595 // If there are substitutions, we need to create a temporary string with the
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000596 // actual value.
597 StringRef RegExToMatch = RegExStr;
598 std::string TmpStr;
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000599 if (!Substitutions.empty()) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000600 TmpStr = RegExStr;
601
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000602 size_t InsertOffset = 0;
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000603 // Substitute all string variables and numeric expressions whose values are
604 // only now known. Use of string variables defined on the same line are
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000605 // handled by back-references.
606 for (const auto &Substitution : Substitutions) {
607 // Substitute and check for failure (e.g. use of undefined variable).
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +0000608 Optional<std::string> Value = Substitution->getResult();
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000609 if (!Value)
610 return StringRef::npos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000611
612 // Plop it into the regex at the adjusted offset.
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000613 TmpStr.insert(TmpStr.begin() + Substitution->getIndex() + InsertOffset,
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000614 Value->begin(), Value->end());
615 InsertOffset += Value->size();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000616 }
617
618 // Match the newly constructed regex.
619 RegExToMatch = TmpStr;
620 }
621
622 SmallVector<StringRef, 4> MatchInfo;
623 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
624 return StringRef::npos;
625
626 // Successful regex match.
627 assert(!MatchInfo.empty() && "Didn't get any match");
628 StringRef FullMatch = MatchInfo[0];
629
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000630 // If this defines any string variables, remember their values.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000631 for (const auto &VariableDef : VariableDefs) {
632 assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000633 Context->GlobalVariableTable[VariableDef.first] =
634 MatchInfo[VariableDef.second];
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000635 }
636
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000637 // If this defines any numeric variables, remember their values.
638 for (const auto &NumericVariableDef : NumericVariableDefs) {
639 const FileCheckNumExprMatch &NumericVariableMatch =
640 NumericVariableDef.getValue();
641 unsigned CaptureParenGroup = NumericVariableMatch.CaptureParenGroup;
642 assert(CaptureParenGroup < MatchInfo.size() && "Internal paren error");
643 FileCheckNumericVariable *DefinedNumericVariable =
644 NumericVariableMatch.DefinedNumericVariable;
645
646 StringRef MatchedValue = MatchInfo[CaptureParenGroup];
647 uint64_t Val;
648 if (MatchedValue.getAsInteger(10, Val)) {
649 SM.PrintMessage(SMLoc::getFromPointer(MatchedValue.data()),
650 SourceMgr::DK_Error, "Unable to represent numeric value");
651 }
652 if (DefinedNumericVariable->setValue(Val))
653 assert(false && "Numeric variable redefined");
654 }
655
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000656 // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
657 // the required preceding newline, which is consumed by the pattern in the
658 // case of CHECK-EMPTY but not CHECK-NEXT.
659 size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
660 MatchLen = FullMatch.size() - MatchStartSkip;
661 return FullMatch.data() - Buffer.data() + MatchStartSkip;
662}
663
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000664unsigned FileCheckPattern::computeMatchDistance(StringRef Buffer) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000665 // Just compute the number of matching characters. For regular expressions, we
666 // just compare against the regex itself and hope for the best.
667 //
668 // FIXME: One easy improvement here is have the regex lib generate a single
669 // example regular expression which matches, and use that as the example
670 // string.
671 StringRef ExampleString(FixedStr);
672 if (ExampleString.empty())
673 ExampleString = RegExStr;
674
675 // Only compare up to the first line in the buffer, or the string size.
676 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
677 BufferPrefix = BufferPrefix.split('\n').first;
678 return BufferPrefix.edit_distance(ExampleString);
679}
680
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000681void FileCheckPattern::printSubstitutions(const SourceMgr &SM, StringRef Buffer,
682 SMRange MatchRange) const {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000683 // Print what we know about substitutions.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000684 if (!Substitutions.empty()) {
685 for (const auto &Substitution : Substitutions) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000686 SmallString<256> Msg;
687 raw_svector_ostream OS(Msg);
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +0000688 Optional<std::string> MatchedValue = Substitution->getResult();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000689
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000690 // Substitution failed or is not known at match time, print the undefined
691 // variable it uses.
692 if (!MatchedValue) {
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000693 StringRef UndefVarName = Substitution->getUndefVarName();
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000694 if (UndefVarName.empty())
695 continue;
696 OS << "uses undefined variable \"";
697 OS.write_escaped(UndefVarName) << "\"";
698 } else {
699 // Substitution succeeded. Print substituted value.
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000700 OS << "with \"";
701 OS.write_escaped(Substitution->getFromString()) << "\" equal to \"";
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000702 OS.write_escaped(*MatchedValue) << "\"";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000703 }
704
705 if (MatchRange.isValid())
706 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
707 {MatchRange});
708 else
709 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
710 SourceMgr::DK_Note, OS.str());
711 }
712 }
713}
714
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000715static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
716 const SourceMgr &SM, SMLoc Loc,
717 Check::FileCheckType CheckTy,
718 StringRef Buffer, size_t Pos, size_t Len,
Joel E. Denny7df86962018-12-18 00:03:03 +0000719 std::vector<FileCheckDiag> *Diags,
720 bool AdjustPrevDiag = false) {
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000721 SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
722 SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
723 SMRange Range(Start, End);
Joel E. Denny96f0e842018-12-18 00:03:36 +0000724 if (Diags) {
Joel E. Denny7df86962018-12-18 00:03:03 +0000725 if (AdjustPrevDiag)
726 Diags->rbegin()->MatchTy = MatchTy;
727 else
728 Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
729 }
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000730 return Range;
731}
732
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000733void FileCheckPattern::printFuzzyMatch(
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000734 const SourceMgr &SM, StringRef Buffer,
Joel E. Denny2c007c82018-12-18 00:02:04 +0000735 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000736 // Attempt to find the closest/best fuzzy match. Usually an error happens
737 // because some string in the output didn't exactly match. In these cases, we
738 // would like to show the user a best guess at what "should have" matched, to
739 // save them having to actually check the input manually.
740 size_t NumLinesForward = 0;
741 size_t Best = StringRef::npos;
742 double BestQuality = 0;
743
744 // Use an arbitrary 4k limit on how far we will search.
745 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
746 if (Buffer[i] == '\n')
747 ++NumLinesForward;
748
749 // Patterns have leading whitespace stripped, so skip whitespace when
750 // looking for something which looks like a pattern.
751 if (Buffer[i] == ' ' || Buffer[i] == '\t')
752 continue;
753
754 // Compute the "quality" of this match as an arbitrary combination of the
755 // match distance and the number of lines skipped to get to this match.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000756 unsigned Distance = computeMatchDistance(Buffer.substr(i));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000757 double Quality = Distance + (NumLinesForward / 100.);
758
759 if (Quality < BestQuality || Best == StringRef::npos) {
760 Best = i;
761 BestQuality = Quality;
762 }
763 }
764
765 // Print the "possible intended match here" line if we found something
766 // reasonable and not equal to what we showed in the "scanning from here"
767 // line.
768 if (Best && Best != StringRef::npos && BestQuality < 50) {
Joel E. Denny2c007c82018-12-18 00:02:04 +0000769 SMRange MatchRange =
770 ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
771 getCheckTy(), Buffer, Best, 0, Diags);
772 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
773 "possible intended match here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000774
775 // FIXME: If we wanted to be really friendly we would show why the match
776 // failed, as it can be hard to spot simple one character differences.
777 }
778}
779
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +0000780Optional<StringRef>
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000781FileCheckPatternContext::getPatternVarValue(StringRef VarName) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000782 auto VarIter = GlobalVariableTable.find(VarName);
783 if (VarIter == GlobalVariableTable.end())
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +0000784 return None;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000785
786 return VarIter->second;
787}
788
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000789FileCheckNumExpr *
790FileCheckPatternContext::makeNumExpr(binop_eval_t EvalBinop,
791 FileCheckNumericVariable *OperandLeft,
792 uint64_t OperandRight) {
793 NumExprs.push_back(llvm::make_unique<FileCheckNumExpr>(EvalBinop, OperandLeft,
794 OperandRight));
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000795 return NumExprs.back().get();
796}
797
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000798template <class... Types>
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000799FileCheckNumericVariable *
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000800FileCheckPatternContext::makeNumericVariable(Types... args) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000801 NumericVariables.push_back(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000802 llvm::make_unique<FileCheckNumericVariable>(args...));
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000803 return NumericVariables.back().get();
804}
805
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000806FileCheckSubstitution *
807FileCheckPatternContext::makeStringSubstitution(StringRef VarName,
808 size_t InsertIdx) {
809 Substitutions.push_back(
810 llvm::make_unique<FileCheckStringSubstitution>(this, VarName, InsertIdx));
811 return Substitutions.back().get();
812}
813
814FileCheckSubstitution *FileCheckPatternContext::makeNumericSubstitution(
815 StringRef Expr, FileCheckNumExpr *NumExpr, size_t InsertIdx) {
816 Substitutions.push_back(llvm::make_unique<FileCheckNumericSubstitution>(
817 this, Expr, NumExpr, InsertIdx));
818 return Substitutions.back().get();
819}
820
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000821size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
822 // Offset keeps track of the current offset within the input Str
823 size_t Offset = 0;
824 // [...] Nesting depth
825 size_t BracketDepth = 0;
826
827 while (!Str.empty()) {
828 if (Str.startswith("]]") && BracketDepth == 0)
829 return Offset;
830 if (Str[0] == '\\') {
831 // Backslash escapes the next char within regexes, so skip them both.
832 Str = Str.substr(2);
833 Offset += 2;
834 } else {
835 switch (Str[0]) {
836 default:
837 break;
838 case '[':
839 BracketDepth++;
840 break;
841 case ']':
842 if (BracketDepth == 0) {
843 SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
844 SourceMgr::DK_Error,
845 "missing closing \"]\" for regex variable");
846 exit(1);
847 }
848 BracketDepth--;
849 break;
850 }
851 Str = Str.substr(1);
852 Offset++;
853 }
854 }
855
856 return StringRef::npos;
857}
858
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +0000859StringRef FileCheck::CanonicalizeFile(MemoryBuffer &MB,
860 SmallVectorImpl<char> &OutputBuffer) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000861 OutputBuffer.reserve(MB.getBufferSize());
862
863 for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
864 Ptr != End; ++Ptr) {
865 // Eliminate trailing dosish \r.
866 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
867 continue;
868 }
869
870 // If current char is not a horizontal whitespace or if horizontal
871 // whitespace canonicalization is disabled, dump it to output as is.
872 if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
873 OutputBuffer.push_back(*Ptr);
874 continue;
875 }
876
877 // Otherwise, add one space and advance over neighboring space.
878 OutputBuffer.push_back(' ');
879 while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
880 ++Ptr;
881 }
882
883 // Add a null byte and then return all but that byte.
884 OutputBuffer.push_back('\0');
885 return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
886}
887
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000888FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
889 const Check::FileCheckType &CheckTy,
890 SMLoc CheckLoc, MatchType MatchTy,
891 SMRange InputRange)
892 : CheckTy(CheckTy), MatchTy(MatchTy) {
893 auto Start = SM.getLineAndColumn(InputRange.Start);
894 auto End = SM.getLineAndColumn(InputRange.End);
895 InputStartLine = Start.first;
896 InputStartCol = Start.second;
897 InputEndLine = End.first;
898 InputEndCol = End.second;
899 Start = SM.getLineAndColumn(CheckLoc);
900 CheckLine = Start.first;
901 CheckCol = Start.second;
902}
903
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000904static bool IsPartOfWord(char c) {
905 return (isalnum(c) || c == '-' || c == '_');
906}
907
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000908Check::FileCheckType &Check::FileCheckType::setCount(int C) {
Fedor Sergeev8477a3e2018-11-13 01:09:53 +0000909 assert(Count > 0 && "zero and negative counts are not supported");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000910 assert((C == 1 || Kind == CheckPlain) &&
911 "count supported only for plain CHECK directives");
912 Count = C;
913 return *this;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000914}
915
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000916std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
917 switch (Kind) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000918 case Check::CheckNone:
919 return "invalid";
920 case Check::CheckPlain:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000921 if (Count > 1)
922 return Prefix.str() + "-COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000923 return Prefix;
924 case Check::CheckNext:
925 return Prefix.str() + "-NEXT";
926 case Check::CheckSame:
927 return Prefix.str() + "-SAME";
928 case Check::CheckNot:
929 return Prefix.str() + "-NOT";
930 case Check::CheckDAG:
931 return Prefix.str() + "-DAG";
932 case Check::CheckLabel:
933 return Prefix.str() + "-LABEL";
934 case Check::CheckEmpty:
935 return Prefix.str() + "-EMPTY";
936 case Check::CheckEOF:
937 return "implicit EOF";
938 case Check::CheckBadNot:
939 return "bad NOT";
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000940 case Check::CheckBadCount:
941 return "bad COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000942 }
943 llvm_unreachable("unknown FileCheckType");
944}
945
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000946static std::pair<Check::FileCheckType, StringRef>
947FindCheckType(StringRef Buffer, StringRef Prefix) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000948 if (Buffer.size() <= Prefix.size())
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000949 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000950
951 char NextChar = Buffer[Prefix.size()];
952
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000953 StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000954 // Verify that the : is present after the prefix.
955 if (NextChar == ':')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000956 return {Check::CheckPlain, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000957
958 if (NextChar != '-')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000959 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000960
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000961 if (Rest.consume_front("COUNT-")) {
962 int64_t Count;
963 if (Rest.consumeInteger(10, Count))
964 // Error happened in parsing integer.
965 return {Check::CheckBadCount, Rest};
966 if (Count <= 0 || Count > INT32_MAX)
967 return {Check::CheckBadCount, Rest};
968 if (!Rest.consume_front(":"))
969 return {Check::CheckBadCount, Rest};
970 return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
971 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000972
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000973 if (Rest.consume_front("NEXT:"))
974 return {Check::CheckNext, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000975
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000976 if (Rest.consume_front("SAME:"))
977 return {Check::CheckSame, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000978
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000979 if (Rest.consume_front("NOT:"))
980 return {Check::CheckNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000981
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000982 if (Rest.consume_front("DAG:"))
983 return {Check::CheckDAG, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000984
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000985 if (Rest.consume_front("LABEL:"))
986 return {Check::CheckLabel, Rest};
987
988 if (Rest.consume_front("EMPTY:"))
989 return {Check::CheckEmpty, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000990
991 // You can't combine -NOT with another suffix.
992 if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
993 Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
994 Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
995 Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000996 return {Check::CheckBadNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000997
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000998 return {Check::CheckNone, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000999}
1000
1001// From the given position, find the next character after the word.
1002static size_t SkipWord(StringRef Str, size_t Loc) {
1003 while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
1004 ++Loc;
1005 return Loc;
1006}
1007
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +00001008/// Searches the buffer for the first prefix in the prefix regular expression.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001009///
1010/// This searches the buffer using the provided regular expression, however it
1011/// enforces constraints beyond that:
1012/// 1) The found prefix must not be a suffix of something that looks like
1013/// a valid prefix.
1014/// 2) The found prefix must be followed by a valid check type suffix using \c
1015/// FindCheckType above.
1016///
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +00001017/// \returns a pair of StringRefs into the Buffer, which combines:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001018/// - the first match of the regular expression to satisfy these two is
1019/// returned,
1020/// otherwise an empty StringRef is returned to indicate failure.
1021/// - buffer rewound to the location right after parsed suffix, for parsing
1022/// to continue from
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001023///
1024/// If this routine returns a valid prefix, it will also shrink \p Buffer to
1025/// start at the beginning of the returned prefix, increment \p LineNumber for
1026/// each new line consumed from \p Buffer, and set \p CheckTy to the type of
1027/// check found by examining the suffix.
1028///
1029/// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
1030/// is unspecified.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001031static std::pair<StringRef, StringRef>
1032FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer,
1033 unsigned &LineNumber, Check::FileCheckType &CheckTy) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001034 SmallVector<StringRef, 2> Matches;
1035
1036 while (!Buffer.empty()) {
1037 // Find the first (longest) match using the RE.
1038 if (!PrefixRE.match(Buffer, &Matches))
1039 // No match at all, bail.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001040 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001041
1042 StringRef Prefix = Matches[0];
1043 Matches.clear();
1044
1045 assert(Prefix.data() >= Buffer.data() &&
1046 Prefix.data() < Buffer.data() + Buffer.size() &&
1047 "Prefix doesn't start inside of buffer!");
1048 size_t Loc = Prefix.data() - Buffer.data();
1049 StringRef Skipped = Buffer.substr(0, Loc);
1050 Buffer = Buffer.drop_front(Loc);
1051 LineNumber += Skipped.count('\n');
1052
1053 // Check that the matched prefix isn't a suffix of some other check-like
1054 // word.
1055 // FIXME: This is a very ad-hoc check. it would be better handled in some
1056 // other way. Among other things it seems hard to distinguish between
1057 // intentional and unintentional uses of this feature.
1058 if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
1059 // Now extract the type.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001060 StringRef AfterSuffix;
1061 std::tie(CheckTy, AfterSuffix) = FindCheckType(Buffer, Prefix);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001062
1063 // If we've found a valid check type for this prefix, we're done.
1064 if (CheckTy != Check::CheckNone)
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001065 return {Prefix, AfterSuffix};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001066 }
1067
1068 // If we didn't successfully find a prefix, we need to skip this invalid
1069 // prefix and continue scanning. We directly skip the prefix that was
1070 // matched and any additional parts of that check-like word.
1071 Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
1072 }
1073
1074 // We ran out of buffer while skipping partial matches so give up.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001075 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001076}
1077
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001078bool FileCheck::ReadCheckFile(SourceMgr &SM, StringRef Buffer, Regex &PrefixRE,
1079 std::vector<FileCheckString> &CheckStrings) {
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001080 if (PatternContext.defineCmdlineVariables(Req.GlobalDefines, SM))
1081 return true;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001082
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001083 std::vector<FileCheckPattern> ImplicitNegativeChecks;
1084 for (const auto &PatternString : Req.ImplicitCheckNot) {
1085 // Create a buffer with fake command line content in order to display the
1086 // command line option responsible for the specific implicit CHECK-NOT.
1087 std::string Prefix = "-implicit-check-not='";
1088 std::string Suffix = "'";
1089 std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
1090 Prefix + PatternString + Suffix, "command line");
1091
1092 StringRef PatternInBuffer =
1093 CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
1094 SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
1095
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001096 ImplicitNegativeChecks.push_back(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001097 FileCheckPattern(Check::CheckNot, &PatternContext, 0));
1098 ImplicitNegativeChecks.back().parsePattern(PatternInBuffer,
1099 "IMPLICIT-CHECK", SM, Req);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001100 }
1101
1102 std::vector<FileCheckPattern> DagNotMatches = ImplicitNegativeChecks;
1103
1104 // LineNumber keeps track of the line on which CheckPrefix instances are
1105 // found.
1106 unsigned LineNumber = 1;
1107
1108 while (1) {
1109 Check::FileCheckType CheckTy;
1110
1111 // See if a prefix occurs in the memory buffer.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001112 StringRef UsedPrefix;
1113 StringRef AfterSuffix;
1114 std::tie(UsedPrefix, AfterSuffix) =
1115 FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, CheckTy);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001116 if (UsedPrefix.empty())
1117 break;
1118 assert(UsedPrefix.data() == Buffer.data() &&
1119 "Failed to move Buffer's start forward, or pointed prefix outside "
1120 "of the buffer!");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001121 assert(AfterSuffix.data() >= Buffer.data() &&
1122 AfterSuffix.data() < Buffer.data() + Buffer.size() &&
1123 "Parsing after suffix doesn't start inside of buffer!");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001124
1125 // Location to use for error messages.
1126 const char *UsedPrefixStart = UsedPrefix.data();
1127
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001128 // Skip the buffer to the end of parsed suffix (or just prefix, if no good
1129 // suffix was processed).
1130 Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
1131 : AfterSuffix;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001132
1133 // Complain about useful-looking but unsupported suffixes.
1134 if (CheckTy == Check::CheckBadNot) {
1135 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
1136 "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
1137 return true;
1138 }
1139
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001140 // Complain about invalid count specification.
1141 if (CheckTy == Check::CheckBadCount) {
1142 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
1143 "invalid count in -COUNT specification on prefix '" +
1144 UsedPrefix + "'");
1145 return true;
1146 }
1147
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001148 // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
1149 // leading whitespace.
1150 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
1151 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
1152
1153 // Scan ahead to the end of line.
1154 size_t EOL = Buffer.find_first_of("\n\r");
1155
1156 // Remember the location of the start of the pattern, for diagnostics.
1157 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
1158
1159 // Parse the pattern.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001160 FileCheckPattern P(CheckTy, &PatternContext, LineNumber);
1161 if (P.parsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, Req))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001162 return true;
1163
1164 // Verify that CHECK-LABEL lines do not define or use variables
1165 if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
1166 SM.PrintMessage(
1167 SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
1168 "found '" + UsedPrefix + "-LABEL:'"
1169 " with variable definition or use");
1170 return true;
1171 }
1172
1173 Buffer = Buffer.substr(EOL);
1174
1175 // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
1176 if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
1177 CheckTy == Check::CheckEmpty) &&
1178 CheckStrings.empty()) {
1179 StringRef Type = CheckTy == Check::CheckNext
1180 ? "NEXT"
1181 : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
1182 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
1183 SourceMgr::DK_Error,
1184 "found '" + UsedPrefix + "-" + Type +
1185 "' without previous '" + UsedPrefix + ": line");
1186 return true;
1187 }
1188
1189 // Handle CHECK-DAG/-NOT.
1190 if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
1191 DagNotMatches.push_back(P);
1192 continue;
1193 }
1194
1195 // Okay, add the string we captured to the output vector and move on.
1196 CheckStrings.emplace_back(P, UsedPrefix, PatternLoc);
1197 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1198 DagNotMatches = ImplicitNegativeChecks;
1199 }
1200
1201 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
1202 // prefix as a filler for the error message.
1203 if (!DagNotMatches.empty()) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001204 CheckStrings.emplace_back(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001205 FileCheckPattern(Check::CheckEOF, &PatternContext, LineNumber + 1),
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001206 *Req.CheckPrefixes.begin(), SMLoc::getFromPointer(Buffer.data()));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001207 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1208 }
1209
1210 if (CheckStrings.empty()) {
1211 errs() << "error: no check strings found with prefix"
1212 << (Req.CheckPrefixes.size() > 1 ? "es " : " ");
1213 auto I = Req.CheckPrefixes.begin();
1214 auto E = Req.CheckPrefixes.end();
1215 if (I != E) {
1216 errs() << "\'" << *I << ":'";
1217 ++I;
1218 }
1219 for (; I != E; ++I)
1220 errs() << ", \'" << *I << ":'";
1221
1222 errs() << '\n';
1223 return true;
1224 }
1225
1226 return false;
1227}
1228
1229static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
1230 StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001231 int MatchedCount, StringRef Buffer, size_t MatchPos,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001232 size_t MatchLen, const FileCheckRequest &Req,
1233 std::vector<FileCheckDiag> *Diags) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001234 bool PrintDiag = true;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001235 if (ExpectedMatch) {
1236 if (!Req.Verbose)
1237 return;
1238 if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
1239 return;
Joel E. Denny352695c2019-01-22 21:41:42 +00001240 // Due to their verbosity, we don't print verbose diagnostics here if we're
1241 // gathering them for a different rendering, but we always print other
1242 // diagnostics.
1243 PrintDiag = !Diags;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001244 }
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001245 SMRange MatchRange = ProcessMatchResult(
Joel E. Dennye2afb612018-12-18 00:03:51 +00001246 ExpectedMatch ? FileCheckDiag::MatchFoundAndExpected
1247 : FileCheckDiag::MatchFoundButExcluded,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001248 SM, Loc, Pat.getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
Joel E. Denny352695c2019-01-22 21:41:42 +00001249 if (!PrintDiag)
1250 return;
1251
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001252 std::string Message = formatv("{0}: {1} string found in input",
1253 Pat.getCheckTy().getDescription(Prefix),
1254 (ExpectedMatch ? "expected" : "excluded"))
1255 .str();
1256 if (Pat.getCount() > 1)
1257 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
1258
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001259 SM.PrintMessage(
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001260 Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001261 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
1262 {MatchRange});
Thomas Preud'homme288ed912019-05-02 00:04:38 +00001263 Pat.printSubstitutions(SM, Buffer, MatchRange);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001264}
1265
1266static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001267 const FileCheckString &CheckStr, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001268 StringRef Buffer, size_t MatchPos, size_t MatchLen,
1269 FileCheckRequest &Req,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001270 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001271 PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001272 MatchedCount, Buffer, MatchPos, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001273}
1274
1275static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001276 StringRef Prefix, SMLoc Loc,
1277 const FileCheckPattern &Pat, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001278 StringRef Buffer, bool VerboseVerbose,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001279 std::vector<FileCheckDiag> *Diags) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001280 bool PrintDiag = true;
1281 if (!ExpectedMatch) {
1282 if (!VerboseVerbose)
1283 return;
1284 // Due to their verbosity, we don't print verbose diagnostics here if we're
1285 // gathering them for a different rendering, but we always print other
1286 // diagnostics.
1287 PrintDiag = !Diags;
1288 }
1289
1290 // If the current position is at the end of a line, advance to the start of
1291 // the next line.
1292 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
1293 SMRange SearchRange = ProcessMatchResult(
1294 ExpectedMatch ? FileCheckDiag::MatchNoneButExpected
1295 : FileCheckDiag::MatchNoneAndExcluded,
1296 SM, Loc, Pat.getCheckTy(), Buffer, 0, Buffer.size(), Diags);
1297 if (!PrintDiag)
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001298 return;
1299
Joel E. Denny352695c2019-01-22 21:41:42 +00001300 // Print "not found" diagnostic.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001301 std::string Message = formatv("{0}: {1} string not found in input",
1302 Pat.getCheckTy().getDescription(Prefix),
1303 (ExpectedMatch ? "expected" : "excluded"))
1304 .str();
1305 if (Pat.getCount() > 1)
1306 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001307 SM.PrintMessage(
1308 Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001309
Joel E. Denny352695c2019-01-22 21:41:42 +00001310 // Print the "scanning from here" line.
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001311 SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001312
1313 // Allow the pattern to print additional information if desired.
Thomas Preud'homme288ed912019-05-02 00:04:38 +00001314 Pat.printSubstitutions(SM, Buffer);
Joel E. Denny96f0e842018-12-18 00:03:36 +00001315
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001316 if (ExpectedMatch)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001317 Pat.printFuzzyMatch(SM, Buffer, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001318}
1319
1320static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001321 const FileCheckString &CheckStr, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001322 StringRef Buffer, bool VerboseVerbose,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001323 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001324 PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001325 MatchedCount, Buffer, VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001326}
1327
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +00001328/// Counts the number of newlines in the specified range.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001329static unsigned CountNumNewlinesBetween(StringRef Range,
1330 const char *&FirstNewLine) {
1331 unsigned NumNewLines = 0;
1332 while (1) {
1333 // Scan for newline.
1334 Range = Range.substr(Range.find_first_of("\n\r"));
1335 if (Range.empty())
1336 return NumNewLines;
1337
1338 ++NumNewLines;
1339
1340 // Handle \n\r and \r\n as a single newline.
1341 if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
1342 (Range[0] != Range[1]))
1343 Range = Range.substr(1);
1344 Range = Range.substr(1);
1345
1346 if (NumNewLines == 1)
1347 FirstNewLine = Range.begin();
1348 }
1349}
1350
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001351size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001352 bool IsLabelScanMode, size_t &MatchLen,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001353 FileCheckRequest &Req,
1354 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001355 size_t LastPos = 0;
1356 std::vector<const FileCheckPattern *> NotStrings;
1357
1358 // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
1359 // bounds; we have not processed variable definitions within the bounded block
1360 // yet so cannot handle any final CHECK-DAG yet; this is handled when going
1361 // over the block again (including the last CHECK-LABEL) in normal mode.
1362 if (!IsLabelScanMode) {
1363 // Match "dag strings" (with mixed "not strings" if any).
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001364 LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001365 if (LastPos == StringRef::npos)
1366 return StringRef::npos;
1367 }
1368
1369 // Match itself from the last position after matching CHECK-DAG.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001370 size_t LastMatchEnd = LastPos;
1371 size_t FirstMatchPos = 0;
1372 // Go match the pattern Count times. Majority of patterns only match with
1373 // count 1 though.
1374 assert(Pat.getCount() != 0 && "pattern count can not be zero");
1375 for (int i = 1; i <= Pat.getCount(); i++) {
1376 StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
1377 size_t CurrentMatchLen;
1378 // get a match at current start point
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001379 size_t MatchPos = Pat.match(MatchBuffer, CurrentMatchLen, SM);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001380 if (i == 1)
1381 FirstMatchPos = LastPos + MatchPos;
1382
1383 // report
1384 if (MatchPos == StringRef::npos) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001385 PrintNoMatch(true, SM, *this, i, MatchBuffer, Req.VerboseVerbose, Diags);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001386 return StringRef::npos;
1387 }
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001388 PrintMatch(true, SM, *this, i, MatchBuffer, MatchPos, CurrentMatchLen, Req,
1389 Diags);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001390
1391 // move start point after the match
1392 LastMatchEnd += MatchPos + CurrentMatchLen;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001393 }
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001394 // Full match len counts from first match pos.
1395 MatchLen = LastMatchEnd - FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001396
1397 // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1398 // or CHECK-NOT
1399 if (!IsLabelScanMode) {
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001400 size_t MatchPos = FirstMatchPos - LastPos;
1401 StringRef MatchBuffer = Buffer.substr(LastPos);
1402 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001403
1404 // If this check is a "CHECK-NEXT", verify that the previous match was on
1405 // the previous line (i.e. that there is one newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001406 if (CheckNext(SM, SkippedRegion)) {
Joel E. Dennye2afb612018-12-18 00:03:51 +00001407 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001408 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001409 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001410 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001411 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001412
1413 // If this check is a "CHECK-SAME", verify that the previous match was on
1414 // the same line (i.e. that there is no newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001415 if (CheckSame(SM, SkippedRegion)) {
Joel E. Dennye2afb612018-12-18 00:03:51 +00001416 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001417 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001418 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001419 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001420 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001421
1422 // If this match had "not strings", verify that they don't exist in the
1423 // skipped region.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001424 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001425 return StringRef::npos;
1426 }
1427
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001428 return FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001429}
1430
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001431bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1432 if (Pat.getCheckTy() != Check::CheckNext &&
1433 Pat.getCheckTy() != Check::CheckEmpty)
1434 return false;
1435
1436 Twine CheckName =
1437 Prefix +
1438 Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
1439
1440 // Count the number of newlines between the previous match and this one.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001441 const char *FirstNewLine = nullptr;
1442 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1443
1444 if (NumNewLines == 0) {
1445 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1446 CheckName + ": is on the same line as previous match");
1447 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1448 "'next' match was here");
1449 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1450 "previous match ended here");
1451 return true;
1452 }
1453
1454 if (NumNewLines != 1) {
1455 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1456 CheckName +
1457 ": is not on the line after the previous match");
1458 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1459 "'next' match was here");
1460 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1461 "previous match ended here");
1462 SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
1463 "non-matching line after previous match is here");
1464 return true;
1465 }
1466
1467 return false;
1468}
1469
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001470bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
1471 if (Pat.getCheckTy() != Check::CheckSame)
1472 return false;
1473
1474 // Count the number of newlines between the previous match and this one.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001475 const char *FirstNewLine = nullptr;
1476 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1477
1478 if (NumNewLines != 0) {
1479 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1480 Prefix +
1481 "-SAME: is not on the same line as the previous match");
1482 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1483 "'next' match was here");
1484 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1485 "previous match ended here");
1486 return true;
1487 }
1488
1489 return false;
1490}
1491
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001492bool FileCheckString::CheckNot(
1493 const SourceMgr &SM, StringRef Buffer,
1494 const std::vector<const FileCheckPattern *> &NotStrings,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001495 const FileCheckRequest &Req, std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001496 for (const FileCheckPattern *Pat : NotStrings) {
1497 assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1498
1499 size_t MatchLen = 0;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001500 size_t Pos = Pat->match(Buffer, MatchLen, SM);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001501
1502 if (Pos == StringRef::npos) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001503 PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001504 Req.VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001505 continue;
1506 }
1507
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001508 PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, Pos, MatchLen,
1509 Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001510
1511 return true;
1512 }
1513
1514 return false;
1515}
1516
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001517size_t
1518FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1519 std::vector<const FileCheckPattern *> &NotStrings,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001520 const FileCheckRequest &Req,
1521 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001522 if (DagNotStrings.empty())
1523 return 0;
1524
1525 // The start of the search range.
1526 size_t StartPos = 0;
1527
1528 struct MatchRange {
1529 size_t Pos;
1530 size_t End;
1531 };
1532 // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
1533 // ranges are erased from this list once they are no longer in the search
1534 // range.
1535 std::list<MatchRange> MatchRanges;
1536
1537 // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
1538 // group, so we don't use a range-based for loop here.
1539 for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
1540 PatItr != PatEnd; ++PatItr) {
1541 const FileCheckPattern &Pat = *PatItr;
1542 assert((Pat.getCheckTy() == Check::CheckDAG ||
1543 Pat.getCheckTy() == Check::CheckNot) &&
1544 "Invalid CHECK-DAG or CHECK-NOT!");
1545
1546 if (Pat.getCheckTy() == Check::CheckNot) {
1547 NotStrings.push_back(&Pat);
1548 continue;
1549 }
1550
1551 assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1552
1553 // CHECK-DAG always matches from the start.
1554 size_t MatchLen = 0, MatchPos = StartPos;
1555
1556 // Search for a match that doesn't overlap a previous match in this
1557 // CHECK-DAG group.
1558 for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
1559 StringRef MatchBuffer = Buffer.substr(MatchPos);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001560 size_t MatchPosBuf = Pat.match(MatchBuffer, MatchLen, SM);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001561 // With a group of CHECK-DAGs, a single mismatching means the match on
1562 // that group of CHECK-DAGs fails immediately.
1563 if (MatchPosBuf == StringRef::npos) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001564 PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001565 Req.VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001566 return StringRef::npos;
1567 }
1568 // Re-calc it as the offset relative to the start of the original string.
1569 MatchPos += MatchPosBuf;
1570 if (Req.VerboseVerbose)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001571 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1572 MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001573 MatchRange M{MatchPos, MatchPos + MatchLen};
1574 if (Req.AllowDeprecatedDagOverlap) {
1575 // We don't need to track all matches in this mode, so we just maintain
1576 // one match range that encompasses the current CHECK-DAG group's
1577 // matches.
1578 if (MatchRanges.empty())
1579 MatchRanges.insert(MatchRanges.end(), M);
1580 else {
1581 auto Block = MatchRanges.begin();
1582 Block->Pos = std::min(Block->Pos, M.Pos);
1583 Block->End = std::max(Block->End, M.End);
1584 }
1585 break;
1586 }
1587 // Iterate previous matches until overlapping match or insertion point.
1588 bool Overlap = false;
1589 for (; MI != ME; ++MI) {
1590 if (M.Pos < MI->End) {
1591 // !Overlap => New match has no overlap and is before this old match.
1592 // Overlap => New match overlaps this old match.
1593 Overlap = MI->Pos < M.End;
1594 break;
1595 }
1596 }
1597 if (!Overlap) {
1598 // Insert non-overlapping match into list.
1599 MatchRanges.insert(MI, M);
1600 break;
1601 }
1602 if (Req.VerboseVerbose) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001603 // Due to their verbosity, we don't print verbose diagnostics here if
1604 // we're gathering them for a different rendering, but we always print
1605 // other diagnostics.
1606 if (!Diags) {
1607 SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
1608 SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
1609 SMRange OldRange(OldStart, OldEnd);
1610 SM.PrintMessage(OldStart, SourceMgr::DK_Note,
1611 "match discarded, overlaps earlier DAG match here",
1612 {OldRange});
1613 } else
Joel E. Dennye2afb612018-12-18 00:03:51 +00001614 Diags->rbegin()->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001615 }
1616 MatchPos = MI->End;
1617 }
1618 if (!Req.VerboseVerbose)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001619 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1620 MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001621
1622 // Handle the end of a CHECK-DAG group.
1623 if (std::next(PatItr) == PatEnd ||
1624 std::next(PatItr)->getCheckTy() == Check::CheckNot) {
1625 if (!NotStrings.empty()) {
1626 // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
1627 // CHECK-DAG, verify that there are no 'not' strings occurred in that
1628 // region.
1629 StringRef SkippedRegion =
1630 Buffer.slice(StartPos, MatchRanges.begin()->Pos);
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001631 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001632 return StringRef::npos;
1633 // Clear "not strings".
1634 NotStrings.clear();
1635 }
1636 // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
1637 // end of this CHECK-DAG group's match range.
1638 StartPos = MatchRanges.rbegin()->End;
1639 // Don't waste time checking for (impossible) overlaps before that.
1640 MatchRanges.clear();
1641 }
1642 }
1643
1644 return StartPos;
1645}
1646
1647// A check prefix must contain only alphanumeric, hyphens and underscores.
1648static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1649 Regex Validator("^[a-zA-Z0-9_-]*$");
1650 return Validator.match(CheckPrefix);
1651}
1652
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001653bool FileCheck::ValidateCheckPrefixes() {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001654 StringSet<> PrefixSet;
1655
1656 for (StringRef Prefix : Req.CheckPrefixes) {
1657 // Reject empty prefixes.
1658 if (Prefix == "")
1659 return false;
1660
1661 if (!PrefixSet.insert(Prefix).second)
1662 return false;
1663
1664 if (!ValidateCheckPrefix(Prefix))
1665 return false;
1666 }
1667
1668 return true;
1669}
1670
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001671Regex FileCheck::buildCheckPrefixRegex() {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001672 // I don't think there's a way to specify an initial value for cl::list,
1673 // so if nothing was specified, add the default
1674 if (Req.CheckPrefixes.empty())
1675 Req.CheckPrefixes.push_back("CHECK");
1676
1677 // We already validated the contents of CheckPrefixes so just concatenate
1678 // them as alternatives.
1679 SmallString<32> PrefixRegexStr;
1680 for (StringRef Prefix : Req.CheckPrefixes) {
1681 if (Prefix != Req.CheckPrefixes.front())
1682 PrefixRegexStr.push_back('|');
1683
1684 PrefixRegexStr.append(Prefix);
1685 }
1686
1687 return Regex(PrefixRegexStr);
1688}
1689
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001690bool FileCheckPatternContext::defineCmdlineVariables(
1691 std::vector<std::string> &CmdlineDefines, SourceMgr &SM) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001692 assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001693 "Overriding defined variable with command-line variable definitions");
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001694
1695 if (CmdlineDefines.empty())
1696 return false;
1697
1698 // Create a string representing the vector of command-line definitions. Each
1699 // definition is on its own line and prefixed with a definition number to
1700 // clarify which definition a given diagnostic corresponds to.
1701 unsigned I = 0;
1702 bool ErrorFound = false;
1703 std::string CmdlineDefsDiag;
1704 StringRef Prefix1 = "Global define #";
1705 StringRef Prefix2 = ": ";
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001706 for (StringRef CmdlineDef : CmdlineDefines)
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001707 CmdlineDefsDiag +=
1708 (Prefix1 + Twine(++I) + Prefix2 + CmdlineDef + "\n").str();
1709
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001710 // Create a buffer with fake command line content in order to display
1711 // parsing diagnostic with location information and point to the
1712 // global definition with invalid syntax.
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001713 std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
1714 MemoryBuffer::getMemBufferCopy(CmdlineDefsDiag, "Global defines");
1715 StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
1716 SM.AddNewSourceBuffer(std::move(CmdLineDefsDiagBuffer), SMLoc());
1717
1718 SmallVector<StringRef, 4> CmdlineDefsDiagVec;
1719 CmdlineDefsDiagRef.split(CmdlineDefsDiagVec, '\n', -1 /*MaxSplit*/,
1720 false /*KeepEmpty*/);
1721 for (StringRef CmdlineDefDiag : CmdlineDefsDiagVec) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001722 unsigned DefStart = CmdlineDefDiag.find(Prefix2) + Prefix2.size();
1723 StringRef CmdlineDef = CmdlineDefDiag.substr(DefStart);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001724 size_t EqIdx = CmdlineDef.find('=');
1725 if (EqIdx == StringRef::npos) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001726 SM.PrintMessage(SMLoc::getFromPointer(CmdlineDef.data()),
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001727 SourceMgr::DK_Error,
1728 "Missing equal sign in global definition");
1729 ErrorFound = true;
1730 continue;
1731 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001732
1733 // Numeric variable definition.
1734 if (CmdlineDef[0] == '#') {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001735 StringRef CmdlineName = CmdlineDef.substr(1, EqIdx - 1);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001736 StringRef VarName;
1737 SMLoc CmdlineNameLoc = SMLoc::getFromPointer(CmdlineName.data());
1738 bool ParseError = FileCheckPattern::parseNumericVariableDefinition(
1739 CmdlineName, VarName, this, SM);
1740 // Check that CmdlineName starts with a valid numeric variable to be
1741 // defined and that it is not followed that anything. That second check
1742 // detects cases like "FOO+2" in a "FOO+2=10" definition.
1743 if (ParseError || !CmdlineName.empty()) {
1744 if (!ParseError)
1745 SM.PrintMessage(CmdlineNameLoc, SourceMgr::DK_Error,
1746 "invalid variable name");
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001747 ErrorFound = true;
1748 continue;
1749 }
1750
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001751 // Detect collisions between string and numeric variables when the latter
1752 // is created later than the former.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001753 if (DefinedVariableTable.find(VarName) != DefinedVariableTable.end()) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001754 SM.PrintMessage(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001755 SMLoc::getFromPointer(VarName.data()), SourceMgr::DK_Error,
1756 "string variable with name '" + VarName + "' already exists");
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001757 ErrorFound = true;
1758 continue;
1759 }
1760
1761 StringRef CmdlineVal = CmdlineDef.substr(EqIdx + 1);
1762 uint64_t Val;
1763 if (CmdlineVal.getAsInteger(10, Val)) {
1764 SM.PrintMessage(SMLoc::getFromPointer(CmdlineVal.data()),
1765 SourceMgr::DK_Error,
1766 "invalid value in numeric variable definition '" +
1767 CmdlineVal + "'");
1768 ErrorFound = true;
1769 continue;
1770 }
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001771 auto DefinedNumericVariable = makeNumericVariable(0, VarName);
1772 DefinedNumericVariable->setValue(Val);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001773
1774 // Record this variable definition.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001775 GlobalNumericVariableTable[DefinedNumericVariable->getName()] =
1776 DefinedNumericVariable;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001777 } else {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001778 // String variable definition.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001779 std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.split('=');
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001780 StringRef CmdlineName = CmdlineNameVal.first;
1781 StringRef OrigCmdlineName = CmdlineName;
1782 StringRef Name;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001783 bool IsPseudo;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001784 if (FileCheckPattern::parseVariable(CmdlineName, Name, IsPseudo) ||
1785 IsPseudo || !CmdlineName.empty()) {
1786 SM.PrintMessage(SMLoc::getFromPointer(OrigCmdlineName.data()),
1787 SourceMgr::DK_Error,
1788 "invalid name in string variable definition '" +
1789 OrigCmdlineName + "'");
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001790 ErrorFound = true;
1791 continue;
1792 }
1793
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001794 // Detect collisions between string and numeric variables when the former
1795 // is created later than the latter.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001796 if (GlobalNumericVariableTable.find(Name) !=
1797 GlobalNumericVariableTable.end()) {
1798 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
1799 "numeric variable with name '" + Name +
1800 "' already exists");
1801 ErrorFound = true;
1802 continue;
1803 }
1804 GlobalVariableTable.insert(CmdlineNameVal);
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001805 // Mark the string variable as defined to detect collisions between
1806 // string and numeric variables in DefineCmdlineVariables when the latter
1807 // is created later than the former. We cannot reuse GlobalVariableTable
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001808 // for this by populating it with an empty string since we would then
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001809 // lose the ability to detect the use of an undefined variable in
1810 // match().
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001811 DefinedVariableTable[Name] = true;
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001812 }
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001813 }
1814
1815 return ErrorFound;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001816}
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001817
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001818void FileCheckPatternContext::clearLocalVars() {
1819 SmallVector<StringRef, 16> LocalPatternVars, LocalNumericVars;
1820 for (const StringMapEntry<StringRef> &Var : GlobalVariableTable)
1821 if (Var.first()[0] != '$')
1822 LocalPatternVars.push_back(Var.first());
1823
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001824 // Numeric substitution reads the value of a variable directly, not via
1825 // GlobalNumericVariableTable. Therefore, we clear local variables by
1826 // clearing their value which will lead to a numeric substitution failure. We
1827 // also mark the variable for removal from GlobalNumericVariableTable since
1828 // this is what defineCmdlineVariables checks to decide that no global
1829 // variable has been defined.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001830 for (const auto &Var : GlobalNumericVariableTable)
1831 if (Var.first()[0] != '$') {
1832 Var.getValue()->clearValue();
1833 LocalNumericVars.push_back(Var.first());
1834 }
1835
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001836 for (const auto &Var : LocalPatternVars)
1837 GlobalVariableTable.erase(Var);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001838 for (const auto &Var : LocalNumericVars)
1839 GlobalNumericVariableTable.erase(Var);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001840}
1841
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001842bool FileCheck::CheckInput(SourceMgr &SM, StringRef Buffer,
1843 ArrayRef<FileCheckString> CheckStrings,
1844 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001845 bool ChecksFailed = false;
1846
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001847 unsigned i = 0, j = 0, e = CheckStrings.size();
1848 while (true) {
1849 StringRef CheckRegion;
1850 if (j == e) {
1851 CheckRegion = Buffer;
1852 } else {
1853 const FileCheckString &CheckLabelStr = CheckStrings[j];
1854 if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
1855 ++j;
1856 continue;
1857 }
1858
1859 // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1860 size_t MatchLabelLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001861 size_t MatchLabelPos =
1862 CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001863 if (MatchLabelPos == StringRef::npos)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001864 // Immediately bail if CHECK-LABEL fails, nothing else we can do.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001865 return false;
1866
1867 CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1868 Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1869 ++j;
1870 }
1871
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001872 // Do not clear the first region as it's the one before the first
1873 // CHECK-LABEL and it would clear variables defined on the command-line
1874 // before they get used.
1875 if (i != 0 && Req.EnableVarScope)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001876 PatternContext.clearLocalVars();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001877
1878 for (; i != j; ++i) {
1879 const FileCheckString &CheckStr = CheckStrings[i];
1880
1881 // Check each string within the scanned region, including a second check
1882 // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1883 size_t MatchLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001884 size_t MatchPos =
1885 CheckStr.Check(SM, CheckRegion, false, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001886
1887 if (MatchPos == StringRef::npos) {
1888 ChecksFailed = true;
1889 i = j;
1890 break;
1891 }
1892
1893 CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1894 }
1895
1896 if (j == e)
1897 break;
1898 }
1899
1900 // Success if no checks failed.
1901 return !ChecksFailed;
1902}