blob: f93dde26c3212775084ed3c7a01e62fb013b6bfe [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'hommea2ef1ba2019-06-19 23:47:24 +000041Expected<uint64_t> FileCheckExpression::eval() const {
42 assert(LeftOp && "Evaluating an empty expression");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +000043 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'hommebaae41f2019-06-19 23:47:10 +000046 return make_error<FileCheckUndefVarError>(LeftOp->getName());
Thomas Preud'homme71d3f222019-06-06 13:21:06 +000047 return EvalBinop(*LeftOpValue, RightOp);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000048}
49
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000050Expected<std::string> FileCheckNumericSubstitution::getResult() const {
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +000051 Expected<uint64_t> EvaluatedValue = Expression->eval();
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +000052 if (!EvaluatedValue)
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000053 return EvaluatedValue.takeError();
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +000054 return utostr(*EvaluatedValue);
55}
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000056
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000057Expected<std::string> FileCheckStringSubstitution::getResult() const {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000058 // Look up the value and escape it so that we can put it into the regex.
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000059 Expected<StringRef> VarVal = Context->getPatternVarValue(FromStr);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000060 if (!VarVal)
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000061 return VarVal.takeError();
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +000062 return Regex::escape(*VarVal);
Thomas Preud'homme288ed912019-05-02 00:04:38 +000063}
64
Thomas Preud'homme5a330472019-04-29 13:32:36 +000065bool FileCheckPattern::isValidVarNameStart(char C) {
66 return C == '_' || isalpha(C);
67}
68
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000069Expected<StringRef> FileCheckPattern::parseVariable(StringRef &Str,
70 bool &IsPseudo,
71 const SourceMgr &SM) {
Thomas Preud'homme5a330472019-04-29 13:32:36 +000072 if (Str.empty())
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000073 return FileCheckErrorDiagnostic::get(SM, Str, "empty variable name");
Thomas Preud'homme5a330472019-04-29 13:32:36 +000074
75 bool ParsedOneChar = false;
76 unsigned I = 0;
77 IsPseudo = Str[0] == '@';
78
79 // Global vars start with '$'.
80 if (Str[0] == '$' || IsPseudo)
81 ++I;
82
83 for (unsigned E = Str.size(); I != E; ++I) {
84 if (!ParsedOneChar && !isValidVarNameStart(Str[I]))
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000085 return FileCheckErrorDiagnostic::get(SM, Str, "invalid variable name");
Thomas Preud'homme5a330472019-04-29 13:32:36 +000086
87 // Variable names are composed of alphanumeric characters and underscores.
88 if (Str[I] != '_' && !isalnum(Str[I]))
89 break;
90 ParsedOneChar = true;
91 }
92
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000093 StringRef Name = Str.take_front(I);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +000094 Str = Str.substr(I);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +000095 return Name;
Thomas Preud'homme5a330472019-04-29 13:32:36 +000096}
97
Thomas Preud'homme288ed912019-05-02 00:04:38 +000098// StringRef holding all characters considered as horizontal whitespaces by
99// FileCheck input canonicalization.
100StringRef SpaceChars = " \t";
101
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000102// Parsing helper function that strips the first character in S and returns it.
103static char popFront(StringRef &S) {
104 char C = S.front();
105 S = S.drop_front();
106 return C;
107}
108
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000109char FileCheckUndefVarError::ID = 0;
110char FileCheckErrorDiagnostic::ID = 0;
111char FileCheckNotFoundError::ID = 0;
112
113Error FileCheckPattern::parseNumericVariableDefinition(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000114 StringRef &Expr, StringRef &Name, FileCheckPatternContext *Context,
115 const SourceMgr &SM) {
116 bool IsPseudo;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000117 Expected<StringRef> ParseVarResult = parseVariable(Expr, IsPseudo, SM);
118 if (!ParseVarResult)
119 return ParseVarResult.takeError();
120 Name = *ParseVarResult;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000121
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000122 if (IsPseudo)
123 return FileCheckErrorDiagnostic::get(
124 SM, Name, "definition of pseudo numeric variable unsupported");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000125
126 // Detect collisions between string and numeric variables when the latter
127 // is created later than the former.
128 if (Context->DefinedVariableTable.find(Name) !=
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000129 Context->DefinedVariableTable.end())
130 return FileCheckErrorDiagnostic::get(
131 SM, Name, "string variable with name '" + Name + "' already exists");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000132
Thomas Preud'homme28196a52019-07-05 12:01:06 +0000133 Expr = Expr.ltrim(SpaceChars);
134 if (!Expr.empty())
135 return FileCheckErrorDiagnostic::get(
136 SM, Expr, "unexpected characters after numeric variable name");
137
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000138 return Error::success();
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000139}
140
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000141Expected<FileCheckNumericVariable *>
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000142FileCheckPattern::parseNumericVariableUse(StringRef &Expr,
143 const SourceMgr &SM) const {
144 bool IsPseudo;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000145 Expected<StringRef> ParseVarResult = parseVariable(Expr, IsPseudo, SM);
146 if (!ParseVarResult)
147 return ParseVarResult.takeError();
148 StringRef Name = *ParseVarResult;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000149
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000150 if (IsPseudo && !Name.equals("@LINE"))
151 return FileCheckErrorDiagnostic::get(
152 SM, Name, "invalid pseudo numeric variable '" + Name + "'");
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000153
Thomas Preud'homme41f2bea2019-07-05 12:01:12 +0000154 // Numeric variable definitions and uses are parsed in the order in which
155 // they appear in the CHECK patterns. For each definition, the pointer to the
156 // class instance of the corresponding numeric variable definition is stored
157 // in GlobalNumericVariableTable in parsePattern. Therefore, the pointer we
158 // get below is for the class instance corresponding to the last definition
Thomas Preud'hommefe7ac172019-07-05 16:25:33 +0000159 // of this variable use. If we don't find a variable definition we create a
160 // dummy one so that parsing can continue. All uses of undefined variables,
161 // whether string or numeric, are then diagnosed in printSubstitutions()
162 // after failing to match.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000163 auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
Thomas Preud'hommefe7ac172019-07-05 16:25:33 +0000164 FileCheckNumericVariable *NumericVariable;
165 if (VarTableIter != Context->GlobalNumericVariableTable.end())
166 NumericVariable = VarTableIter->second;
167 else {
168 NumericVariable = Context->makeNumericVariable(0, Name);
169 Context->GlobalNumericVariableTable[Name] = NumericVariable;
170 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000171
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000172 if (!IsPseudo && NumericVariable->getDefLineNumber() == LineNumber)
173 return FileCheckErrorDiagnostic::get(
174 SM, Name,
175 "numeric variable '" + Name + "' defined on the same line as used");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000176
177 return NumericVariable;
178}
179
180static uint64_t add(uint64_t LeftOp, uint64_t RightOp) {
181 return LeftOp + RightOp;
182}
183
184static uint64_t sub(uint64_t LeftOp, uint64_t RightOp) {
185 return LeftOp - RightOp;
186}
187
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000188Expected<FileCheckExpression *>
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000189FileCheckPattern::parseBinop(StringRef &Expr, const SourceMgr &SM) const {
190 Expected<FileCheckNumericVariable *> LeftParseResult =
191 parseNumericVariableUse(Expr, SM);
192 if (!LeftParseResult) {
193 return LeftParseResult.takeError();
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000194 }
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000195 FileCheckNumericVariable *LeftOp = *LeftParseResult;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000196
197 // Check if this is a supported operation and select a function to perform
198 // it.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000199 Expr = Expr.ltrim(SpaceChars);
200 if (Expr.empty())
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000201 return Context->makeExpression(add, LeftOp, 0);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000202 SMLoc OpLoc = SMLoc::getFromPointer(Expr.data());
203 char Operator = popFront(Expr);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000204 binop_eval_t EvalBinop;
205 switch (Operator) {
206 case '+':
207 EvalBinop = add;
208 break;
209 case '-':
210 EvalBinop = sub;
211 break;
212 default:
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000213 return FileCheckErrorDiagnostic::get(
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000214 SM, OpLoc, Twine("unsupported operation '") + Twine(Operator) + "'");
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000215 }
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000216
217 // Parse right operand.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000218 Expr = Expr.ltrim(SpaceChars);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000219 if (Expr.empty())
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000220 return FileCheckErrorDiagnostic::get(SM, Expr,
221 "missing operand in expression");
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000222 uint64_t RightOp;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000223 if (Expr.consumeInteger(10, RightOp))
224 return FileCheckErrorDiagnostic::get(
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000225 SM, Expr, "invalid offset in expression '" + Expr + "'");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000226 Expr = Expr.ltrim(SpaceChars);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000227 if (!Expr.empty())
228 return FileCheckErrorDiagnostic::get(
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000229 SM, Expr, "unexpected characters at end of expression '" + Expr + "'");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000230
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000231 return Context->makeExpression(EvalBinop, LeftOp, RightOp);
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000232}
233
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000234Expected<FileCheckExpression *> FileCheckPattern::parseNumericSubstitutionBlock(
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000235 StringRef Expr,
236 Optional<FileCheckNumericVariable *> &DefinedNumericVariable,
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000237 const SourceMgr &SM) const {
238 // Parse the numeric variable definition.
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000239 DefinedNumericVariable = None;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000240 size_t DefEnd = Expr.find(':');
241 if (DefEnd != StringRef::npos) {
242 StringRef DefExpr = Expr.substr(0, DefEnd);
Thomas Preud'homme28196a52019-07-05 12:01:06 +0000243 StringRef UseExpr = Expr.substr(DefEnd + 1);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000244
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000245 UseExpr = UseExpr.ltrim(SpaceChars);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000246 if (!UseExpr.empty())
247 return FileCheckErrorDiagnostic::get(
248 SM, UseExpr,
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000249 "unexpected string after variable definition: '" + UseExpr + "'");
Thomas Preud'homme28196a52019-07-05 12:01:06 +0000250
251 DefExpr = DefExpr.ltrim(SpaceChars);
252 StringRef Name;
253 Error Err = parseNumericVariableDefinition(DefExpr, Name, Context, SM);
254 if (Err)
255 return std::move(Err);
256 DefinedNumericVariable = Context->makeNumericVariable(LineNumber, Name);
257
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000258 return Context->makeExpression(add, nullptr, 0);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000259 }
260
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000261 // Parse the expression itself.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000262 Expr = Expr.ltrim(SpaceChars);
263 return parseBinop(Expr, SM);
264}
265
266bool FileCheckPattern::parsePattern(StringRef PatternStr, StringRef Prefix,
267 SourceMgr &SM,
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000268 const FileCheckRequest &Req) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000269 bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
270
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000271 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
272
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000273 // Create fake @LINE pseudo variable definition.
274 StringRef LinePseudo = "@LINE";
275 uint64_t LineNumber64 = LineNumber;
276 FileCheckNumericVariable *LinePseudoVar =
277 Context->makeNumericVariable(LinePseudo, LineNumber64);
278 Context->GlobalNumericVariableTable[LinePseudo] = LinePseudoVar;
279
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000280 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
281 // Ignore trailing whitespace.
282 while (!PatternStr.empty() &&
283 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
284 PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
285
286 // Check that there is something on the line.
287 if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
288 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
289 "found empty check string with prefix '" + Prefix + ":'");
290 return true;
291 }
292
293 if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
294 SM.PrintMessage(
295 PatternLoc, SourceMgr::DK_Error,
296 "found non-empty check string for empty check with prefix '" + Prefix +
297 ":'");
298 return true;
299 }
300
301 if (CheckTy == Check::CheckEmpty) {
302 RegExStr = "(\n$)";
303 return false;
304 }
305
306 // Check to see if this is a fixed string, or if it has regex pieces.
307 if (!MatchFullLinesHere &&
308 (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
309 PatternStr.find("[[") == StringRef::npos))) {
310 FixedStr = PatternStr;
311 return false;
312 }
313
314 if (MatchFullLinesHere) {
315 RegExStr += '^';
316 if (!Req.NoCanonicalizeWhiteSpace)
317 RegExStr += " *";
318 }
319
320 // Paren value #0 is for the fully matched string. Any new parenthesized
321 // values add from there.
322 unsigned CurParen = 1;
323
324 // Otherwise, there is at least one regex piece. Build up the regex pattern
325 // by escaping scary characters in fixed strings, building up one big regex.
326 while (!PatternStr.empty()) {
327 // RegEx matches.
328 if (PatternStr.startswith("{{")) {
329 // This is the start of a regex match. Scan for the }}.
330 size_t End = PatternStr.find("}}");
331 if (End == StringRef::npos) {
332 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
333 SourceMgr::DK_Error,
334 "found start of regex string with no end '}}'");
335 return true;
336 }
337
338 // Enclose {{}} patterns in parens just like [[]] even though we're not
339 // capturing the result for any purpose. This is required in case the
340 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
341 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
342 RegExStr += '(';
343 ++CurParen;
344
345 if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
346 return true;
347 RegExStr += ')';
348
349 PatternStr = PatternStr.substr(End + 2);
350 continue;
351 }
352
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000353 // String and numeric substitution blocks. String substitution blocks come
354 // in two forms: [[foo:.*]] and [[foo]]. The former matches .* (or some
355 // other regex) and assigns it to the string variable 'foo'. The latter
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000356 // substitutes foo's value. Numeric substitution blocks work the same way
357 // as string ones, but start with a '#' sign after the double brackets.
358 // Both string and numeric variable names must satisfy the regular
359 // expression "[a-zA-Z_][0-9a-zA-Z_]*" to be valid, as this helps catch
360 // some common errors.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000361 if (PatternStr.startswith("[[")) {
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000362 StringRef UnparsedPatternStr = PatternStr.substr(2);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000363 // Find the closing bracket pair ending the match. End is going to be an
364 // offset relative to the beginning of the match string.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000365 size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
366 StringRef MatchStr = UnparsedPatternStr.substr(0, End);
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000367 bool IsNumBlock = MatchStr.consume_front("#");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000368
369 if (End == StringRef::npos) {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000370 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
371 SourceMgr::DK_Error,
372 "Invalid substitution block, no ]] found");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000373 return true;
374 }
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000375 // Strip the substitution block we are parsing. End points to the start
376 // of the "]]" closing the expression so account for it in computing the
377 // index of the first unparsed character.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000378 PatternStr = UnparsedPatternStr.substr(End + 2);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000379
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000380 bool IsDefinition = false;
381 StringRef DefName;
382 StringRef SubstStr;
383 StringRef MatchRegexp;
384 size_t SubstInsertIdx = RegExStr.size();
385
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000386 // Parse string variable or legacy expression.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000387 if (!IsNumBlock) {
388 size_t VarEndIdx = MatchStr.find(":");
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000389 size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
390 if (SpacePos != StringRef::npos) {
391 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
392 SourceMgr::DK_Error, "unexpected whitespace");
393 return true;
394 }
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000395
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000396 // Get the name (e.g. "foo") and verify it is well formed.
397 bool IsPseudo;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000398 StringRef OrigMatchStr = MatchStr;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000399 Expected<StringRef> ParseVarResult =
400 parseVariable(MatchStr, IsPseudo, SM);
401 if (!ParseVarResult) {
402 logAllUnhandledErrors(ParseVarResult.takeError(), errs());
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000403 return true;
404 }
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000405 StringRef Name = *ParseVarResult;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000406
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000407 IsDefinition = (VarEndIdx != StringRef::npos);
408 if (IsDefinition) {
409 if ((IsPseudo || !MatchStr.consume_front(":"))) {
410 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
411 SourceMgr::DK_Error,
412 "invalid name in string variable definition");
413 return true;
414 }
415
416 // Detect collisions between string and numeric variables when the
417 // former is created later than the latter.
418 if (Context->GlobalNumericVariableTable.find(Name) !=
419 Context->GlobalNumericVariableTable.end()) {
420 SM.PrintMessage(
421 SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
422 "numeric variable with name '" + Name + "' already exists");
423 return true;
424 }
425 DefName = Name;
426 MatchRegexp = MatchStr;
427 } else {
428 if (IsPseudo) {
429 MatchStr = OrigMatchStr;
430 IsNumBlock = true;
431 } else
432 SubstStr = Name;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000433 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000434 }
435
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000436 // Parse numeric substitution block.
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000437 FileCheckExpression *Expression;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000438 Optional<FileCheckNumericVariable *> DefinedNumericVariable;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000439 if (IsNumBlock) {
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000440 Expected<FileCheckExpression *> ParseResult =
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000441 parseNumericSubstitutionBlock(MatchStr, DefinedNumericVariable, SM);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000442 if (!ParseResult) {
443 logAllUnhandledErrors(ParseResult.takeError(), errs());
Thomas Preud'homme15cb1f12019-04-29 17:46:26 +0000444 return true;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000445 }
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000446 Expression = *ParseResult;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000447 if (DefinedNumericVariable) {
448 IsDefinition = true;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000449 DefName = (*DefinedNumericVariable)->getName();
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000450 MatchRegexp = StringRef("[0-9]+");
451 } else
452 SubstStr = MatchStr;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000453 }
454
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000455 // Handle substitutions: [[foo]] and [[#<foo expr>]].
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000456 if (!IsDefinition) {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000457 // Handle substitution of string variables that were defined earlier on
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000458 // the same line by emitting a backreference. Expressions do not
459 // support substituting a numeric variable defined on the same line.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000460 if (!IsNumBlock && VariableDefs.find(SubstStr) != VariableDefs.end()) {
461 unsigned CaptureParenGroup = VariableDefs[SubstStr];
462 if (CaptureParenGroup < 1 || CaptureParenGroup > 9) {
463 SM.PrintMessage(SMLoc::getFromPointer(SubstStr.data()),
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000464 SourceMgr::DK_Error,
465 "Can't back-reference more than 9 variables");
466 return true;
467 }
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000468 AddBackrefToRegEx(CaptureParenGroup);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000469 } else {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000470 // Handle substitution of string variables ([[<var>]]) defined in
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000471 // previous CHECK patterns, and substitution of expressions.
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000472 FileCheckSubstitution *Substitution =
473 IsNumBlock
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000474 ? Context->makeNumericSubstitution(SubstStr, Expression,
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000475 SubstInsertIdx)
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000476 : Context->makeStringSubstitution(SubstStr, SubstInsertIdx);
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000477 Substitutions.push_back(Substitution);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000478 }
479 continue;
480 }
481
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000482 // Handle variable definitions: [[<def>:(...)]] and
483 // [[#(...)<def>:(...)]].
484 if (IsNumBlock) {
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000485 FileCheckNumericVariableMatch NumericVariableDefinition = {
486 *DefinedNumericVariable, CurParen};
487 NumericVariableDefs[DefName] = NumericVariableDefinition;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000488 // This store is done here rather than in match() to allow
489 // parseNumericVariableUse() to get the pointer to the class instance
490 // of the right variable definition corresponding to a given numeric
491 // variable use.
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000492 Context->GlobalNumericVariableTable[DefName] = *DefinedNumericVariable;
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000493 } else {
494 VariableDefs[DefName] = CurParen;
495 // Mark the string variable as defined to detect collisions between
496 // string and numeric variables in parseNumericVariableUse() and
497 // DefineCmdlineVariables() when the latter is created later than the
498 // former. We cannot reuse GlobalVariableTable for this by populating
499 // it with an empty string since we would then lose the ability to
500 // detect the use of an undefined variable in match().
501 Context->DefinedVariableTable[DefName] = true;
502 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000503 RegExStr += '(';
504 ++CurParen;
505
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000506 if (AddRegExToRegEx(MatchRegexp, CurParen, SM))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000507 return true;
508
509 RegExStr += ')';
510 }
511
512 // Handle fixed string matches.
513 // Find the end, which is the start of the next regex.
514 size_t FixedMatchEnd = PatternStr.find("{{");
515 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
516 RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
517 PatternStr = PatternStr.substr(FixedMatchEnd);
518 }
519
520 if (MatchFullLinesHere) {
521 if (!Req.NoCanonicalizeWhiteSpace)
522 RegExStr += " *";
523 RegExStr += '$';
524 }
525
526 return false;
527}
528
529bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
530 Regex R(RS);
531 std::string Error;
532 if (!R.isValid(Error)) {
533 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
534 "invalid regex: " + Error);
535 return true;
536 }
537
538 RegExStr += RS.str();
539 CurParen += R.getNumMatches();
540 return false;
541}
542
543void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
544 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
545 std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
546 RegExStr += Backref;
547}
548
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000549Expected<size_t> FileCheckPattern::match(StringRef Buffer, size_t &MatchLen,
550 const SourceMgr &SM) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000551 // If this is the EOF pattern, match it immediately.
552 if (CheckTy == Check::CheckEOF) {
553 MatchLen = 0;
554 return Buffer.size();
555 }
556
557 // If this is a fixed string pattern, just match it now.
558 if (!FixedStr.empty()) {
559 MatchLen = FixedStr.size();
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000560 size_t Pos = Buffer.find(FixedStr);
561 if (Pos == StringRef::npos)
562 return make_error<FileCheckNotFoundError>();
563 return Pos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000564 }
565
566 // Regex match.
567
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000568 // If there are substitutions, we need to create a temporary string with the
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000569 // actual value.
570 StringRef RegExToMatch = RegExStr;
571 std::string TmpStr;
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000572 if (!Substitutions.empty()) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000573 TmpStr = RegExStr;
574
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000575 size_t InsertOffset = 0;
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000576 // Substitute all string variables and expressions whose values are only
577 // now known. Use of string variables defined on the same line are handled
578 // by back-references.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000579 for (const auto &Substitution : Substitutions) {
580 // Substitute and check for failure (e.g. use of undefined variable).
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000581 Expected<std::string> Value = Substitution->getResult();
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000582 if (!Value)
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000583 return Value.takeError();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000584
585 // Plop it into the regex at the adjusted offset.
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000586 TmpStr.insert(TmpStr.begin() + Substitution->getIndex() + InsertOffset,
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000587 Value->begin(), Value->end());
588 InsertOffset += Value->size();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000589 }
590
591 // Match the newly constructed regex.
592 RegExToMatch = TmpStr;
593 }
594
595 SmallVector<StringRef, 4> MatchInfo;
596 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000597 return make_error<FileCheckNotFoundError>();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000598
599 // Successful regex match.
600 assert(!MatchInfo.empty() && "Didn't get any match");
601 StringRef FullMatch = MatchInfo[0];
602
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000603 // If this defines any string variables, remember their values.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000604 for (const auto &VariableDef : VariableDefs) {
605 assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000606 Context->GlobalVariableTable[VariableDef.first] =
607 MatchInfo[VariableDef.second];
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000608 }
609
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000610 // If this defines any numeric variables, remember their values.
611 for (const auto &NumericVariableDef : NumericVariableDefs) {
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000612 const FileCheckNumericVariableMatch &NumericVariableMatch =
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000613 NumericVariableDef.getValue();
614 unsigned CaptureParenGroup = NumericVariableMatch.CaptureParenGroup;
615 assert(CaptureParenGroup < MatchInfo.size() && "Internal paren error");
616 FileCheckNumericVariable *DefinedNumericVariable =
617 NumericVariableMatch.DefinedNumericVariable;
618
619 StringRef MatchedValue = MatchInfo[CaptureParenGroup];
620 uint64_t Val;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000621 if (MatchedValue.getAsInteger(10, Val))
622 return FileCheckErrorDiagnostic::get(SM, MatchedValue,
623 "Unable to represent numeric value");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000624 if (DefinedNumericVariable->setValue(Val))
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000625 llvm_unreachable("Numeric variable redefined");
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000626 }
627
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000628 // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
629 // the required preceding newline, which is consumed by the pattern in the
630 // case of CHECK-EMPTY but not CHECK-NEXT.
631 size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
632 MatchLen = FullMatch.size() - MatchStartSkip;
633 return FullMatch.data() - Buffer.data() + MatchStartSkip;
634}
635
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000636unsigned FileCheckPattern::computeMatchDistance(StringRef Buffer) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000637 // Just compute the number of matching characters. For regular expressions, we
638 // just compare against the regex itself and hope for the best.
639 //
640 // FIXME: One easy improvement here is have the regex lib generate a single
641 // example regular expression which matches, and use that as the example
642 // string.
643 StringRef ExampleString(FixedStr);
644 if (ExampleString.empty())
645 ExampleString = RegExStr;
646
647 // Only compare up to the first line in the buffer, or the string size.
648 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
649 BufferPrefix = BufferPrefix.split('\n').first;
650 return BufferPrefix.edit_distance(ExampleString);
651}
652
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000653void FileCheckPattern::printSubstitutions(const SourceMgr &SM, StringRef Buffer,
654 SMRange MatchRange) const {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +0000655 // Print what we know about substitutions.
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000656 if (!Substitutions.empty()) {
657 for (const auto &Substitution : Substitutions) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000658 SmallString<256> Msg;
659 raw_svector_ostream OS(Msg);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000660 Expected<std::string> MatchedValue = Substitution->getResult();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000661
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000662 // Substitution failed or is not known at match time, print the undefined
663 // variable it uses.
664 if (!MatchedValue) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000665 bool UndefSeen = false;
666 handleAllErrors(MatchedValue.takeError(),
667 [](const FileCheckNotFoundError &E) {},
Thomas Preud'hommea188ad22019-07-05 12:00:56 +0000668 // Handled in PrintNoMatch().
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000669 [](const FileCheckErrorDiagnostic &E) {},
670 [&](const FileCheckUndefVarError &E) {
671 if (!UndefSeen) {
672 OS << "uses undefined variable ";
673 UndefSeen = true;
674 }
675 E.log(OS);
676 },
677 [](const ErrorInfoBase &E) {
678 llvm_unreachable("Unexpected error");
679 });
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000680 } else {
681 // Substitution succeeded. Print substituted value.
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000682 OS << "with \"";
683 OS.write_escaped(Substitution->getFromString()) << "\" equal to \"";
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000684 OS.write_escaped(*MatchedValue) << "\"";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000685 }
686
687 if (MatchRange.isValid())
688 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
689 {MatchRange});
690 else
691 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
692 SourceMgr::DK_Note, OS.str());
693 }
694 }
695}
696
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000697static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
698 const SourceMgr &SM, SMLoc Loc,
699 Check::FileCheckType CheckTy,
700 StringRef Buffer, size_t Pos, size_t Len,
Joel E. Denny7df86962018-12-18 00:03:03 +0000701 std::vector<FileCheckDiag> *Diags,
702 bool AdjustPrevDiag = false) {
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000703 SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
704 SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
705 SMRange Range(Start, End);
Joel E. Denny96f0e842018-12-18 00:03:36 +0000706 if (Diags) {
Joel E. Denny7df86962018-12-18 00:03:03 +0000707 if (AdjustPrevDiag)
708 Diags->rbegin()->MatchTy = MatchTy;
709 else
710 Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
711 }
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000712 return Range;
713}
714
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000715void FileCheckPattern::printFuzzyMatch(
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000716 const SourceMgr &SM, StringRef Buffer,
Joel E. Denny2c007c82018-12-18 00:02:04 +0000717 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000718 // Attempt to find the closest/best fuzzy match. Usually an error happens
719 // because some string in the output didn't exactly match. In these cases, we
720 // would like to show the user a best guess at what "should have" matched, to
721 // save them having to actually check the input manually.
722 size_t NumLinesForward = 0;
723 size_t Best = StringRef::npos;
724 double BestQuality = 0;
725
726 // Use an arbitrary 4k limit on how far we will search.
727 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
728 if (Buffer[i] == '\n')
729 ++NumLinesForward;
730
731 // Patterns have leading whitespace stripped, so skip whitespace when
732 // looking for something which looks like a pattern.
733 if (Buffer[i] == ' ' || Buffer[i] == '\t')
734 continue;
735
736 // Compute the "quality" of this match as an arbitrary combination of the
737 // match distance and the number of lines skipped to get to this match.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000738 unsigned Distance = computeMatchDistance(Buffer.substr(i));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000739 double Quality = Distance + (NumLinesForward / 100.);
740
741 if (Quality < BestQuality || Best == StringRef::npos) {
742 Best = i;
743 BestQuality = Quality;
744 }
745 }
746
747 // Print the "possible intended match here" line if we found something
748 // reasonable and not equal to what we showed in the "scanning from here"
749 // line.
750 if (Best && Best != StringRef::npos && BestQuality < 50) {
Joel E. Denny2c007c82018-12-18 00:02:04 +0000751 SMRange MatchRange =
752 ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
753 getCheckTy(), Buffer, Best, 0, Diags);
754 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
755 "possible intended match here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000756
757 // FIXME: If we wanted to be really friendly we would show why the match
758 // failed, as it can be hard to spot simple one character differences.
759 }
760}
761
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000762Expected<StringRef>
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000763FileCheckPatternContext::getPatternVarValue(StringRef VarName) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000764 auto VarIter = GlobalVariableTable.find(VarName);
765 if (VarIter == GlobalVariableTable.end())
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +0000766 return make_error<FileCheckUndefVarError>(VarName);
Thomas Preud'hommee038fa72019-04-15 10:10:11 +0000767
768 return VarIter->second;
769}
770
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000771FileCheckExpression *
772FileCheckPatternContext::makeExpression(binop_eval_t EvalBinop,
773 FileCheckNumericVariable *OperandLeft,
774 uint64_t OperandRight) {
775 Expressions.push_back(llvm::make_unique<FileCheckExpression>(
776 EvalBinop, OperandLeft, OperandRight));
777 return Expressions.back().get();
Thomas Preud'homme288ed912019-05-02 00:04:38 +0000778}
779
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000780template <class... Types>
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000781FileCheckNumericVariable *
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000782FileCheckPatternContext::makeNumericVariable(Types... args) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000783 NumericVariables.push_back(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +0000784 llvm::make_unique<FileCheckNumericVariable>(args...));
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +0000785 return NumericVariables.back().get();
786}
787
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000788FileCheckSubstitution *
789FileCheckPatternContext::makeStringSubstitution(StringRef VarName,
790 size_t InsertIdx) {
791 Substitutions.push_back(
792 llvm::make_unique<FileCheckStringSubstitution>(this, VarName, InsertIdx));
793 return Substitutions.back().get();
794}
795
796FileCheckSubstitution *FileCheckPatternContext::makeNumericSubstitution(
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000797 StringRef ExpressionStr, FileCheckExpression *Expression,
798 size_t InsertIdx) {
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000799 Substitutions.push_back(llvm::make_unique<FileCheckNumericSubstitution>(
Thomas Preud'hommea2ef1ba2019-06-19 23:47:24 +0000800 this, ExpressionStr, Expression, InsertIdx));
Thomas Preud'hommef3b9bb32019-05-23 00:10:29 +0000801 return Substitutions.back().get();
802}
803
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000804size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
805 // Offset keeps track of the current offset within the input Str
806 size_t Offset = 0;
807 // [...] Nesting depth
808 size_t BracketDepth = 0;
809
810 while (!Str.empty()) {
811 if (Str.startswith("]]") && BracketDepth == 0)
812 return Offset;
813 if (Str[0] == '\\') {
814 // Backslash escapes the next char within regexes, so skip them both.
815 Str = Str.substr(2);
816 Offset += 2;
817 } else {
818 switch (Str[0]) {
819 default:
820 break;
821 case '[':
822 BracketDepth++;
823 break;
824 case ']':
825 if (BracketDepth == 0) {
826 SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
827 SourceMgr::DK_Error,
828 "missing closing \"]\" for regex variable");
829 exit(1);
830 }
831 BracketDepth--;
832 break;
833 }
834 Str = Str.substr(1);
835 Offset++;
836 }
837 }
838
839 return StringRef::npos;
840}
841
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +0000842StringRef FileCheck::CanonicalizeFile(MemoryBuffer &MB,
843 SmallVectorImpl<char> &OutputBuffer) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000844 OutputBuffer.reserve(MB.getBufferSize());
845
846 for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
847 Ptr != End; ++Ptr) {
848 // Eliminate trailing dosish \r.
849 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
850 continue;
851 }
852
853 // If current char is not a horizontal whitespace or if horizontal
854 // whitespace canonicalization is disabled, dump it to output as is.
855 if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
856 OutputBuffer.push_back(*Ptr);
857 continue;
858 }
859
860 // Otherwise, add one space and advance over neighboring space.
861 OutputBuffer.push_back(' ');
862 while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
863 ++Ptr;
864 }
865
866 // Add a null byte and then return all but that byte.
867 OutputBuffer.push_back('\0');
868 return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
869}
870
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000871FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
872 const Check::FileCheckType &CheckTy,
873 SMLoc CheckLoc, MatchType MatchTy,
874 SMRange InputRange)
875 : CheckTy(CheckTy), MatchTy(MatchTy) {
876 auto Start = SM.getLineAndColumn(InputRange.Start);
877 auto End = SM.getLineAndColumn(InputRange.End);
878 InputStartLine = Start.first;
879 InputStartCol = Start.second;
880 InputEndLine = End.first;
881 InputEndCol = End.second;
882 Start = SM.getLineAndColumn(CheckLoc);
883 CheckLine = Start.first;
884 CheckCol = Start.second;
885}
886
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000887static bool IsPartOfWord(char c) {
888 return (isalnum(c) || c == '-' || c == '_');
889}
890
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000891Check::FileCheckType &Check::FileCheckType::setCount(int C) {
Fedor Sergeev8477a3e2018-11-13 01:09:53 +0000892 assert(Count > 0 && "zero and negative counts are not supported");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000893 assert((C == 1 || Kind == CheckPlain) &&
894 "count supported only for plain CHECK directives");
895 Count = C;
896 return *this;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000897}
898
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000899std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
900 switch (Kind) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000901 case Check::CheckNone:
902 return "invalid";
903 case Check::CheckPlain:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000904 if (Count > 1)
905 return Prefix.str() + "-COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000906 return Prefix;
907 case Check::CheckNext:
908 return Prefix.str() + "-NEXT";
909 case Check::CheckSame:
910 return Prefix.str() + "-SAME";
911 case Check::CheckNot:
912 return Prefix.str() + "-NOT";
913 case Check::CheckDAG:
914 return Prefix.str() + "-DAG";
915 case Check::CheckLabel:
916 return Prefix.str() + "-LABEL";
917 case Check::CheckEmpty:
918 return Prefix.str() + "-EMPTY";
919 case Check::CheckEOF:
920 return "implicit EOF";
921 case Check::CheckBadNot:
922 return "bad NOT";
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000923 case Check::CheckBadCount:
924 return "bad COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000925 }
926 llvm_unreachable("unknown FileCheckType");
927}
928
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000929static std::pair<Check::FileCheckType, StringRef>
930FindCheckType(StringRef Buffer, StringRef Prefix) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000931 if (Buffer.size() <= Prefix.size())
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000932 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000933
934 char NextChar = Buffer[Prefix.size()];
935
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000936 StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000937 // Verify that the : is present after the prefix.
938 if (NextChar == ':')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000939 return {Check::CheckPlain, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000940
941 if (NextChar != '-')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000942 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000943
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000944 if (Rest.consume_front("COUNT-")) {
945 int64_t Count;
946 if (Rest.consumeInteger(10, Count))
947 // Error happened in parsing integer.
948 return {Check::CheckBadCount, Rest};
949 if (Count <= 0 || Count > INT32_MAX)
950 return {Check::CheckBadCount, Rest};
951 if (!Rest.consume_front(":"))
952 return {Check::CheckBadCount, Rest};
953 return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
954 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000955
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000956 if (Rest.consume_front("NEXT:"))
957 return {Check::CheckNext, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000958
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000959 if (Rest.consume_front("SAME:"))
960 return {Check::CheckSame, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000961
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000962 if (Rest.consume_front("NOT:"))
963 return {Check::CheckNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000964
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000965 if (Rest.consume_front("DAG:"))
966 return {Check::CheckDAG, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000967
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000968 if (Rest.consume_front("LABEL:"))
969 return {Check::CheckLabel, Rest};
970
971 if (Rest.consume_front("EMPTY:"))
972 return {Check::CheckEmpty, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000973
974 // You can't combine -NOT with another suffix.
975 if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
976 Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
977 Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
978 Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000979 return {Check::CheckBadNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000980
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000981 return {Check::CheckNone, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000982}
983
984// From the given position, find the next character after the word.
985static size_t SkipWord(StringRef Str, size_t Loc) {
986 while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
987 ++Loc;
988 return Loc;
989}
990
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +0000991/// Searches the buffer for the first prefix in the prefix regular expression.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000992///
993/// This searches the buffer using the provided regular expression, however it
994/// enforces constraints beyond that:
995/// 1) The found prefix must not be a suffix of something that looks like
996/// a valid prefix.
997/// 2) The found prefix must be followed by a valid check type suffix using \c
998/// FindCheckType above.
999///
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +00001000/// \returns a pair of StringRefs into the Buffer, which combines:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001001/// - the first match of the regular expression to satisfy these two is
1002/// returned,
1003/// otherwise an empty StringRef is returned to indicate failure.
1004/// - buffer rewound to the location right after parsed suffix, for parsing
1005/// to continue from
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001006///
1007/// If this routine returns a valid prefix, it will also shrink \p Buffer to
1008/// start at the beginning of the returned prefix, increment \p LineNumber for
1009/// each new line consumed from \p Buffer, and set \p CheckTy to the type of
1010/// check found by examining the suffix.
1011///
1012/// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
1013/// is unspecified.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001014static std::pair<StringRef, StringRef>
1015FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer,
1016 unsigned &LineNumber, Check::FileCheckType &CheckTy) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001017 SmallVector<StringRef, 2> Matches;
1018
1019 while (!Buffer.empty()) {
1020 // Find the first (longest) match using the RE.
1021 if (!PrefixRE.match(Buffer, &Matches))
1022 // No match at all, bail.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001023 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001024
1025 StringRef Prefix = Matches[0];
1026 Matches.clear();
1027
1028 assert(Prefix.data() >= Buffer.data() &&
1029 Prefix.data() < Buffer.data() + Buffer.size() &&
1030 "Prefix doesn't start inside of buffer!");
1031 size_t Loc = Prefix.data() - Buffer.data();
1032 StringRef Skipped = Buffer.substr(0, Loc);
1033 Buffer = Buffer.drop_front(Loc);
1034 LineNumber += Skipped.count('\n');
1035
1036 // Check that the matched prefix isn't a suffix of some other check-like
1037 // word.
1038 // FIXME: This is a very ad-hoc check. it would be better handled in some
1039 // other way. Among other things it seems hard to distinguish between
1040 // intentional and unintentional uses of this feature.
1041 if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
1042 // Now extract the type.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001043 StringRef AfterSuffix;
1044 std::tie(CheckTy, AfterSuffix) = FindCheckType(Buffer, Prefix);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001045
1046 // If we've found a valid check type for this prefix, we're done.
1047 if (CheckTy != Check::CheckNone)
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001048 return {Prefix, AfterSuffix};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001049 }
1050
1051 // If we didn't successfully find a prefix, we need to skip this invalid
1052 // prefix and continue scanning. We directly skip the prefix that was
1053 // matched and any additional parts of that check-like word.
1054 Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
1055 }
1056
1057 // We ran out of buffer while skipping partial matches so give up.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001058 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001059}
1060
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001061bool FileCheck::ReadCheckFile(SourceMgr &SM, StringRef Buffer, Regex &PrefixRE,
1062 std::vector<FileCheckString> &CheckStrings) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001063 Error DefineError =
1064 PatternContext.defineCmdlineVariables(Req.GlobalDefines, SM);
1065 if (DefineError) {
1066 logAllUnhandledErrors(std::move(DefineError), errs());
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001067 return true;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001068 }
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001069
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001070 std::vector<FileCheckPattern> ImplicitNegativeChecks;
1071 for (const auto &PatternString : Req.ImplicitCheckNot) {
1072 // Create a buffer with fake command line content in order to display the
1073 // command line option responsible for the specific implicit CHECK-NOT.
1074 std::string Prefix = "-implicit-check-not='";
1075 std::string Suffix = "'";
1076 std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
1077 Prefix + PatternString + Suffix, "command line");
1078
1079 StringRef PatternInBuffer =
1080 CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
1081 SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
1082
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001083 ImplicitNegativeChecks.push_back(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001084 FileCheckPattern(Check::CheckNot, &PatternContext, 0));
1085 ImplicitNegativeChecks.back().parsePattern(PatternInBuffer,
1086 "IMPLICIT-CHECK", SM, Req);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001087 }
1088
1089 std::vector<FileCheckPattern> DagNotMatches = ImplicitNegativeChecks;
1090
1091 // LineNumber keeps track of the line on which CheckPrefix instances are
1092 // found.
1093 unsigned LineNumber = 1;
1094
1095 while (1) {
1096 Check::FileCheckType CheckTy;
1097
1098 // See if a prefix occurs in the memory buffer.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001099 StringRef UsedPrefix;
1100 StringRef AfterSuffix;
1101 std::tie(UsedPrefix, AfterSuffix) =
1102 FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, CheckTy);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001103 if (UsedPrefix.empty())
1104 break;
1105 assert(UsedPrefix.data() == Buffer.data() &&
1106 "Failed to move Buffer's start forward, or pointed prefix outside "
1107 "of the buffer!");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001108 assert(AfterSuffix.data() >= Buffer.data() &&
1109 AfterSuffix.data() < Buffer.data() + Buffer.size() &&
1110 "Parsing after suffix doesn't start inside of buffer!");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001111
1112 // Location to use for error messages.
1113 const char *UsedPrefixStart = UsedPrefix.data();
1114
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001115 // Skip the buffer to the end of parsed suffix (or just prefix, if no good
1116 // suffix was processed).
1117 Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
1118 : AfterSuffix;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001119
1120 // Complain about useful-looking but unsupported suffixes.
1121 if (CheckTy == Check::CheckBadNot) {
1122 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
1123 "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
1124 return true;
1125 }
1126
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001127 // Complain about invalid count specification.
1128 if (CheckTy == Check::CheckBadCount) {
1129 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
1130 "invalid count in -COUNT specification on prefix '" +
1131 UsedPrefix + "'");
1132 return true;
1133 }
1134
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001135 // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
1136 // leading whitespace.
1137 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
1138 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
1139
1140 // Scan ahead to the end of line.
1141 size_t EOL = Buffer.find_first_of("\n\r");
1142
1143 // Remember the location of the start of the pattern, for diagnostics.
1144 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
1145
1146 // Parse the pattern.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001147 FileCheckPattern P(CheckTy, &PatternContext, LineNumber);
1148 if (P.parsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, Req))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001149 return true;
1150
1151 // Verify that CHECK-LABEL lines do not define or use variables
1152 if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
1153 SM.PrintMessage(
1154 SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
1155 "found '" + UsedPrefix + "-LABEL:'"
1156 " with variable definition or use");
1157 return true;
1158 }
1159
1160 Buffer = Buffer.substr(EOL);
1161
1162 // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
1163 if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
1164 CheckTy == Check::CheckEmpty) &&
1165 CheckStrings.empty()) {
1166 StringRef Type = CheckTy == Check::CheckNext
1167 ? "NEXT"
1168 : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
1169 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
1170 SourceMgr::DK_Error,
1171 "found '" + UsedPrefix + "-" + Type +
1172 "' without previous '" + UsedPrefix + ": line");
1173 return true;
1174 }
1175
1176 // Handle CHECK-DAG/-NOT.
1177 if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
1178 DagNotMatches.push_back(P);
1179 continue;
1180 }
1181
1182 // Okay, add the string we captured to the output vector and move on.
1183 CheckStrings.emplace_back(P, UsedPrefix, PatternLoc);
1184 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1185 DagNotMatches = ImplicitNegativeChecks;
1186 }
1187
1188 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
1189 // prefix as a filler for the error message.
1190 if (!DagNotMatches.empty()) {
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001191 CheckStrings.emplace_back(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001192 FileCheckPattern(Check::CheckEOF, &PatternContext, LineNumber + 1),
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001193 *Req.CheckPrefixes.begin(), SMLoc::getFromPointer(Buffer.data()));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001194 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1195 }
1196
1197 if (CheckStrings.empty()) {
1198 errs() << "error: no check strings found with prefix"
1199 << (Req.CheckPrefixes.size() > 1 ? "es " : " ");
1200 auto I = Req.CheckPrefixes.begin();
1201 auto E = Req.CheckPrefixes.end();
1202 if (I != E) {
1203 errs() << "\'" << *I << ":'";
1204 ++I;
1205 }
1206 for (; I != E; ++I)
1207 errs() << ", \'" << *I << ":'";
1208
1209 errs() << '\n';
1210 return true;
1211 }
1212
1213 return false;
1214}
1215
1216static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
1217 StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001218 int MatchedCount, StringRef Buffer, size_t MatchPos,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001219 size_t MatchLen, const FileCheckRequest &Req,
1220 std::vector<FileCheckDiag> *Diags) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001221 bool PrintDiag = true;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001222 if (ExpectedMatch) {
1223 if (!Req.Verbose)
1224 return;
1225 if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
1226 return;
Joel E. Denny352695c2019-01-22 21:41:42 +00001227 // Due to their verbosity, we don't print verbose diagnostics here if we're
1228 // gathering them for a different rendering, but we always print other
1229 // diagnostics.
1230 PrintDiag = !Diags;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001231 }
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001232 SMRange MatchRange = ProcessMatchResult(
Joel E. Dennye2afb612018-12-18 00:03:51 +00001233 ExpectedMatch ? FileCheckDiag::MatchFoundAndExpected
1234 : FileCheckDiag::MatchFoundButExcluded,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001235 SM, Loc, Pat.getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
Joel E. Denny352695c2019-01-22 21:41:42 +00001236 if (!PrintDiag)
1237 return;
1238
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001239 std::string Message = formatv("{0}: {1} string found in input",
1240 Pat.getCheckTy().getDescription(Prefix),
1241 (ExpectedMatch ? "expected" : "excluded"))
1242 .str();
1243 if (Pat.getCount() > 1)
1244 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
1245
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001246 SM.PrintMessage(
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001247 Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001248 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
1249 {MatchRange});
Thomas Preud'homme288ed912019-05-02 00:04:38 +00001250 Pat.printSubstitutions(SM, Buffer, MatchRange);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001251}
1252
1253static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001254 const FileCheckString &CheckStr, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001255 StringRef Buffer, size_t MatchPos, size_t MatchLen,
1256 FileCheckRequest &Req,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001257 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001258 PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001259 MatchedCount, Buffer, MatchPos, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001260}
1261
1262static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001263 StringRef Prefix, SMLoc Loc,
1264 const FileCheckPattern &Pat, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001265 StringRef Buffer, bool VerboseVerbose,
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001266 std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
1267 assert(MatchErrors && "Called on successful match");
Joel E. Denny352695c2019-01-22 21:41:42 +00001268 bool PrintDiag = true;
1269 if (!ExpectedMatch) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001270 if (!VerboseVerbose) {
1271 consumeError(std::move(MatchErrors));
Joel E. Denny352695c2019-01-22 21:41:42 +00001272 return;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001273 }
Joel E. Denny352695c2019-01-22 21:41:42 +00001274 // Due to their verbosity, we don't print verbose diagnostics here if we're
1275 // gathering them for a different rendering, but we always print other
1276 // diagnostics.
1277 PrintDiag = !Diags;
1278 }
1279
1280 // If the current position is at the end of a line, advance to the start of
1281 // the next line.
1282 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
1283 SMRange SearchRange = ProcessMatchResult(
1284 ExpectedMatch ? FileCheckDiag::MatchNoneButExpected
1285 : FileCheckDiag::MatchNoneAndExcluded,
1286 SM, Loc, Pat.getCheckTy(), Buffer, 0, Buffer.size(), Diags);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001287 if (!PrintDiag) {
1288 consumeError(std::move(MatchErrors));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001289 return;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001290 }
1291
1292 MatchErrors =
1293 handleErrors(std::move(MatchErrors),
1294 [](const FileCheckErrorDiagnostic &E) { E.log(errs()); });
1295
1296 // No problem matching the string per se.
1297 if (!MatchErrors)
1298 return;
1299 consumeError(std::move(MatchErrors));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001300
Joel E. Denny352695c2019-01-22 21:41:42 +00001301 // Print "not found" diagnostic.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001302 std::string Message = formatv("{0}: {1} string not found in input",
1303 Pat.getCheckTy().getDescription(Prefix),
1304 (ExpectedMatch ? "expected" : "excluded"))
1305 .str();
1306 if (Pat.getCount() > 1)
1307 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001308 SM.PrintMessage(
1309 Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001310
Joel E. Denny352695c2019-01-22 21:41:42 +00001311 // Print the "scanning from here" line.
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001312 SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001313
1314 // Allow the pattern to print additional information if desired.
Thomas Preud'homme288ed912019-05-02 00:04:38 +00001315 Pat.printSubstitutions(SM, Buffer);
Joel E. Denny96f0e842018-12-18 00:03:36 +00001316
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001317 if (ExpectedMatch)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001318 Pat.printFuzzyMatch(SM, Buffer, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001319}
1320
1321static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001322 const FileCheckString &CheckStr, int MatchedCount,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001323 StringRef Buffer, bool VerboseVerbose,
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001324 std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001325 PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001326 MatchedCount, Buffer, VerboseVerbose, Diags,
1327 std::move(MatchErrors));
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001328}
1329
Thomas Preud'homme4a8ef112019-05-08 21:47:31 +00001330/// Counts the number of newlines in the specified range.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001331static unsigned CountNumNewlinesBetween(StringRef Range,
1332 const char *&FirstNewLine) {
1333 unsigned NumNewLines = 0;
1334 while (1) {
1335 // Scan for newline.
1336 Range = Range.substr(Range.find_first_of("\n\r"));
1337 if (Range.empty())
1338 return NumNewLines;
1339
1340 ++NumNewLines;
1341
1342 // Handle \n\r and \r\n as a single newline.
1343 if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
1344 (Range[0] != Range[1]))
1345 Range = Range.substr(1);
1346 Range = Range.substr(1);
1347
1348 if (NumNewLines == 1)
1349 FirstNewLine = Range.begin();
1350 }
1351}
1352
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001353size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001354 bool IsLabelScanMode, size_t &MatchLen,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001355 FileCheckRequest &Req,
1356 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001357 size_t LastPos = 0;
1358 std::vector<const FileCheckPattern *> NotStrings;
1359
1360 // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
1361 // bounds; we have not processed variable definitions within the bounded block
1362 // yet so cannot handle any final CHECK-DAG yet; this is handled when going
1363 // over the block again (including the last CHECK-LABEL) in normal mode.
1364 if (!IsLabelScanMode) {
1365 // Match "dag strings" (with mixed "not strings" if any).
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001366 LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001367 if (LastPos == StringRef::npos)
1368 return StringRef::npos;
1369 }
1370
1371 // Match itself from the last position after matching CHECK-DAG.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001372 size_t LastMatchEnd = LastPos;
1373 size_t FirstMatchPos = 0;
1374 // Go match the pattern Count times. Majority of patterns only match with
1375 // count 1 though.
1376 assert(Pat.getCount() != 0 && "pattern count can not be zero");
1377 for (int i = 1; i <= Pat.getCount(); i++) {
1378 StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
1379 size_t CurrentMatchLen;
1380 // get a match at current start point
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001381 Expected<size_t> MatchResult = Pat.match(MatchBuffer, CurrentMatchLen, SM);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001382
1383 // report
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001384 if (!MatchResult) {
1385 PrintNoMatch(true, SM, *this, i, MatchBuffer, Req.VerboseVerbose, Diags,
1386 MatchResult.takeError());
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001387 return StringRef::npos;
1388 }
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001389 size_t MatchPos = *MatchResult;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001390 PrintMatch(true, SM, *this, i, MatchBuffer, MatchPos, CurrentMatchLen, Req,
1391 Diags);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001392 if (i == 1)
1393 FirstMatchPos = LastPos + MatchPos;
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001394
1395 // move start point after the match
1396 LastMatchEnd += MatchPos + CurrentMatchLen;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001397 }
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001398 // Full match len counts from first match pos.
1399 MatchLen = LastMatchEnd - FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001400
1401 // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1402 // or CHECK-NOT
1403 if (!IsLabelScanMode) {
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001404 size_t MatchPos = FirstMatchPos - LastPos;
1405 StringRef MatchBuffer = Buffer.substr(LastPos);
1406 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001407
1408 // If this check is a "CHECK-NEXT", verify that the previous match was on
1409 // the previous line (i.e. that there is one newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001410 if (CheckNext(SM, SkippedRegion)) {
Joel E. Dennye2afb612018-12-18 00:03:51 +00001411 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001412 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001413 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001414 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001415 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001416
1417 // If this check is a "CHECK-SAME", verify that the previous match was on
1418 // the same line (i.e. that there is no newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001419 if (CheckSame(SM, SkippedRegion)) {
Joel E. Dennye2afb612018-12-18 00:03:51 +00001420 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001421 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001422 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001423 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001424 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001425
1426 // If this match had "not strings", verify that they don't exist in the
1427 // skipped region.
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001428 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001429 return StringRef::npos;
1430 }
1431
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001432 return FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001433}
1434
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001435bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1436 if (Pat.getCheckTy() != Check::CheckNext &&
1437 Pat.getCheckTy() != Check::CheckEmpty)
1438 return false;
1439
1440 Twine CheckName =
1441 Prefix +
1442 Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
1443
1444 // Count the number of newlines between the previous match and this one.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001445 const char *FirstNewLine = nullptr;
1446 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1447
1448 if (NumNewLines == 0) {
1449 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1450 CheckName + ": is on the same line as previous match");
1451 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1452 "'next' match was here");
1453 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1454 "previous match ended here");
1455 return true;
1456 }
1457
1458 if (NumNewLines != 1) {
1459 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1460 CheckName +
1461 ": is not on the line after the previous match");
1462 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1463 "'next' match was here");
1464 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1465 "previous match ended here");
1466 SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
1467 "non-matching line after previous match is here");
1468 return true;
1469 }
1470
1471 return false;
1472}
1473
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001474bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
1475 if (Pat.getCheckTy() != Check::CheckSame)
1476 return false;
1477
1478 // Count the number of newlines between the previous match and this one.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001479 const char *FirstNewLine = nullptr;
1480 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1481
1482 if (NumNewLines != 0) {
1483 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1484 Prefix +
1485 "-SAME: is not on the same line as the previous match");
1486 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1487 "'next' match was here");
1488 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1489 "previous match ended here");
1490 return true;
1491 }
1492
1493 return false;
1494}
1495
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001496bool FileCheckString::CheckNot(
1497 const SourceMgr &SM, StringRef Buffer,
1498 const std::vector<const FileCheckPattern *> &NotStrings,
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001499 const FileCheckRequest &Req, std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001500 for (const FileCheckPattern *Pat : NotStrings) {
1501 assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1502
1503 size_t MatchLen = 0;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001504 Expected<size_t> MatchResult = Pat->match(Buffer, MatchLen, SM);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001505
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001506 if (!MatchResult) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001507 PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001508 Req.VerboseVerbose, Diags, MatchResult.takeError());
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001509 continue;
1510 }
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001511 size_t Pos = *MatchResult;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001512
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001513 PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, Pos, MatchLen,
1514 Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001515
1516 return true;
1517 }
1518
1519 return false;
1520}
1521
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001522size_t
1523FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1524 std::vector<const FileCheckPattern *> &NotStrings,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001525 const FileCheckRequest &Req,
1526 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001527 if (DagNotStrings.empty())
1528 return 0;
1529
1530 // The start of the search range.
1531 size_t StartPos = 0;
1532
1533 struct MatchRange {
1534 size_t Pos;
1535 size_t End;
1536 };
1537 // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
1538 // ranges are erased from this list once they are no longer in the search
1539 // range.
1540 std::list<MatchRange> MatchRanges;
1541
1542 // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
1543 // group, so we don't use a range-based for loop here.
1544 for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
1545 PatItr != PatEnd; ++PatItr) {
1546 const FileCheckPattern &Pat = *PatItr;
1547 assert((Pat.getCheckTy() == Check::CheckDAG ||
1548 Pat.getCheckTy() == Check::CheckNot) &&
1549 "Invalid CHECK-DAG or CHECK-NOT!");
1550
1551 if (Pat.getCheckTy() == Check::CheckNot) {
1552 NotStrings.push_back(&Pat);
1553 continue;
1554 }
1555
1556 assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1557
1558 // CHECK-DAG always matches from the start.
1559 size_t MatchLen = 0, MatchPos = StartPos;
1560
1561 // Search for a match that doesn't overlap a previous match in this
1562 // CHECK-DAG group.
1563 for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
1564 StringRef MatchBuffer = Buffer.substr(MatchPos);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001565 Expected<size_t> MatchResult = Pat.match(MatchBuffer, MatchLen, SM);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001566 // With a group of CHECK-DAGs, a single mismatching means the match on
1567 // that group of CHECK-DAGs fails immediately.
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001568 if (!MatchResult) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001569 PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001570 Req.VerboseVerbose, Diags, MatchResult.takeError());
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001571 return StringRef::npos;
1572 }
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001573 size_t MatchPosBuf = *MatchResult;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001574 // Re-calc it as the offset relative to the start of the original string.
1575 MatchPos += MatchPosBuf;
1576 if (Req.VerboseVerbose)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001577 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1578 MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001579 MatchRange M{MatchPos, MatchPos + MatchLen};
1580 if (Req.AllowDeprecatedDagOverlap) {
1581 // We don't need to track all matches in this mode, so we just maintain
1582 // one match range that encompasses the current CHECK-DAG group's
1583 // matches.
1584 if (MatchRanges.empty())
1585 MatchRanges.insert(MatchRanges.end(), M);
1586 else {
1587 auto Block = MatchRanges.begin();
1588 Block->Pos = std::min(Block->Pos, M.Pos);
1589 Block->End = std::max(Block->End, M.End);
1590 }
1591 break;
1592 }
1593 // Iterate previous matches until overlapping match or insertion point.
1594 bool Overlap = false;
1595 for (; MI != ME; ++MI) {
1596 if (M.Pos < MI->End) {
1597 // !Overlap => New match has no overlap and is before this old match.
1598 // Overlap => New match overlaps this old match.
1599 Overlap = MI->Pos < M.End;
1600 break;
1601 }
1602 }
1603 if (!Overlap) {
1604 // Insert non-overlapping match into list.
1605 MatchRanges.insert(MI, M);
1606 break;
1607 }
1608 if (Req.VerboseVerbose) {
Joel E. Denny352695c2019-01-22 21:41:42 +00001609 // Due to their verbosity, we don't print verbose diagnostics here if
1610 // we're gathering them for a different rendering, but we always print
1611 // other diagnostics.
1612 if (!Diags) {
1613 SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
1614 SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
1615 SMRange OldRange(OldStart, OldEnd);
1616 SM.PrintMessage(OldStart, SourceMgr::DK_Note,
1617 "match discarded, overlaps earlier DAG match here",
1618 {OldRange});
1619 } else
Joel E. Dennye2afb612018-12-18 00:03:51 +00001620 Diags->rbegin()->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001621 }
1622 MatchPos = MI->End;
1623 }
1624 if (!Req.VerboseVerbose)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001625 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1626 MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001627
1628 // Handle the end of a CHECK-DAG group.
1629 if (std::next(PatItr) == PatEnd ||
1630 std::next(PatItr)->getCheckTy() == Check::CheckNot) {
1631 if (!NotStrings.empty()) {
1632 // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
1633 // CHECK-DAG, verify that there are no 'not' strings occurred in that
1634 // region.
1635 StringRef SkippedRegion =
1636 Buffer.slice(StartPos, MatchRanges.begin()->Pos);
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001637 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001638 return StringRef::npos;
1639 // Clear "not strings".
1640 NotStrings.clear();
1641 }
1642 // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
1643 // end of this CHECK-DAG group's match range.
1644 StartPos = MatchRanges.rbegin()->End;
1645 // Don't waste time checking for (impossible) overlaps before that.
1646 MatchRanges.clear();
1647 }
1648 }
1649
1650 return StartPos;
1651}
1652
1653// A check prefix must contain only alphanumeric, hyphens and underscores.
1654static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1655 Regex Validator("^[a-zA-Z0-9_-]*$");
1656 return Validator.match(CheckPrefix);
1657}
1658
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001659bool FileCheck::ValidateCheckPrefixes() {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001660 StringSet<> PrefixSet;
1661
1662 for (StringRef Prefix : Req.CheckPrefixes) {
1663 // Reject empty prefixes.
1664 if (Prefix == "")
1665 return false;
1666
1667 if (!PrefixSet.insert(Prefix).second)
1668 return false;
1669
1670 if (!ValidateCheckPrefix(Prefix))
1671 return false;
1672 }
1673
1674 return true;
1675}
1676
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001677Regex FileCheck::buildCheckPrefixRegex() {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001678 // I don't think there's a way to specify an initial value for cl::list,
1679 // so if nothing was specified, add the default
1680 if (Req.CheckPrefixes.empty())
1681 Req.CheckPrefixes.push_back("CHECK");
1682
1683 // We already validated the contents of CheckPrefixes so just concatenate
1684 // them as alternatives.
1685 SmallString<32> PrefixRegexStr;
1686 for (StringRef Prefix : Req.CheckPrefixes) {
1687 if (Prefix != Req.CheckPrefixes.front())
1688 PrefixRegexStr.push_back('|');
1689
1690 PrefixRegexStr.append(Prefix);
1691 }
1692
1693 return Regex(PrefixRegexStr);
1694}
1695
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001696Error FileCheckPatternContext::defineCmdlineVariables(
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001697 std::vector<std::string> &CmdlineDefines, SourceMgr &SM) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001698 assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001699 "Overriding defined variable with command-line variable definitions");
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001700
1701 if (CmdlineDefines.empty())
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001702 return Error::success();
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001703
1704 // Create a string representing the vector of command-line definitions. Each
1705 // definition is on its own line and prefixed with a definition number to
1706 // clarify which definition a given diagnostic corresponds to.
1707 unsigned I = 0;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001708 Error Errs = Error::success();
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001709 std::string CmdlineDefsDiag;
1710 StringRef Prefix1 = "Global define #";
1711 StringRef Prefix2 = ": ";
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001712 for (StringRef CmdlineDef : CmdlineDefines)
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001713 CmdlineDefsDiag +=
1714 (Prefix1 + Twine(++I) + Prefix2 + CmdlineDef + "\n").str();
1715
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001716 // Create a buffer with fake command line content in order to display
1717 // parsing diagnostic with location information and point to the
1718 // global definition with invalid syntax.
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001719 std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
1720 MemoryBuffer::getMemBufferCopy(CmdlineDefsDiag, "Global defines");
1721 StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
1722 SM.AddNewSourceBuffer(std::move(CmdLineDefsDiagBuffer), SMLoc());
1723
1724 SmallVector<StringRef, 4> CmdlineDefsDiagVec;
1725 CmdlineDefsDiagRef.split(CmdlineDefsDiagVec, '\n', -1 /*MaxSplit*/,
1726 false /*KeepEmpty*/);
1727 for (StringRef CmdlineDefDiag : CmdlineDefsDiagVec) {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001728 unsigned DefStart = CmdlineDefDiag.find(Prefix2) + Prefix2.size();
1729 StringRef CmdlineDef = CmdlineDefDiag.substr(DefStart);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001730 size_t EqIdx = CmdlineDef.find('=');
1731 if (EqIdx == StringRef::npos) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001732 Errs = joinErrors(
1733 std::move(Errs),
1734 FileCheckErrorDiagnostic::get(
1735 SM, CmdlineDef, "missing equal sign in global definition"));
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001736 continue;
1737 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001738
1739 // Numeric variable definition.
1740 if (CmdlineDef[0] == '#') {
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001741 StringRef CmdlineName = CmdlineDef.substr(1, EqIdx - 1);
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001742 StringRef VarName;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001743 Error ErrorDiagnostic = FileCheckPattern::parseNumericVariableDefinition(
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001744 CmdlineName, VarName, this, SM);
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001745 if (ErrorDiagnostic) {
1746 Errs = joinErrors(std::move(Errs), std::move(ErrorDiagnostic));
1747 continue;
1748 }
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001749
1750 StringRef CmdlineVal = CmdlineDef.substr(EqIdx + 1);
1751 uint64_t Val;
1752 if (CmdlineVal.getAsInteger(10, Val)) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001753 Errs = joinErrors(std::move(Errs),
1754 FileCheckErrorDiagnostic::get(
1755 SM, CmdlineVal,
1756 "invalid value in numeric variable definition '" +
1757 CmdlineVal + "'"));
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001758 continue;
1759 }
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001760 auto DefinedNumericVariable = makeNumericVariable(0, VarName);
1761 DefinedNumericVariable->setValue(Val);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001762
1763 // Record this variable definition.
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001764 GlobalNumericVariableTable[DefinedNumericVariable->getName()] =
1765 DefinedNumericVariable;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001766 } else {
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001767 // String variable definition.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001768 std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.split('=');
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001769 StringRef CmdlineName = CmdlineNameVal.first;
1770 StringRef OrigCmdlineName = CmdlineName;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001771 bool IsPseudo;
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001772 Expected<StringRef> ParseVarResult =
1773 FileCheckPattern::parseVariable(CmdlineName, IsPseudo, SM);
1774 if (!ParseVarResult) {
1775 Errs = joinErrors(std::move(Errs), ParseVarResult.takeError());
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001776 continue;
1777 }
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001778 // Check that CmdlineName does not denote a pseudo variable is only
1779 // composed of the parsed numeric variable. This catches cases like
1780 // "FOO+2" in a "FOO+2=10" definition.
1781 if (IsPseudo || !CmdlineName.empty()) {
1782 Errs = joinErrors(std::move(Errs),
1783 FileCheckErrorDiagnostic::get(
1784 SM, OrigCmdlineName,
1785 "invalid name in string variable definition '" +
1786 OrigCmdlineName + "'"));
1787 continue;
1788 }
1789 StringRef Name = *ParseVarResult;
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001790
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001791 // Detect collisions between string and numeric variables when the former
1792 // is created later than the latter.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001793 if (GlobalNumericVariableTable.find(Name) !=
1794 GlobalNumericVariableTable.end()) {
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001795 Errs = joinErrors(std::move(Errs), FileCheckErrorDiagnostic::get(
1796 SM, Name,
1797 "numeric variable with name '" +
1798 Name + "' already exists"));
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001799 continue;
1800 }
1801 GlobalVariableTable.insert(CmdlineNameVal);
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001802 // Mark the string variable as defined to detect collisions between
1803 // string and numeric variables in DefineCmdlineVariables when the latter
1804 // is created later than the former. We cannot reuse GlobalVariableTable
Thomas Preud'homme71d3f222019-06-06 13:21:06 +00001805 // for this by populating it with an empty string since we would then
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001806 // lose the ability to detect the use of an undefined variable in
1807 // match().
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001808 DefinedVariableTable[Name] = true;
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001809 }
Thomas Preud'homme5a330472019-04-29 13:32:36 +00001810 }
1811
Thomas Preud'hommebaae41f2019-06-19 23:47:10 +00001812 return Errs;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001813}
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001814
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001815void FileCheckPatternContext::clearLocalVars() {
1816 SmallVector<StringRef, 16> LocalPatternVars, LocalNumericVars;
1817 for (const StringMapEntry<StringRef> &Var : GlobalVariableTable)
1818 if (Var.first()[0] != '$')
1819 LocalPatternVars.push_back(Var.first());
1820
Thomas Preud'homme1a944d22019-05-23 00:10:14 +00001821 // Numeric substitution reads the value of a variable directly, not via
1822 // GlobalNumericVariableTable. Therefore, we clear local variables by
1823 // clearing their value which will lead to a numeric substitution failure. We
1824 // also mark the variable for removal from GlobalNumericVariableTable since
1825 // this is what defineCmdlineVariables checks to decide that no global
1826 // variable has been defined.
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001827 for (const auto &Var : GlobalNumericVariableTable)
1828 if (Var.first()[0] != '$') {
1829 Var.getValue()->clearValue();
1830 LocalNumericVars.push_back(Var.first());
1831 }
1832
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001833 for (const auto &Var : LocalPatternVars)
1834 GlobalVariableTable.erase(Var);
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001835 for (const auto &Var : LocalNumericVars)
1836 GlobalNumericVariableTable.erase(Var);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001837}
1838
Thomas Preud'homme7b7683d2019-05-23 17:19:36 +00001839bool FileCheck::CheckInput(SourceMgr &SM, StringRef Buffer,
1840 ArrayRef<FileCheckString> CheckStrings,
1841 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001842 bool ChecksFailed = false;
1843
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001844 unsigned i = 0, j = 0, e = CheckStrings.size();
1845 while (true) {
1846 StringRef CheckRegion;
1847 if (j == e) {
1848 CheckRegion = Buffer;
1849 } else {
1850 const FileCheckString &CheckLabelStr = CheckStrings[j];
1851 if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
1852 ++j;
1853 continue;
1854 }
1855
1856 // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1857 size_t MatchLabelLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001858 size_t MatchLabelPos =
1859 CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001860 if (MatchLabelPos == StringRef::npos)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001861 // Immediately bail if CHECK-LABEL fails, nothing else we can do.
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001862 return false;
1863
1864 CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1865 Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1866 ++j;
1867 }
1868
Thomas Preud'homme7b4ecdd2019-05-14 11:58:30 +00001869 // Do not clear the first region as it's the one before the first
1870 // CHECK-LABEL and it would clear variables defined on the command-line
1871 // before they get used.
1872 if (i != 0 && Req.EnableVarScope)
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001873 PatternContext.clearLocalVars();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001874
1875 for (; i != j; ++i) {
1876 const FileCheckString &CheckStr = CheckStrings[i];
1877
1878 // Check each string within the scanned region, including a second check
1879 // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1880 size_t MatchLen = 0;
Thomas Preud'hommee038fa72019-04-15 10:10:11 +00001881 size_t MatchPos =
1882 CheckStr.Check(SM, CheckRegion, false, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001883
1884 if (MatchPos == StringRef::npos) {
1885 ChecksFailed = true;
1886 i = j;
1887 break;
1888 }
1889
1890 CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1891 }
1892
1893 if (j == e)
1894 break;
1895 }
1896
1897 // Success if no checks failed.
1898 return !ChecksFailed;
1899}