blob: 068fa96b9fae593dba4efbe14e332795a9262b0b [file] [log] [blame]
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// FileCheck does a line-by line check of a file that validates whether it
11// contains the expected content. This is useful for regression tests etc.
12//
13// This file implements most of the API that will be used by the FileCheck utility
14// as well as various unittests.
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Support/FileCheck.h"
18#include "llvm/ADT/StringSet.h"
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +000019#include "llvm/Support/FormatVariadic.h"
20#include <cstdint>
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +000021#include <list>
22#include <map>
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +000023#include <tuple>
24#include <utility>
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +000025
26using namespace llvm;
27
28/// Parses the given string into the Pattern.
29///
30/// \p Prefix provides which prefix is being matched, \p SM provides the
31/// SourceMgr used for error reports, and \p LineNumber is the line number in
32/// the input file from which the pattern string was read. Returns true in
33/// case of an error, false otherwise.
34bool FileCheckPattern::ParsePattern(StringRef PatternStr, StringRef Prefix,
35 SourceMgr &SM, unsigned LineNumber,
36 const FileCheckRequest &Req) {
37 bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
38
39 this->LineNumber = LineNumber;
40 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
41
42 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
43 // Ignore trailing whitespace.
44 while (!PatternStr.empty() &&
45 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
46 PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
47
48 // Check that there is something on the line.
49 if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
50 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
51 "found empty check string with prefix '" + Prefix + ":'");
52 return true;
53 }
54
55 if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
56 SM.PrintMessage(
57 PatternLoc, SourceMgr::DK_Error,
58 "found non-empty check string for empty check with prefix '" + Prefix +
59 ":'");
60 return true;
61 }
62
63 if (CheckTy == Check::CheckEmpty) {
64 RegExStr = "(\n$)";
65 return false;
66 }
67
68 // Check to see if this is a fixed string, or if it has regex pieces.
69 if (!MatchFullLinesHere &&
70 (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
71 PatternStr.find("[[") == StringRef::npos))) {
72 FixedStr = PatternStr;
73 return false;
74 }
75
76 if (MatchFullLinesHere) {
77 RegExStr += '^';
78 if (!Req.NoCanonicalizeWhiteSpace)
79 RegExStr += " *";
80 }
81
82 // Paren value #0 is for the fully matched string. Any new parenthesized
83 // values add from there.
84 unsigned CurParen = 1;
85
86 // Otherwise, there is at least one regex piece. Build up the regex pattern
87 // by escaping scary characters in fixed strings, building up one big regex.
88 while (!PatternStr.empty()) {
89 // RegEx matches.
90 if (PatternStr.startswith("{{")) {
91 // This is the start of a regex match. Scan for the }}.
92 size_t End = PatternStr.find("}}");
93 if (End == StringRef::npos) {
94 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
95 SourceMgr::DK_Error,
96 "found start of regex string with no end '}}'");
97 return true;
98 }
99
100 // Enclose {{}} patterns in parens just like [[]] even though we're not
101 // capturing the result for any purpose. This is required in case the
102 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
103 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
104 RegExStr += '(';
105 ++CurParen;
106
107 if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
108 return true;
109 RegExStr += ')';
110
111 PatternStr = PatternStr.substr(End + 2);
112 continue;
113 }
114
115 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
116 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
117 // second form is [[foo]] which is a reference to foo. The variable name
118 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
119 // it. This is to catch some common errors.
120 if (PatternStr.startswith("[[")) {
121 // Find the closing bracket pair ending the match. End is going to be an
122 // offset relative to the beginning of the match string.
123 size_t End = FindRegexVarEnd(PatternStr.substr(2), SM);
124
125 if (End == StringRef::npos) {
126 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
127 SourceMgr::DK_Error,
128 "invalid named regex reference, no ]] found");
129 return true;
130 }
131
132 StringRef MatchStr = PatternStr.substr(2, End);
133 PatternStr = PatternStr.substr(End + 4);
134
135 // Get the regex name (e.g. "foo").
136 size_t NameEnd = MatchStr.find(':');
137 StringRef Name = MatchStr.substr(0, NameEnd);
138
139 if (Name.empty()) {
140 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
141 "invalid name in named regex: empty name");
142 return true;
143 }
144
145 // Verify that the name/expression is well formed. FileCheck currently
146 // supports @LINE, @LINE+number, @LINE-number expressions. The check here
147 // is relaxed, more strict check is performed in \c EvaluateExpression.
148 bool IsExpression = false;
149 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
150 if (i == 0) {
151 if (Name[i] == '$') // Global vars start with '$'
152 continue;
153 if (Name[i] == '@') {
154 if (NameEnd != StringRef::npos) {
155 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
156 SourceMgr::DK_Error,
157 "invalid name in named regex definition");
158 return true;
159 }
160 IsExpression = true;
161 continue;
162 }
163 }
164 if (Name[i] != '_' && !isalnum(Name[i]) &&
165 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
166 SM.PrintMessage(SMLoc::getFromPointer(Name.data() + i),
167 SourceMgr::DK_Error, "invalid name in named regex");
168 return true;
169 }
170 }
171
172 // Name can't start with a digit.
173 if (isdigit(static_cast<unsigned char>(Name[0]))) {
174 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
175 "invalid name in named regex");
176 return true;
177 }
178
179 // Handle [[foo]].
180 if (NameEnd == StringRef::npos) {
181 // Handle variables that were defined earlier on the same line by
182 // emitting a backreference.
183 if (VariableDefs.find(Name) != VariableDefs.end()) {
184 unsigned VarParenNum = VariableDefs[Name];
185 if (VarParenNum < 1 || VarParenNum > 9) {
186 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
187 SourceMgr::DK_Error,
188 "Can't back-reference more than 9 variables");
189 return true;
190 }
191 AddBackrefToRegEx(VarParenNum);
192 } else {
193 VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
194 }
195 continue;
196 }
197
198 // Handle [[foo:.*]].
199 VariableDefs[Name] = CurParen;
200 RegExStr += '(';
201 ++CurParen;
202
203 if (AddRegExToRegEx(MatchStr.substr(NameEnd + 1), CurParen, SM))
204 return true;
205
206 RegExStr += ')';
207 }
208
209 // Handle fixed string matches.
210 // Find the end, which is the start of the next regex.
211 size_t FixedMatchEnd = PatternStr.find("{{");
212 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
213 RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
214 PatternStr = PatternStr.substr(FixedMatchEnd);
215 }
216
217 if (MatchFullLinesHere) {
218 if (!Req.NoCanonicalizeWhiteSpace)
219 RegExStr += " *";
220 RegExStr += '$';
221 }
222
223 return false;
224}
225
226bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
227 Regex R(RS);
228 std::string Error;
229 if (!R.isValid(Error)) {
230 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
231 "invalid regex: " + Error);
232 return true;
233 }
234
235 RegExStr += RS.str();
236 CurParen += R.getNumMatches();
237 return false;
238}
239
240void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
241 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
242 std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
243 RegExStr += Backref;
244}
245
246/// Evaluates expression and stores the result to \p Value.
247///
248/// Returns true on success and false when the expression has invalid syntax.
249bool FileCheckPattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
250 // The only supported expression is @LINE([\+-]\d+)?
251 if (!Expr.startswith("@LINE"))
252 return false;
253 Expr = Expr.substr(StringRef("@LINE").size());
254 int Offset = 0;
255 if (!Expr.empty()) {
256 if (Expr[0] == '+')
257 Expr = Expr.substr(1);
258 else if (Expr[0] != '-')
259 return false;
260 if (Expr.getAsInteger(10, Offset))
261 return false;
262 }
263 Value = llvm::itostr(LineNumber + Offset);
264 return true;
265}
266
267/// Matches the pattern string against the input buffer \p Buffer
268///
269/// This returns the position that is matched or npos if there is no match. If
270/// there is a match, the size of the matched string is returned in \p
271/// MatchLen.
272///
273/// The \p VariableTable StringMap provides the current values of filecheck
274/// variables and is updated if this match defines new values.
275size_t FileCheckPattern::Match(StringRef Buffer, size_t &MatchLen,
276 StringMap<StringRef> &VariableTable) const {
277 // If this is the EOF pattern, match it immediately.
278 if (CheckTy == Check::CheckEOF) {
279 MatchLen = 0;
280 return Buffer.size();
281 }
282
283 // If this is a fixed string pattern, just match it now.
284 if (!FixedStr.empty()) {
285 MatchLen = FixedStr.size();
286 return Buffer.find(FixedStr);
287 }
288
289 // Regex match.
290
291 // If there are variable uses, we need to create a temporary string with the
292 // actual value.
293 StringRef RegExToMatch = RegExStr;
294 std::string TmpStr;
295 if (!VariableUses.empty()) {
296 TmpStr = RegExStr;
297
298 unsigned InsertOffset = 0;
299 for (const auto &VariableUse : VariableUses) {
300 std::string Value;
301
302 if (VariableUse.first[0] == '@') {
303 if (!EvaluateExpression(VariableUse.first, Value))
304 return StringRef::npos;
305 } else {
306 StringMap<StringRef>::iterator it =
307 VariableTable.find(VariableUse.first);
308 // If the variable is undefined, return an error.
309 if (it == VariableTable.end())
310 return StringRef::npos;
311
312 // Look up the value and escape it so that we can put it into the regex.
313 Value += Regex::escape(it->second);
314 }
315
316 // Plop it into the regex at the adjusted offset.
317 TmpStr.insert(TmpStr.begin() + VariableUse.second + InsertOffset,
318 Value.begin(), Value.end());
319 InsertOffset += Value.size();
320 }
321
322 // Match the newly constructed regex.
323 RegExToMatch = TmpStr;
324 }
325
326 SmallVector<StringRef, 4> MatchInfo;
327 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
328 return StringRef::npos;
329
330 // Successful regex match.
331 assert(!MatchInfo.empty() && "Didn't get any match");
332 StringRef FullMatch = MatchInfo[0];
333
334 // If this defines any variables, remember their values.
335 for (const auto &VariableDef : VariableDefs) {
336 assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
337 VariableTable[VariableDef.first] = MatchInfo[VariableDef.second];
338 }
339
340 // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
341 // the required preceding newline, which is consumed by the pattern in the
342 // case of CHECK-EMPTY but not CHECK-NEXT.
343 size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
344 MatchLen = FullMatch.size() - MatchStartSkip;
345 return FullMatch.data() - Buffer.data() + MatchStartSkip;
346}
347
348
349/// Computes an arbitrary estimate for the quality of matching this pattern at
350/// the start of \p Buffer; a distance of zero should correspond to a perfect
351/// match.
352unsigned
353FileCheckPattern::ComputeMatchDistance(StringRef Buffer,
354 const StringMap<StringRef> &VariableTable) const {
355 // Just compute the number of matching characters. For regular expressions, we
356 // just compare against the regex itself and hope for the best.
357 //
358 // FIXME: One easy improvement here is have the regex lib generate a single
359 // example regular expression which matches, and use that as the example
360 // string.
361 StringRef ExampleString(FixedStr);
362 if (ExampleString.empty())
363 ExampleString = RegExStr;
364
365 // Only compare up to the first line in the buffer, or the string size.
366 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
367 BufferPrefix = BufferPrefix.split('\n').first;
368 return BufferPrefix.edit_distance(ExampleString);
369}
370
371void FileCheckPattern::PrintVariableUses(const SourceMgr &SM, StringRef Buffer,
372 const StringMap<StringRef> &VariableTable,
373 SMRange MatchRange) const {
374 // If this was a regular expression using variables, print the current
375 // variable values.
376 if (!VariableUses.empty()) {
377 for (const auto &VariableUse : VariableUses) {
378 SmallString<256> Msg;
379 raw_svector_ostream OS(Msg);
380 StringRef Var = VariableUse.first;
381 if (Var[0] == '@') {
382 std::string Value;
383 if (EvaluateExpression(Var, Value)) {
384 OS << "with expression \"";
385 OS.write_escaped(Var) << "\" equal to \"";
386 OS.write_escaped(Value) << "\"";
387 } else {
388 OS << "uses incorrect expression \"";
389 OS.write_escaped(Var) << "\"";
390 }
391 } else {
392 StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
393
394 // Check for undefined variable references.
395 if (it == VariableTable.end()) {
396 OS << "uses undefined variable \"";
397 OS.write_escaped(Var) << "\"";
398 } else {
399 OS << "with variable \"";
400 OS.write_escaped(Var) << "\" equal to \"";
401 OS.write_escaped(it->second) << "\"";
402 }
403 }
404
405 if (MatchRange.isValid())
406 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
407 {MatchRange});
408 else
409 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
410 SourceMgr::DK_Note, OS.str());
411 }
412 }
413}
414
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000415static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
416 const SourceMgr &SM, SMLoc Loc,
417 Check::FileCheckType CheckTy,
418 StringRef Buffer, size_t Pos, size_t Len,
Joel E. Denny7df86962018-12-18 00:03:03 +0000419 std::vector<FileCheckDiag> *Diags,
420 bool AdjustPrevDiag = false) {
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000421 SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
422 SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
423 SMRange Range(Start, End);
424 // TODO: The second condition will disappear when we extend this to handle
425 // more match types.
Joel E. Denny7df86962018-12-18 00:03:03 +0000426 if (Diags && MatchTy != FileCheckDiag::MatchTypeCount) {
427 if (AdjustPrevDiag)
428 Diags->rbegin()->MatchTy = MatchTy;
429 else
430 Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
431 }
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000432 return Range;
433}
434
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000435void FileCheckPattern::PrintFuzzyMatch(
436 const SourceMgr &SM, StringRef Buffer,
Joel E. Denny2c007c82018-12-18 00:02:04 +0000437 const StringMap<StringRef> &VariableTable,
438 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000439 // Attempt to find the closest/best fuzzy match. Usually an error happens
440 // because some string in the output didn't exactly match. In these cases, we
441 // would like to show the user a best guess at what "should have" matched, to
442 // save them having to actually check the input manually.
443 size_t NumLinesForward = 0;
444 size_t Best = StringRef::npos;
445 double BestQuality = 0;
446
447 // Use an arbitrary 4k limit on how far we will search.
448 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
449 if (Buffer[i] == '\n')
450 ++NumLinesForward;
451
452 // Patterns have leading whitespace stripped, so skip whitespace when
453 // looking for something which looks like a pattern.
454 if (Buffer[i] == ' ' || Buffer[i] == '\t')
455 continue;
456
457 // Compute the "quality" of this match as an arbitrary combination of the
458 // match distance and the number of lines skipped to get to this match.
459 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
460 double Quality = Distance + (NumLinesForward / 100.);
461
462 if (Quality < BestQuality || Best == StringRef::npos) {
463 Best = i;
464 BestQuality = Quality;
465 }
466 }
467
468 // Print the "possible intended match here" line if we found something
469 // reasonable and not equal to what we showed in the "scanning from here"
470 // line.
471 if (Best && Best != StringRef::npos && BestQuality < 50) {
Joel E. Denny2c007c82018-12-18 00:02:04 +0000472 SMRange MatchRange =
473 ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
474 getCheckTy(), Buffer, Best, 0, Diags);
475 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
476 "possible intended match here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000477
478 // FIXME: If we wanted to be really friendly we would show why the match
479 // failed, as it can be hard to spot simple one character differences.
480 }
481}
482
483/// Finds the closing sequence of a regex variable usage or definition.
484///
485/// \p Str has to point in the beginning of the definition (right after the
486/// opening sequence). Returns the offset of the closing sequence within Str,
487/// or npos if it was not found.
488size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
489 // Offset keeps track of the current offset within the input Str
490 size_t Offset = 0;
491 // [...] Nesting depth
492 size_t BracketDepth = 0;
493
494 while (!Str.empty()) {
495 if (Str.startswith("]]") && BracketDepth == 0)
496 return Offset;
497 if (Str[0] == '\\') {
498 // Backslash escapes the next char within regexes, so skip them both.
499 Str = Str.substr(2);
500 Offset += 2;
501 } else {
502 switch (Str[0]) {
503 default:
504 break;
505 case '[':
506 BracketDepth++;
507 break;
508 case ']':
509 if (BracketDepth == 0) {
510 SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
511 SourceMgr::DK_Error,
512 "missing closing \"]\" for regex variable");
513 exit(1);
514 }
515 BracketDepth--;
516 break;
517 }
518 Str = Str.substr(1);
519 Offset++;
520 }
521 }
522
523 return StringRef::npos;
524}
525
526/// Canonicalize whitespaces in the file. Line endings are replaced with
527/// UNIX-style '\n'.
528StringRef
529llvm::FileCheck::CanonicalizeFile(MemoryBuffer &MB,
530 SmallVectorImpl<char> &OutputBuffer) {
531 OutputBuffer.reserve(MB.getBufferSize());
532
533 for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
534 Ptr != End; ++Ptr) {
535 // Eliminate trailing dosish \r.
536 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
537 continue;
538 }
539
540 // If current char is not a horizontal whitespace or if horizontal
541 // whitespace canonicalization is disabled, dump it to output as is.
542 if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
543 OutputBuffer.push_back(*Ptr);
544 continue;
545 }
546
547 // Otherwise, add one space and advance over neighboring space.
548 OutputBuffer.push_back(' ');
549 while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
550 ++Ptr;
551 }
552
553 // Add a null byte and then return all but that byte.
554 OutputBuffer.push_back('\0');
555 return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
556}
557
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000558FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
559 const Check::FileCheckType &CheckTy,
560 SMLoc CheckLoc, MatchType MatchTy,
561 SMRange InputRange)
562 : CheckTy(CheckTy), MatchTy(MatchTy) {
563 auto Start = SM.getLineAndColumn(InputRange.Start);
564 auto End = SM.getLineAndColumn(InputRange.End);
565 InputStartLine = Start.first;
566 InputStartCol = Start.second;
567 InputEndLine = End.first;
568 InputEndCol = End.second;
569 Start = SM.getLineAndColumn(CheckLoc);
570 CheckLine = Start.first;
571 CheckCol = Start.second;
572}
573
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000574static bool IsPartOfWord(char c) {
575 return (isalnum(c) || c == '-' || c == '_');
576}
577
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000578Check::FileCheckType &Check::FileCheckType::setCount(int C) {
Fedor Sergeev8477a3e2018-11-13 01:09:53 +0000579 assert(Count > 0 && "zero and negative counts are not supported");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000580 assert((C == 1 || Kind == CheckPlain) &&
581 "count supported only for plain CHECK directives");
582 Count = C;
583 return *this;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000584}
585
586// Get a description of the type.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000587std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
588 switch (Kind) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000589 case Check::CheckNone:
590 return "invalid";
591 case Check::CheckPlain:
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000592 if (Count > 1)
593 return Prefix.str() + "-COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000594 return Prefix;
595 case Check::CheckNext:
596 return Prefix.str() + "-NEXT";
597 case Check::CheckSame:
598 return Prefix.str() + "-SAME";
599 case Check::CheckNot:
600 return Prefix.str() + "-NOT";
601 case Check::CheckDAG:
602 return Prefix.str() + "-DAG";
603 case Check::CheckLabel:
604 return Prefix.str() + "-LABEL";
605 case Check::CheckEmpty:
606 return Prefix.str() + "-EMPTY";
607 case Check::CheckEOF:
608 return "implicit EOF";
609 case Check::CheckBadNot:
610 return "bad NOT";
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000611 case Check::CheckBadCount:
612 return "bad COUNT";
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000613 }
614 llvm_unreachable("unknown FileCheckType");
615}
616
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000617static std::pair<Check::FileCheckType, StringRef>
618FindCheckType(StringRef Buffer, StringRef Prefix) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000619 if (Buffer.size() <= Prefix.size())
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000620 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000621
622 char NextChar = Buffer[Prefix.size()];
623
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000624 StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000625 // Verify that the : is present after the prefix.
626 if (NextChar == ':')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000627 return {Check::CheckPlain, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000628
629 if (NextChar != '-')
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000630 return {Check::CheckNone, StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000631
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000632 if (Rest.consume_front("COUNT-")) {
633 int64_t Count;
634 if (Rest.consumeInteger(10, Count))
635 // Error happened in parsing integer.
636 return {Check::CheckBadCount, Rest};
637 if (Count <= 0 || Count > INT32_MAX)
638 return {Check::CheckBadCount, Rest};
639 if (!Rest.consume_front(":"))
640 return {Check::CheckBadCount, Rest};
641 return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
642 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000643
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000644 if (Rest.consume_front("NEXT:"))
645 return {Check::CheckNext, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000646
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000647 if (Rest.consume_front("SAME:"))
648 return {Check::CheckSame, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000649
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000650 if (Rest.consume_front("NOT:"))
651 return {Check::CheckNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000652
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000653 if (Rest.consume_front("DAG:"))
654 return {Check::CheckDAG, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000655
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000656 if (Rest.consume_front("LABEL:"))
657 return {Check::CheckLabel, Rest};
658
659 if (Rest.consume_front("EMPTY:"))
660 return {Check::CheckEmpty, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000661
662 // You can't combine -NOT with another suffix.
663 if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
664 Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
665 Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
666 Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000667 return {Check::CheckBadNot, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000668
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000669 return {Check::CheckNone, Rest};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000670}
671
672// From the given position, find the next character after the word.
673static size_t SkipWord(StringRef Str, size_t Loc) {
674 while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
675 ++Loc;
676 return Loc;
677}
678
679/// Search the buffer for the first prefix in the prefix regular expression.
680///
681/// This searches the buffer using the provided regular expression, however it
682/// enforces constraints beyond that:
683/// 1) The found prefix must not be a suffix of something that looks like
684/// a valid prefix.
685/// 2) The found prefix must be followed by a valid check type suffix using \c
686/// FindCheckType above.
687///
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000688/// Returns a pair of StringRefs into the Buffer, which combines:
689/// - the first match of the regular expression to satisfy these two is
690/// returned,
691/// otherwise an empty StringRef is returned to indicate failure.
692/// - buffer rewound to the location right after parsed suffix, for parsing
693/// to continue from
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000694///
695/// If this routine returns a valid prefix, it will also shrink \p Buffer to
696/// start at the beginning of the returned prefix, increment \p LineNumber for
697/// each new line consumed from \p Buffer, and set \p CheckTy to the type of
698/// check found by examining the suffix.
699///
700/// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
701/// is unspecified.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000702static std::pair<StringRef, StringRef>
703FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer,
704 unsigned &LineNumber, Check::FileCheckType &CheckTy) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000705 SmallVector<StringRef, 2> Matches;
706
707 while (!Buffer.empty()) {
708 // Find the first (longest) match using the RE.
709 if (!PrefixRE.match(Buffer, &Matches))
710 // No match at all, bail.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000711 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000712
713 StringRef Prefix = Matches[0];
714 Matches.clear();
715
716 assert(Prefix.data() >= Buffer.data() &&
717 Prefix.data() < Buffer.data() + Buffer.size() &&
718 "Prefix doesn't start inside of buffer!");
719 size_t Loc = Prefix.data() - Buffer.data();
720 StringRef Skipped = Buffer.substr(0, Loc);
721 Buffer = Buffer.drop_front(Loc);
722 LineNumber += Skipped.count('\n');
723
724 // Check that the matched prefix isn't a suffix of some other check-like
725 // word.
726 // FIXME: This is a very ad-hoc check. it would be better handled in some
727 // other way. Among other things it seems hard to distinguish between
728 // intentional and unintentional uses of this feature.
729 if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
730 // Now extract the type.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000731 StringRef AfterSuffix;
732 std::tie(CheckTy, AfterSuffix) = FindCheckType(Buffer, Prefix);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000733
734 // If we've found a valid check type for this prefix, we're done.
735 if (CheckTy != Check::CheckNone)
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000736 return {Prefix, AfterSuffix};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000737 }
738
739 // If we didn't successfully find a prefix, we need to skip this invalid
740 // prefix and continue scanning. We directly skip the prefix that was
741 // matched and any additional parts of that check-like word.
742 Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
743 }
744
745 // We ran out of buffer while skipping partial matches so give up.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000746 return {StringRef(), StringRef()};
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000747}
748
749/// Read the check file, which specifies the sequence of expected strings.
750///
751/// The strings are added to the CheckStrings vector. Returns true in case of
752/// an error, false otherwise.
753bool llvm::FileCheck::ReadCheckFile(SourceMgr &SM, StringRef Buffer,
754 Regex &PrefixRE,
755 std::vector<FileCheckString> &CheckStrings) {
756 std::vector<FileCheckPattern> ImplicitNegativeChecks;
757 for (const auto &PatternString : Req.ImplicitCheckNot) {
758 // Create a buffer with fake command line content in order to display the
759 // command line option responsible for the specific implicit CHECK-NOT.
760 std::string Prefix = "-implicit-check-not='";
761 std::string Suffix = "'";
762 std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
763 Prefix + PatternString + Suffix, "command line");
764
765 StringRef PatternInBuffer =
766 CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
767 SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
768
769 ImplicitNegativeChecks.push_back(FileCheckPattern(Check::CheckNot));
770 ImplicitNegativeChecks.back().ParsePattern(PatternInBuffer,
771 "IMPLICIT-CHECK", SM, 0, Req);
772 }
773
774 std::vector<FileCheckPattern> DagNotMatches = ImplicitNegativeChecks;
775
776 // LineNumber keeps track of the line on which CheckPrefix instances are
777 // found.
778 unsigned LineNumber = 1;
779
780 while (1) {
781 Check::FileCheckType CheckTy;
782
783 // See if a prefix occurs in the memory buffer.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000784 StringRef UsedPrefix;
785 StringRef AfterSuffix;
786 std::tie(UsedPrefix, AfterSuffix) =
787 FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, CheckTy);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000788 if (UsedPrefix.empty())
789 break;
790 assert(UsedPrefix.data() == Buffer.data() &&
791 "Failed to move Buffer's start forward, or pointed prefix outside "
792 "of the buffer!");
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000793 assert(AfterSuffix.data() >= Buffer.data() &&
794 AfterSuffix.data() < Buffer.data() + Buffer.size() &&
795 "Parsing after suffix doesn't start inside of buffer!");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000796
797 // Location to use for error messages.
798 const char *UsedPrefixStart = UsedPrefix.data();
799
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000800 // Skip the buffer to the end of parsed suffix (or just prefix, if no good
801 // suffix was processed).
802 Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
803 : AfterSuffix;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000804
805 // Complain about useful-looking but unsupported suffixes.
806 if (CheckTy == Check::CheckBadNot) {
807 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
808 "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
809 return true;
810 }
811
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000812 // Complain about invalid count specification.
813 if (CheckTy == Check::CheckBadCount) {
814 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
815 "invalid count in -COUNT specification on prefix '" +
816 UsedPrefix + "'");
817 return true;
818 }
819
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000820 // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
821 // leading whitespace.
822 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
823 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
824
825 // Scan ahead to the end of line.
826 size_t EOL = Buffer.find_first_of("\n\r");
827
828 // Remember the location of the start of the pattern, for diagnostics.
829 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
830
831 // Parse the pattern.
832 FileCheckPattern P(CheckTy);
833 if (P.ParsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, LineNumber, Req))
834 return true;
835
836 // Verify that CHECK-LABEL lines do not define or use variables
837 if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
838 SM.PrintMessage(
839 SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
840 "found '" + UsedPrefix + "-LABEL:'"
841 " with variable definition or use");
842 return true;
843 }
844
845 Buffer = Buffer.substr(EOL);
846
847 // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
848 if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
849 CheckTy == Check::CheckEmpty) &&
850 CheckStrings.empty()) {
851 StringRef Type = CheckTy == Check::CheckNext
852 ? "NEXT"
853 : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
854 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
855 SourceMgr::DK_Error,
856 "found '" + UsedPrefix + "-" + Type +
857 "' without previous '" + UsedPrefix + ": line");
858 return true;
859 }
860
861 // Handle CHECK-DAG/-NOT.
862 if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
863 DagNotMatches.push_back(P);
864 continue;
865 }
866
867 // Okay, add the string we captured to the output vector and move on.
868 CheckStrings.emplace_back(P, UsedPrefix, PatternLoc);
869 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
870 DagNotMatches = ImplicitNegativeChecks;
871 }
872
873 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
874 // prefix as a filler for the error message.
875 if (!DagNotMatches.empty()) {
876 CheckStrings.emplace_back(FileCheckPattern(Check::CheckEOF), *Req.CheckPrefixes.begin(),
877 SMLoc::getFromPointer(Buffer.data()));
878 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
879 }
880
881 if (CheckStrings.empty()) {
882 errs() << "error: no check strings found with prefix"
883 << (Req.CheckPrefixes.size() > 1 ? "es " : " ");
884 auto I = Req.CheckPrefixes.begin();
885 auto E = Req.CheckPrefixes.end();
886 if (I != E) {
887 errs() << "\'" << *I << ":'";
888 ++I;
889 }
890 for (; I != E; ++I)
891 errs() << ", \'" << *I << ":'";
892
893 errs() << '\n';
894 return true;
895 }
896
897 return false;
898}
899
900static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
901 StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000902 int MatchedCount, StringRef Buffer,
903 StringMap<StringRef> &VariableTable, size_t MatchPos,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +0000904 size_t MatchLen, const FileCheckRequest &Req,
905 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000906 if (ExpectedMatch) {
907 if (!Req.Verbose)
908 return;
909 if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
910 return;
911 }
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +0000912 SMRange MatchRange = ProcessMatchResult(
Joel E. Denny7df86962018-12-18 00:03:03 +0000913 ExpectedMatch ? FileCheckDiag::MatchFinalAndExpected
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +0000914 : FileCheckDiag::MatchFinalButExcluded,
915 SM, Loc, Pat.getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000916 std::string Message = formatv("{0}: {1} string found in input",
917 Pat.getCheckTy().getDescription(Prefix),
918 (ExpectedMatch ? "expected" : "excluded"))
919 .str();
920 if (Pat.getCount() > 1)
921 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
922
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000923 SM.PrintMessage(
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000924 Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +0000925 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
926 {MatchRange});
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000927 Pat.PrintVariableUses(SM, Buffer, VariableTable, MatchRange);
928}
929
930static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000931 const FileCheckString &CheckStr, int MatchedCount,
932 StringRef Buffer, StringMap<StringRef> &VariableTable,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +0000933 size_t MatchPos, size_t MatchLen, FileCheckRequest &Req,
934 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000935 PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +0000936 MatchedCount, Buffer, VariableTable, MatchPos, MatchLen, Req,
937 Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000938}
939
940static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000941 StringRef Prefix, SMLoc Loc,
942 const FileCheckPattern &Pat, int MatchedCount,
943 StringRef Buffer, StringMap<StringRef> &VariableTable,
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000944 bool VerboseVerbose,
945 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000946 if (!ExpectedMatch && !VerboseVerbose)
947 return;
948
949 // Otherwise, we have an error, emit an error message.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000950 std::string Message = formatv("{0}: {1} string not found in input",
951 Pat.getCheckTy().getDescription(Prefix),
952 (ExpectedMatch ? "expected" : "excluded"))
953 .str();
954 if (Pat.getCount() > 1)
955 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
956
957 SM.PrintMessage(
958 Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000959
960 // Print the "scanning from here" line. If the current position is at the
961 // end of a line, advance to the start of the next line.
962 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000963 SMRange SearchRange = ProcessMatchResult(
964 ExpectedMatch ? FileCheckDiag::MatchNoneButExpected
965 : FileCheckDiag::MatchTypeCount,
966 SM, Loc, Pat.getCheckTy(), Buffer, 0, Buffer.size(), Diags);
967 SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000968
969 // Allow the pattern to print additional information if desired.
970 Pat.PrintVariableUses(SM, Buffer, VariableTable);
971 if (ExpectedMatch)
Joel E. Denny2c007c82018-12-18 00:02:04 +0000972 Pat.PrintFuzzyMatch(SM, Buffer, VariableTable, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000973}
974
975static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +0000976 const FileCheckString &CheckStr, int MatchedCount,
977 StringRef Buffer, StringMap<StringRef> &VariableTable,
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000978 bool VerboseVerbose,
979 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000980 PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
Joel E. Denny3c5d2672018-12-18 00:01:39 +0000981 MatchedCount, Buffer, VariableTable, VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +0000982}
983
984/// Count the number of newlines in the specified range.
985static unsigned CountNumNewlinesBetween(StringRef Range,
986 const char *&FirstNewLine) {
987 unsigned NumNewLines = 0;
988 while (1) {
989 // Scan for newline.
990 Range = Range.substr(Range.find_first_of("\n\r"));
991 if (Range.empty())
992 return NumNewLines;
993
994 ++NumNewLines;
995
996 // Handle \n\r and \r\n as a single newline.
997 if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
998 (Range[0] != Range[1]))
999 Range = Range.substr(1);
1000 Range = Range.substr(1);
1001
1002 if (NumNewLines == 1)
1003 FirstNewLine = Range.begin();
1004 }
1005}
1006
1007/// Match check string and its "not strings" and/or "dag strings".
1008size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001009 bool IsLabelScanMode, size_t &MatchLen,
1010 StringMap<StringRef> &VariableTable,
1011 FileCheckRequest &Req,
1012 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001013 size_t LastPos = 0;
1014 std::vector<const FileCheckPattern *> NotStrings;
1015
1016 // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
1017 // bounds; we have not processed variable definitions within the bounded block
1018 // yet so cannot handle any final CHECK-DAG yet; this is handled when going
1019 // over the block again (including the last CHECK-LABEL) in normal mode.
1020 if (!IsLabelScanMode) {
1021 // Match "dag strings" (with mixed "not strings" if any).
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001022 LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001023 if (LastPos == StringRef::npos)
1024 return StringRef::npos;
1025 }
1026
1027 // Match itself from the last position after matching CHECK-DAG.
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001028 size_t LastMatchEnd = LastPos;
1029 size_t FirstMatchPos = 0;
1030 // Go match the pattern Count times. Majority of patterns only match with
1031 // count 1 though.
1032 assert(Pat.getCount() != 0 && "pattern count can not be zero");
1033 for (int i = 1; i <= Pat.getCount(); i++) {
1034 StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
1035 size_t CurrentMatchLen;
1036 // get a match at current start point
1037 size_t MatchPos = Pat.Match(MatchBuffer, CurrentMatchLen, VariableTable);
1038 if (i == 1)
1039 FirstMatchPos = LastPos + MatchPos;
1040
1041 // report
1042 if (MatchPos == StringRef::npos) {
1043 PrintNoMatch(true, SM, *this, i, MatchBuffer, VariableTable,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001044 Req.VerboseVerbose, Diags);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001045 return StringRef::npos;
1046 }
1047 PrintMatch(true, SM, *this, i, MatchBuffer, VariableTable, MatchPos,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001048 CurrentMatchLen, Req, Diags);
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001049
1050 // move start point after the match
1051 LastMatchEnd += MatchPos + CurrentMatchLen;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001052 }
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001053 // Full match len counts from first match pos.
1054 MatchLen = LastMatchEnd - FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001055
1056 // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1057 // or CHECK-NOT
1058 if (!IsLabelScanMode) {
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001059 size_t MatchPos = FirstMatchPos - LastPos;
1060 StringRef MatchBuffer = Buffer.substr(LastPos);
1061 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001062
1063 // If this check is a "CHECK-NEXT", verify that the previous match was on
1064 // the previous line (i.e. that there is one newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001065 if (CheckNext(SM, SkippedRegion)) {
1066 ProcessMatchResult(FileCheckDiag::MatchFinalButWrongLine, SM, Loc,
1067 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001068 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001069 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001070 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001071
1072 // If this check is a "CHECK-SAME", verify that the previous match was on
1073 // the same line (i.e. that there is no newline between them).
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001074 if (CheckSame(SM, SkippedRegion)) {
1075 ProcessMatchResult(FileCheckDiag::MatchFinalButWrongLine, SM, Loc,
1076 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
Joel E. Denny7df86962018-12-18 00:03:03 +00001077 Diags, Req.Verbose);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001078 return StringRef::npos;
Joel E. Dennycadfcef2018-12-18 00:02:22 +00001079 }
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001080
1081 // If this match had "not strings", verify that they don't exist in the
1082 // skipped region.
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001083 if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001084 return StringRef::npos;
1085 }
1086
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001087 return FirstMatchPos;
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001088}
1089
1090/// Verify there is a single line in the given buffer.
1091bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1092 if (Pat.getCheckTy() != Check::CheckNext &&
1093 Pat.getCheckTy() != Check::CheckEmpty)
1094 return false;
1095
1096 Twine CheckName =
1097 Prefix +
1098 Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
1099
1100 // Count the number of newlines between the previous match and this one.
1101 assert(Buffer.data() !=
1102 SM.getMemoryBuffer(SM.FindBufferContainingLoc(
1103 SMLoc::getFromPointer(Buffer.data())))
1104 ->getBufferStart() &&
1105 "CHECK-NEXT and CHECK-EMPTY can't be the first check in a file");
1106
1107 const char *FirstNewLine = nullptr;
1108 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1109
1110 if (NumNewLines == 0) {
1111 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1112 CheckName + ": is on the same line as previous match");
1113 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1114 "'next' match was here");
1115 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1116 "previous match ended here");
1117 return true;
1118 }
1119
1120 if (NumNewLines != 1) {
1121 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1122 CheckName +
1123 ": is not on the line after the previous match");
1124 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1125 "'next' match was here");
1126 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1127 "previous match ended here");
1128 SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
1129 "non-matching line after previous match is here");
1130 return true;
1131 }
1132
1133 return false;
1134}
1135
1136/// Verify there is no newline in the given buffer.
1137bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
1138 if (Pat.getCheckTy() != Check::CheckSame)
1139 return false;
1140
1141 // Count the number of newlines between the previous match and this one.
1142 assert(Buffer.data() !=
1143 SM.getMemoryBuffer(SM.FindBufferContainingLoc(
1144 SMLoc::getFromPointer(Buffer.data())))
1145 ->getBufferStart() &&
1146 "CHECK-SAME can't be the first check in a file");
1147
1148 const char *FirstNewLine = nullptr;
1149 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1150
1151 if (NumNewLines != 0) {
1152 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1153 Prefix +
1154 "-SAME: is not on the same line as the previous match");
1155 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1156 "'next' match was here");
1157 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1158 "previous match ended here");
1159 return true;
1160 }
1161
1162 return false;
1163}
1164
1165/// Verify there's no "not strings" in the given buffer.
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001166bool FileCheckString::CheckNot(
1167 const SourceMgr &SM, StringRef Buffer,
1168 const std::vector<const FileCheckPattern *> &NotStrings,
1169 StringMap<StringRef> &VariableTable, const FileCheckRequest &Req,
1170 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001171 for (const FileCheckPattern *Pat : NotStrings) {
1172 assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1173
1174 size_t MatchLen = 0;
1175 size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);
1176
1177 if (Pos == StringRef::npos) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001178 PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001179 VariableTable, Req.VerboseVerbose, nullptr);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001180 continue;
1181 }
1182
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001183 PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, VariableTable,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001184 Pos, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001185
1186 return true;
1187 }
1188
1189 return false;
1190}
1191
1192/// Match "dag strings" and their mixed "not strings".
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001193size_t
1194FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1195 std::vector<const FileCheckPattern *> &NotStrings,
1196 StringMap<StringRef> &VariableTable,
1197 const FileCheckRequest &Req,
1198 std::vector<FileCheckDiag> *Diags) const {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001199 if (DagNotStrings.empty())
1200 return 0;
1201
1202 // The start of the search range.
1203 size_t StartPos = 0;
1204
1205 struct MatchRange {
1206 size_t Pos;
1207 size_t End;
1208 };
1209 // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
1210 // ranges are erased from this list once they are no longer in the search
1211 // range.
1212 std::list<MatchRange> MatchRanges;
1213
1214 // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
1215 // group, so we don't use a range-based for loop here.
1216 for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
1217 PatItr != PatEnd; ++PatItr) {
1218 const FileCheckPattern &Pat = *PatItr;
1219 assert((Pat.getCheckTy() == Check::CheckDAG ||
1220 Pat.getCheckTy() == Check::CheckNot) &&
1221 "Invalid CHECK-DAG or CHECK-NOT!");
1222
1223 if (Pat.getCheckTy() == Check::CheckNot) {
1224 NotStrings.push_back(&Pat);
1225 continue;
1226 }
1227
1228 assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1229
1230 // CHECK-DAG always matches from the start.
1231 size_t MatchLen = 0, MatchPos = StartPos;
1232
1233 // Search for a match that doesn't overlap a previous match in this
1234 // CHECK-DAG group.
1235 for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
1236 StringRef MatchBuffer = Buffer.substr(MatchPos);
1237 size_t MatchPosBuf = Pat.Match(MatchBuffer, MatchLen, VariableTable);
1238 // With a group of CHECK-DAGs, a single mismatching means the match on
1239 // that group of CHECK-DAGs fails immediately.
1240 if (MatchPosBuf == StringRef::npos) {
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001241 PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001242 VariableTable, Req.VerboseVerbose, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001243 return StringRef::npos;
1244 }
1245 // Re-calc it as the offset relative to the start of the original string.
1246 MatchPos += MatchPosBuf;
1247 if (Req.VerboseVerbose)
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001248 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001249 VariableTable, MatchPos, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001250 MatchRange M{MatchPos, MatchPos + MatchLen};
1251 if (Req.AllowDeprecatedDagOverlap) {
1252 // We don't need to track all matches in this mode, so we just maintain
1253 // one match range that encompasses the current CHECK-DAG group's
1254 // matches.
1255 if (MatchRanges.empty())
1256 MatchRanges.insert(MatchRanges.end(), M);
1257 else {
1258 auto Block = MatchRanges.begin();
1259 Block->Pos = std::min(Block->Pos, M.Pos);
1260 Block->End = std::max(Block->End, M.End);
1261 }
1262 break;
1263 }
1264 // Iterate previous matches until overlapping match or insertion point.
1265 bool Overlap = false;
1266 for (; MI != ME; ++MI) {
1267 if (M.Pos < MI->End) {
1268 // !Overlap => New match has no overlap and is before this old match.
1269 // Overlap => New match overlaps this old match.
1270 Overlap = MI->Pos < M.End;
1271 break;
1272 }
1273 }
1274 if (!Overlap) {
1275 // Insert non-overlapping match into list.
1276 MatchRanges.insert(MI, M);
1277 break;
1278 }
1279 if (Req.VerboseVerbose) {
1280 SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
1281 SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
1282 SMRange OldRange(OldStart, OldEnd);
1283 SM.PrintMessage(OldStart, SourceMgr::DK_Note,
1284 "match discarded, overlaps earlier DAG match here",
1285 {OldRange});
Joel E. Denny7df86962018-12-18 00:03:03 +00001286 if (Diags)
1287 Diags->pop_back();
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001288 }
1289 MatchPos = MI->End;
1290 }
1291 if (!Req.VerboseVerbose)
Fedor Sergeev6c9e19b2018-11-13 00:46:13 +00001292 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, VariableTable,
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001293 MatchPos, MatchLen, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001294
1295 // Handle the end of a CHECK-DAG group.
1296 if (std::next(PatItr) == PatEnd ||
1297 std::next(PatItr)->getCheckTy() == Check::CheckNot) {
1298 if (!NotStrings.empty()) {
1299 // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
1300 // CHECK-DAG, verify that there are no 'not' strings occurred in that
1301 // region.
1302 StringRef SkippedRegion =
1303 Buffer.slice(StartPos, MatchRanges.begin()->Pos);
Joel E. Denny0e7e3fa2018-12-18 00:02:47 +00001304 if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable, Req, Diags))
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001305 return StringRef::npos;
1306 // Clear "not strings".
1307 NotStrings.clear();
1308 }
1309 // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
1310 // end of this CHECK-DAG group's match range.
1311 StartPos = MatchRanges.rbegin()->End;
1312 // Don't waste time checking for (impossible) overlaps before that.
1313 MatchRanges.clear();
1314 }
1315 }
1316
1317 return StartPos;
1318}
1319
1320// A check prefix must contain only alphanumeric, hyphens and underscores.
1321static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1322 Regex Validator("^[a-zA-Z0-9_-]*$");
1323 return Validator.match(CheckPrefix);
1324}
1325
1326bool llvm::FileCheck::ValidateCheckPrefixes() {
1327 StringSet<> PrefixSet;
1328
1329 for (StringRef Prefix : Req.CheckPrefixes) {
1330 // Reject empty prefixes.
1331 if (Prefix == "")
1332 return false;
1333
1334 if (!PrefixSet.insert(Prefix).second)
1335 return false;
1336
1337 if (!ValidateCheckPrefix(Prefix))
1338 return false;
1339 }
1340
1341 return true;
1342}
1343
1344// Combines the check prefixes into a single regex so that we can efficiently
1345// scan for any of the set.
1346//
1347// The semantics are that the longest-match wins which matches our regex
1348// library.
1349Regex llvm::FileCheck::buildCheckPrefixRegex() {
1350 // I don't think there's a way to specify an initial value for cl::list,
1351 // so if nothing was specified, add the default
1352 if (Req.CheckPrefixes.empty())
1353 Req.CheckPrefixes.push_back("CHECK");
1354
1355 // We already validated the contents of CheckPrefixes so just concatenate
1356 // them as alternatives.
1357 SmallString<32> PrefixRegexStr;
1358 for (StringRef Prefix : Req.CheckPrefixes) {
1359 if (Prefix != Req.CheckPrefixes.front())
1360 PrefixRegexStr.push_back('|');
1361
1362 PrefixRegexStr.append(Prefix);
1363 }
1364
1365 return Regex(PrefixRegexStr);
1366}
1367
1368// Remove local variables from \p VariableTable. Global variables
1369// (start with '$') are preserved.
1370static void ClearLocalVars(StringMap<StringRef> &VariableTable) {
1371 SmallVector<StringRef, 16> LocalVars;
1372 for (const auto &Var : VariableTable)
1373 if (Var.first()[0] != '$')
1374 LocalVars.push_back(Var.first());
1375
1376 for (const auto &Var : LocalVars)
1377 VariableTable.erase(Var);
1378}
1379
1380/// Check the input to FileCheck provided in the \p Buffer against the \p
1381/// CheckStrings read from the check file.
1382///
1383/// Returns false if the input fails to satisfy the checks.
1384bool llvm::FileCheck::CheckInput(SourceMgr &SM, StringRef Buffer,
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001385 ArrayRef<FileCheckString> CheckStrings,
1386 std::vector<FileCheckDiag> *Diags) {
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001387 bool ChecksFailed = false;
1388
1389 /// VariableTable - This holds all the current filecheck variables.
1390 StringMap<StringRef> VariableTable;
1391
1392 for (const auto& Def : Req.GlobalDefines)
1393 VariableTable.insert(StringRef(Def).split('='));
1394
1395 unsigned i = 0, j = 0, e = CheckStrings.size();
1396 while (true) {
1397 StringRef CheckRegion;
1398 if (j == e) {
1399 CheckRegion = Buffer;
1400 } else {
1401 const FileCheckString &CheckLabelStr = CheckStrings[j];
1402 if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
1403 ++j;
1404 continue;
1405 }
1406
1407 // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1408 size_t MatchLabelLen = 0;
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001409 size_t MatchLabelPos = CheckLabelStr.Check(
1410 SM, Buffer, true, MatchLabelLen, VariableTable, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001411 if (MatchLabelPos == StringRef::npos)
1412 // Immediately bail of CHECK-LABEL fails, nothing else we can do.
1413 return false;
1414
1415 CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1416 Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1417 ++j;
1418 }
1419
1420 if (Req.EnableVarScope)
1421 ClearLocalVars(VariableTable);
1422
1423 for (; i != j; ++i) {
1424 const FileCheckString &CheckStr = CheckStrings[i];
1425
1426 // Check each string within the scanned region, including a second check
1427 // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1428 size_t MatchLen = 0;
Joel E. Denny3c5d2672018-12-18 00:01:39 +00001429 size_t MatchPos = CheckStr.Check(SM, CheckRegion, false, MatchLen,
1430 VariableTable, Req, Diags);
Aditya Nandakumarffa9d2e2018-08-07 21:58:49 +00001431
1432 if (MatchPos == StringRef::npos) {
1433 ChecksFailed = true;
1434 i = j;
1435 break;
1436 }
1437
1438 CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1439 }
1440
1441 if (j == e)
1442 break;
1443 }
1444
1445 // Success if no checks failed.
1446 return !ChecksFailed;
1447}