1 //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 // This program exits with an error status of 2 on error, exit status of 0 if
14 // the file matched the expected contents, and exit status of 1 if it did not
15 // contain the expected contents.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/PrettyStackTrace.h"
23 #include "llvm/Support/Regex.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/system_error.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringMap.h"
34 static cl::opt<std::string>
35 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
37 static cl::opt<std::string>
38 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
39 cl::init("-"), cl::value_desc("filename"));
41 static cl::opt<std::string>
42 CheckPrefix("check-prefix", cl::init("CHECK"),
43 cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
46 NoCanonicalizeWhiteSpace("strict-whitespace",
47 cl::desc("Do not treat all horizontal whitespace as equivalent"));
49 //===----------------------------------------------------------------------===//
50 // Pattern Handling Code.
51 //===----------------------------------------------------------------------===//
56 /// MatchEOF - When set, this pattern only matches the end of file. This is
57 /// used for trailing CHECK-NOTs.
60 /// FixedStr - If non-empty, this pattern is a fixed string match with the
61 /// specified fixed string.
64 /// RegEx - If non-empty, this is a regex pattern.
67 /// \brief Contains the number of line this pattern is in.
70 /// VariableUses - Entries in this vector map to uses of a variable in the
71 /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain
72 /// "foobaz" and we'll get an entry in this vector that tells us to insert the
73 /// value of bar at offset 3.
74 std::vector<std::pair<StringRef, unsigned> > VariableUses;
76 /// VariableDefs - Entries in this vector map to definitions of a variable in
77 /// the pattern, e.g. "foo[[bar:.*]]baz". In this case, the RegExStr will
78 /// contain "foo(.*)baz" and VariableDefs will contain the pair "bar",1. The
79 /// index indicates what parenthesized value captures the variable value.
80 std::vector<std::pair<StringRef, unsigned> > VariableDefs;
84 Pattern(bool matchEOF = false) : MatchEOF(matchEOF) { }
86 /// ParsePattern - Parse the given string into the Pattern. SM provides the
87 /// SourceMgr used for error reports, and LineNumber is the line number in
88 /// the input file from which the pattern string was read.
89 /// Returns true in case of an error, false otherwise.
90 bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
92 /// Match - Match the pattern string against the input buffer Buffer. This
93 /// returns the position that is matched or npos if there is no match. If
94 /// there is a match, the size of the matched string is returned in MatchLen.
96 /// The VariableTable StringMap provides the current values of filecheck
97 /// variables and is updated if this match defines new values.
98 size_t Match(StringRef Buffer, size_t &MatchLen,
99 StringMap<StringRef> &VariableTable) const;
101 /// PrintFailureInfo - Print additional information about a failure to match
102 /// involving this pattern.
103 void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
104 const StringMap<StringRef> &VariableTable) const;
107 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
108 bool AddRegExToRegEx(StringRef RegExStr, unsigned &CurParen, SourceMgr &SM);
110 /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
111 /// matching this pattern at the start of \arg Buffer; a distance of zero
112 /// should correspond to a perfect match.
113 unsigned ComputeMatchDistance(StringRef Buffer,
114 const StringMap<StringRef> &VariableTable) const;
116 /// \brief Evaluates expression and stores the result to \p Value.
117 /// \return true on success. false when the expression has invalid syntax.
118 bool EvaluateExpression(StringRef Expr, std::string &Value) const;
122 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
123 unsigned LineNumber) {
124 this->LineNumber = LineNumber;
125 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
127 // Ignore trailing whitespace.
128 while (!PatternStr.empty() &&
129 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
130 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
132 // Check that there is something on the line.
133 if (PatternStr.empty()) {
134 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
135 "found empty check string with prefix '" +
140 // Check to see if this is a fixed string, or if it has regex pieces.
141 if (PatternStr.size() < 2 ||
142 (PatternStr.find("{{") == StringRef::npos &&
143 PatternStr.find("[[") == StringRef::npos)) {
144 FixedStr = PatternStr;
148 // Paren value #0 is for the fully matched string. Any new parenthesized
149 // values add from there.
150 unsigned CurParen = 1;
152 // Otherwise, there is at least one regex piece. Build up the regex pattern
153 // by escaping scary characters in fixed strings, building up one big regex.
154 while (!PatternStr.empty()) {
156 if (PatternStr.startswith("{{")) {
157 // This is the start of a regex match. Scan for the }}.
158 size_t End = PatternStr.find("}}");
159 if (End == StringRef::npos) {
160 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
162 "found start of regex string with no end '}}'");
166 // Enclose {{}} patterns in parens just like [[]] even though we're not
167 // capturing the result for any purpose. This is required in case the
168 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
169 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
173 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
177 PatternStr = PatternStr.substr(End+2);
181 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
182 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
183 // second form is [[foo]] which is a reference to foo. The variable name
184 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
185 // it. This is to catch some common errors.
186 if (PatternStr.startswith("[[")) {
187 // Verify that it is terminated properly.
188 size_t End = PatternStr.find("]]");
189 if (End == StringRef::npos) {
190 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
192 "invalid named regex reference, no ]] found");
196 StringRef MatchStr = PatternStr.substr(2, End-2);
197 PatternStr = PatternStr.substr(End+2);
199 // Get the regex name (e.g. "foo").
200 size_t NameEnd = MatchStr.find(':');
201 StringRef Name = MatchStr.substr(0, NameEnd);
204 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
205 "invalid name in named regex: empty name");
209 // Verify that the name/expression is well formed. FileCheck currently
210 // supports @LINE, @LINE+number, @LINE-number expressions. The check here
211 // is relaxed, more strict check is performed in \c EvaluateExpression.
212 bool IsExpression = false;
213 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
214 if (i == 0 && Name[i] == '@') {
215 if (NameEnd != StringRef::npos) {
216 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
218 "invalid name in named regex definition");
224 if (Name[i] != '_' && !isalnum(Name[i]) &&
225 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
226 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
227 SourceMgr::DK_Error, "invalid name in named regex");
232 // Name can't start with a digit.
233 if (isdigit(Name[0])) {
234 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
235 "invalid name in named regex");
240 if (NameEnd == StringRef::npos) {
241 VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
245 // Handle [[foo:.*]].
246 VariableDefs.push_back(std::make_pair(Name, CurParen));
250 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
256 // Handle fixed string matches.
257 // Find the end, which is the start of the next regex.
258 size_t FixedMatchEnd = PatternStr.find("{{");
259 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
260 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
261 PatternStr = PatternStr.substr(FixedMatchEnd);
267 void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
268 // Add the characters from FixedStr to the regex, escaping as needed. This
269 // avoids "leaning toothpicks" in common patterns.
270 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
271 switch (FixedStr[i]) {
272 // These are the special characters matched in "p_ere_exp".
288 TheStr += FixedStr[i];
294 bool Pattern::AddRegExToRegEx(StringRef RegexStr, unsigned &CurParen,
298 if (!R.isValid(Error)) {
299 SM.PrintMessage(SMLoc::getFromPointer(RegexStr.data()), SourceMgr::DK_Error,
300 "invalid regex: " + Error);
304 RegExStr += RegexStr.str();
305 CurParen += R.getNumMatches();
309 bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
310 // The only supported expression is @LINE([\+-]\d+)?
311 if (!Expr.startswith("@LINE"))
313 Expr = Expr.substr(StringRef("@LINE").size());
317 Expr = Expr.substr(1);
318 else if (Expr[0] != '-')
320 if (Expr.getAsInteger(10, Offset))
323 Value = llvm::itostr(LineNumber + Offset);
327 /// Match - Match the pattern string against the input buffer Buffer. This
328 /// returns the position that is matched or npos if there is no match. If
329 /// there is a match, the size of the matched string is returned in MatchLen.
330 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
331 StringMap<StringRef> &VariableTable) const {
332 // If this is the EOF pattern, match it immediately.
335 return Buffer.size();
338 // If this is a fixed string pattern, just match it now.
339 if (!FixedStr.empty()) {
340 MatchLen = FixedStr.size();
341 return Buffer.find(FixedStr);
346 // If there are variable uses, we need to create a temporary string with the
348 StringRef RegExToMatch = RegExStr;
350 if (!VariableUses.empty()) {
353 unsigned InsertOffset = 0;
354 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
357 if (VariableUses[i].first[0] == '@') {
358 if (!EvaluateExpression(VariableUses[i].first, Value))
359 return StringRef::npos;
361 StringMap<StringRef>::iterator it =
362 VariableTable.find(VariableUses[i].first);
363 // If the variable is undefined, return an error.
364 if (it == VariableTable.end())
365 return StringRef::npos;
367 // Look up the value and escape it so that we can plop it into the regex.
368 AddFixedStringToRegEx(it->second, Value);
371 // Plop it into the regex at the adjusted offset.
372 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
373 Value.begin(), Value.end());
374 InsertOffset += Value.size();
377 // Match the newly constructed regex.
378 RegExToMatch = TmpStr;
382 SmallVector<StringRef, 4> MatchInfo;
383 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
384 return StringRef::npos;
386 // Successful regex match.
387 assert(!MatchInfo.empty() && "Didn't get any match");
388 StringRef FullMatch = MatchInfo[0];
390 // If this defines any variables, remember their values.
391 for (unsigned i = 0, e = VariableDefs.size(); i != e; ++i) {
392 assert(VariableDefs[i].second < MatchInfo.size() &&
393 "Internal paren error");
394 VariableTable[VariableDefs[i].first] = MatchInfo[VariableDefs[i].second];
397 MatchLen = FullMatch.size();
398 return FullMatch.data()-Buffer.data();
401 unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
402 const StringMap<StringRef> &VariableTable) const {
403 // Just compute the number of matching characters. For regular expressions, we
404 // just compare against the regex itself and hope for the best.
406 // FIXME: One easy improvement here is have the regex lib generate a single
407 // example regular expression which matches, and use that as the example
409 StringRef ExampleString(FixedStr);
410 if (ExampleString.empty())
411 ExampleString = RegExStr;
413 // Only compare up to the first line in the buffer, or the string size.
414 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
415 BufferPrefix = BufferPrefix.split('\n').first;
416 return BufferPrefix.edit_distance(ExampleString);
419 void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
420 const StringMap<StringRef> &VariableTable) const{
421 // If this was a regular expression using variables, print the current
423 if (!VariableUses.empty()) {
424 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
425 SmallString<256> Msg;
426 raw_svector_ostream OS(Msg);
427 StringRef Var = VariableUses[i].first;
430 if (EvaluateExpression(Var, Value)) {
431 OS << "with expression \"";
432 OS.write_escaped(Var) << "\" equal to \"";
433 OS.write_escaped(Value) << "\"";
435 OS << "uses incorrect expression \"";
436 OS.write_escaped(Var) << "\"";
439 StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
441 // Check for undefined variable references.
442 if (it == VariableTable.end()) {
443 OS << "uses undefined variable \"";
444 OS.write_escaped(Var) << "\"";
446 OS << "with variable \"";
447 OS.write_escaped(Var) << "\" equal to \"";
448 OS.write_escaped(it->second) << "\"";
452 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
457 // Attempt to find the closest/best fuzzy match. Usually an error happens
458 // because some string in the output didn't exactly match. In these cases, we
459 // would like to show the user a best guess at what "should have" matched, to
460 // save them having to actually check the input manually.
461 size_t NumLinesForward = 0;
462 size_t Best = StringRef::npos;
463 double BestQuality = 0;
465 // Use an arbitrary 4k limit on how far we will search.
466 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
467 if (Buffer[i] == '\n')
470 // Patterns have leading whitespace stripped, so skip whitespace when
471 // looking for something which looks like a pattern.
472 if (Buffer[i] == ' ' || Buffer[i] == '\t')
475 // Compute the "quality" of this match as an arbitrary combination of the
476 // match distance and the number of lines skipped to get to this match.
477 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
478 double Quality = Distance + (NumLinesForward / 100.);
480 if (Quality < BestQuality || Best == StringRef::npos) {
482 BestQuality = Quality;
486 // Print the "possible intended match here" line if we found something
487 // reasonable and not equal to what we showed in the "scanning from here"
489 if (Best && Best != StringRef::npos && BestQuality < 50) {
490 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
491 SourceMgr::DK_Note, "possible intended match here");
493 // FIXME: If we wanted to be really friendly we would show why the match
494 // failed, as it can be hard to spot simple one character differences.
498 //===----------------------------------------------------------------------===//
500 //===----------------------------------------------------------------------===//
502 /// CheckString - This is a check that we found in the input file.
504 /// Pat - The pattern to match.
507 /// Loc - The location in the match file that the check string was specified.
510 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
511 /// to a CHECK: directive.
514 /// NotStrings - These are all of the strings that are disallowed from
515 /// occurring between this match string and the previous one (or start of
517 std::vector<std::pair<SMLoc, Pattern> > NotStrings;
519 CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
520 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
523 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
524 /// memory buffer, free it, and return a new one.
525 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
526 SmallString<128> NewFile;
527 NewFile.reserve(MB->getBufferSize());
529 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
531 // Eliminate trailing dosish \r.
532 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
536 // If current char is not a horizontal whitespace, dump it to output as is.
537 if (*Ptr != ' ' && *Ptr != '\t') {
538 NewFile.push_back(*Ptr);
542 // Otherwise, add one space and advance over neighboring space.
543 NewFile.push_back(' ');
544 while (Ptr+1 != End &&
545 (Ptr[1] == ' ' || Ptr[1] == '\t'))
549 // Free the old buffer and return a new one.
551 MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
558 /// ReadCheckFile - Read the check file, which specifies the sequence of
559 /// expected strings. The strings are added to the CheckStrings vector.
560 /// Returns true in case of an error, false otherwise.
561 static bool ReadCheckFile(SourceMgr &SM,
562 std::vector<CheckString> &CheckStrings) {
563 OwningPtr<MemoryBuffer> File;
565 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) {
566 errs() << "Could not open check file '" << CheckFilename << "': "
567 << ec.message() << '\n';
570 MemoryBuffer *F = File.take();
572 // If we want to canonicalize whitespace, strip excess whitespace from the
573 // buffer containing the CHECK lines.
574 if (!NoCanonicalizeWhiteSpace)
575 F = CanonicalizeInputFile(F);
577 SM.AddNewSourceBuffer(F, SMLoc());
579 // Find all instances of CheckPrefix followed by : in the file.
580 StringRef Buffer = F->getBuffer();
581 std::vector<std::pair<SMLoc, Pattern> > NotMatches;
583 // LineNumber keeps track of the line on which CheckPrefix instances are
585 unsigned LineNumber = 1;
588 // See if Prefix occurs in the memory buffer.
589 size_t PrefixLoc = Buffer.find(CheckPrefix);
590 // If we didn't find a match, we're done.
591 if (PrefixLoc == StringRef::npos)
594 LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
596 Buffer = Buffer.substr(PrefixLoc);
598 const char *CheckPrefixStart = Buffer.data();
600 // When we find a check prefix, keep track of whether we find CHECK: or
602 bool IsCheckNext = false, IsCheckNot = false;
604 // Verify that the : is present after the prefix.
605 if (Buffer[CheckPrefix.size()] == ':') {
606 Buffer = Buffer.substr(CheckPrefix.size()+1);
607 } else if (Buffer.size() > CheckPrefix.size()+6 &&
608 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
609 Buffer = Buffer.substr(CheckPrefix.size()+6);
611 } else if (Buffer.size() > CheckPrefix.size()+5 &&
612 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
613 Buffer = Buffer.substr(CheckPrefix.size()+5);
616 Buffer = Buffer.substr(1);
620 // Okay, we found the prefix, yay. Remember the rest of the line, but
621 // ignore leading and trailing whitespace.
622 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
624 // Scan ahead to the end of line.
625 size_t EOL = Buffer.find_first_of("\n\r");
627 // Remember the location of the start of the pattern, for diagnostics.
628 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
630 // Parse the pattern.
632 if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
635 Buffer = Buffer.substr(EOL);
637 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
638 if (IsCheckNext && CheckStrings.empty()) {
639 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
641 "found '"+CheckPrefix+"-NEXT:' without previous '"+
642 CheckPrefix+ ": line");
648 NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
653 // Okay, add the string we captured to the output vector and move on.
654 CheckStrings.push_back(CheckString(P,
657 std::swap(NotMatches, CheckStrings.back().NotStrings);
660 // Add an EOF pattern for any trailing CHECK-NOTs.
661 if (!NotMatches.empty()) {
662 CheckStrings.push_back(CheckString(Pattern(true),
663 SMLoc::getFromPointer(Buffer.data()),
665 std::swap(NotMatches, CheckStrings.back().NotStrings);
668 if (CheckStrings.empty()) {
669 errs() << "error: no check strings found with prefix '" << CheckPrefix
677 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
679 StringMap<StringRef> &VariableTable) {
680 // Otherwise, we have an error, emit an error message.
681 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
682 "expected string not found in input");
684 // Print the "scanning from here" line. If the current position is at the
685 // end of a line, advance to the start of the next line.
686 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
688 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
689 "scanning from here");
691 // Allow the pattern to print additional information if desired.
692 CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable);
695 /// CountNumNewlinesBetween - Count the number of newlines in the specified
697 static unsigned CountNumNewlinesBetween(StringRef Range) {
698 unsigned NumNewLines = 0;
701 Range = Range.substr(Range.find_first_of("\n\r"));
702 if (Range.empty()) return NumNewLines;
706 // Handle \n\r and \r\n as a single newline.
707 if (Range.size() > 1 &&
708 (Range[1] == '\n' || Range[1] == '\r') &&
709 (Range[0] != Range[1]))
710 Range = Range.substr(1);
711 Range = Range.substr(1);
715 int main(int argc, char **argv) {
716 sys::PrintStackTraceOnErrorSignal();
717 PrettyStackTraceProgram X(argc, argv);
718 cl::ParseCommandLineOptions(argc, argv);
722 // Read the expected strings from the check file.
723 std::vector<CheckString> CheckStrings;
724 if (ReadCheckFile(SM, CheckStrings))
727 // Open the file to check and add it to SourceMgr.
728 OwningPtr<MemoryBuffer> File;
730 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
731 errs() << "Could not open input file '" << InputFilename << "': "
732 << ec.message() << '\n';
735 MemoryBuffer *F = File.take();
737 if (F->getBufferSize() == 0) {
738 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
742 // Remove duplicate spaces in the input file if requested.
743 if (!NoCanonicalizeWhiteSpace)
744 F = CanonicalizeInputFile(F);
746 SM.AddNewSourceBuffer(F, SMLoc());
748 /// VariableTable - This holds all the current filecheck variables.
749 StringMap<StringRef> VariableTable;
751 // Check that we have all of the expected strings, in order, in the input
753 StringRef Buffer = F->getBuffer();
755 const char *LastMatch = Buffer.data();
757 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
758 const CheckString &CheckStr = CheckStrings[StrNo];
760 StringRef SearchFrom = Buffer;
762 // Find StrNo in the file.
764 size_t MatchPos = CheckStr.Pat.Match(Buffer, MatchLen, VariableTable);
765 Buffer = Buffer.substr(MatchPos);
767 // If we didn't find a match, reject the input.
768 if (MatchPos == StringRef::npos) {
769 PrintCheckFailed(SM, CheckStr, SearchFrom, VariableTable);
773 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
775 // If this check is a "CHECK-NEXT", verify that the previous match was on
776 // the previous line (i.e. that there is one newline between them).
777 if (CheckStr.IsCheckNext) {
778 // Count the number of newlines between the previous match and this one.
779 assert(LastMatch != F->getBufferStart() &&
780 "CHECK-NEXT can't be the first check in a file");
782 unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
783 if (NumNewLines == 0) {
784 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
785 CheckPrefix+"-NEXT: is on the same line as previous match");
786 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
787 SourceMgr::DK_Note, "'next' match was here");
788 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
789 "previous match was here");
793 if (NumNewLines != 1) {
794 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+
795 "-NEXT: is not on the line after the previous match");
796 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
797 SourceMgr::DK_Note, "'next' match was here");
798 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
799 "previous match was here");
804 // If this match had "not strings", verify that they don't exist in the
806 for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size();
807 ChunkNo != e; ++ChunkNo) {
809 size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion,
812 if (Pos == StringRef::npos) continue;
814 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos), SourceMgr::DK_Error,
815 CheckPrefix+"-NOT: string occurred!");
816 SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first, SourceMgr::DK_Note,
817 CheckPrefix+"-NOT: pattern specified here");
822 // Otherwise, everything is good. Step over the matched text and remember
823 // the position after the match as the end of the last match.
824 Buffer = Buffer.substr(MatchLen);
825 LastMatch = Buffer.data();