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/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/Regex.h"
27 #include "llvm/Support/Signals.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/system_error.h"
37 static cl::opt<std::string>
38 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
40 static cl::opt<std::string>
41 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
42 cl::init("-"), cl::value_desc("filename"));
44 static cl::opt<std::string>
45 CheckPrefix("check-prefix", cl::init("CHECK"),
46 cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
49 NoCanonicalizeWhiteSpace("strict-whitespace",
50 cl::desc("Do not treat all horizontal whitespace as equivalent"));
52 //===----------------------------------------------------------------------===//
53 // Pattern Handling Code.
54 //===----------------------------------------------------------------------===//
59 /// MatchEOF - When set, this pattern only matches the end of file. This is
60 /// used for trailing CHECK-NOTs.
63 /// FixedStr - If non-empty, this pattern is a fixed string match with the
64 /// specified fixed string.
67 /// RegEx - If non-empty, this is a regex pattern.
70 /// \brief Contains the number of line this pattern is in.
73 /// VariableUses - Entries in this vector map to uses of a variable in the
74 /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain
75 /// "foobaz" and we'll get an entry in this vector that tells us to insert the
76 /// value of bar at offset 3.
77 std::vector<std::pair<StringRef, unsigned> > VariableUses;
79 /// VariableDefs - Maps definitions of variables to their parenthesized
81 /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
82 std::map<StringRef, unsigned> VariableDefs;
86 Pattern(bool matchEOF = false) : MatchEOF(matchEOF) { }
88 /// getLoc - Return the location in source code.
89 SMLoc getLoc() const { return PatternLoc; }
91 /// ParsePattern - Parse the given string into the Pattern. SM provides the
92 /// SourceMgr used for error reports, and LineNumber is the line number in
93 /// the input file from which the pattern string was read.
94 /// Returns true in case of an error, false otherwise.
95 bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
97 /// Match - Match the pattern string against the input buffer Buffer. This
98 /// returns the position that is matched or npos if there is no match. If
99 /// there is a match, the size of the matched string is returned in MatchLen.
101 /// The VariableTable StringMap provides the current values of filecheck
102 /// variables and is updated if this match defines new values.
103 size_t Match(StringRef Buffer, size_t &MatchLen,
104 StringMap<StringRef> &VariableTable) const;
106 /// PrintFailureInfo - Print additional information about a failure to match
107 /// involving this pattern.
108 void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
109 const StringMap<StringRef> &VariableTable) const;
112 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
113 bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
114 void AddBackrefToRegEx(unsigned BackrefNum);
116 /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
117 /// matching this pattern at the start of \arg Buffer; a distance of zero
118 /// should correspond to a perfect match.
119 unsigned ComputeMatchDistance(StringRef Buffer,
120 const StringMap<StringRef> &VariableTable) const;
122 /// \brief Evaluates expression and stores the result to \p Value.
123 /// \return true on success. false when the expression has invalid syntax.
124 bool EvaluateExpression(StringRef Expr, std::string &Value) const;
126 /// \brief Finds the closing sequence of a regex variable usage or
127 /// definition. Str has to point in the beginning of the definition
128 /// (right after the opening sequence).
129 /// \return offset of the closing sequence within Str, or npos if it was not
131 size_t FindRegexVarEnd(StringRef Str);
135 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
136 unsigned LineNumber) {
137 this->LineNumber = LineNumber;
138 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
140 // Ignore trailing whitespace.
141 while (!PatternStr.empty() &&
142 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
143 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
145 // Check that there is something on the line.
146 if (PatternStr.empty()) {
147 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
148 "found empty check string with prefix '" +
153 // Check to see if this is a fixed string, or if it has regex pieces.
154 if (PatternStr.size() < 2 ||
155 (PatternStr.find("{{") == StringRef::npos &&
156 PatternStr.find("[[") == StringRef::npos)) {
157 FixedStr = PatternStr;
161 // Paren value #0 is for the fully matched string. Any new parenthesized
162 // values add from there.
163 unsigned CurParen = 1;
165 // Otherwise, there is at least one regex piece. Build up the regex pattern
166 // by escaping scary characters in fixed strings, building up one big regex.
167 while (!PatternStr.empty()) {
169 if (PatternStr.startswith("{{")) {
170 // This is the start of a regex match. Scan for the }}.
171 size_t End = PatternStr.find("}}");
172 if (End == StringRef::npos) {
173 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
175 "found start of regex string with no end '}}'");
179 // Enclose {{}} patterns in parens just like [[]] even though we're not
180 // capturing the result for any purpose. This is required in case the
181 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
182 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
186 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
190 PatternStr = PatternStr.substr(End+2);
194 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
195 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
196 // second form is [[foo]] which is a reference to foo. The variable name
197 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
198 // it. This is to catch some common errors.
199 if (PatternStr.startswith("[[")) {
200 // Find the closing bracket pair ending the match. End is going to be an
201 // offset relative to the beginning of the match string.
202 size_t End = FindRegexVarEnd(PatternStr.substr(2));
204 if (End == StringRef::npos) {
205 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
207 "invalid named regex reference, no ]] found");
211 StringRef MatchStr = PatternStr.substr(2, End);
212 PatternStr = PatternStr.substr(End+4);
214 // Get the regex name (e.g. "foo").
215 size_t NameEnd = MatchStr.find(':');
216 StringRef Name = MatchStr.substr(0, NameEnd);
219 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
220 "invalid name in named regex: empty name");
224 // Verify that the name/expression is well formed. FileCheck currently
225 // supports @LINE, @LINE+number, @LINE-number expressions. The check here
226 // is relaxed, more strict check is performed in \c EvaluateExpression.
227 bool IsExpression = false;
228 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
229 if (i == 0 && Name[i] == '@') {
230 if (NameEnd != StringRef::npos) {
231 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
233 "invalid name in named regex definition");
239 if (Name[i] != '_' && !isalnum(Name[i]) &&
240 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
241 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
242 SourceMgr::DK_Error, "invalid name in named regex");
247 // Name can't start with a digit.
248 if (isdigit(static_cast<unsigned char>(Name[0]))) {
249 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
250 "invalid name in named regex");
255 if (NameEnd == StringRef::npos) {
256 // Handle variables that were defined earlier on the same line by
257 // emitting a backreference.
258 if (VariableDefs.find(Name) != VariableDefs.end()) {
259 unsigned VarParenNum = VariableDefs[Name];
260 if (VarParenNum < 1 || VarParenNum > 9) {
261 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
263 "Can't back-reference more than 9 variables");
266 AddBackrefToRegEx(VarParenNum);
268 VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
273 // Handle [[foo:.*]].
274 VariableDefs[Name] = CurParen;
278 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
284 // Handle fixed string matches.
285 // Find the end, which is the start of the next regex.
286 size_t FixedMatchEnd = PatternStr.find("{{");
287 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
288 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
289 PatternStr = PatternStr.substr(FixedMatchEnd);
295 void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
296 // Add the characters from FixedStr to the regex, escaping as needed. This
297 // avoids "leaning toothpicks" in common patterns.
298 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
299 switch (FixedStr[i]) {
300 // These are the special characters matched in "p_ere_exp".
316 TheStr += FixedStr[i];
322 bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
326 if (!R.isValid(Error)) {
327 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
328 "invalid regex: " + Error);
332 RegExStr += RS.str();
333 CurParen += R.getNumMatches();
337 void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
338 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
339 std::string Backref = std::string("\\") +
340 std::string(1, '0' + BackrefNum);
344 bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
345 // The only supported expression is @LINE([\+-]\d+)?
346 if (!Expr.startswith("@LINE"))
348 Expr = Expr.substr(StringRef("@LINE").size());
352 Expr = Expr.substr(1);
353 else if (Expr[0] != '-')
355 if (Expr.getAsInteger(10, Offset))
358 Value = llvm::itostr(LineNumber + Offset);
362 /// Match - Match the pattern string against the input buffer Buffer. This
363 /// returns the position that is matched or npos if there is no match. If
364 /// there is a match, the size of the matched string is returned in MatchLen.
365 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
366 StringMap<StringRef> &VariableTable) const {
367 // If this is the EOF pattern, match it immediately.
370 return Buffer.size();
373 // If this is a fixed string pattern, just match it now.
374 if (!FixedStr.empty()) {
375 MatchLen = FixedStr.size();
376 return Buffer.find(FixedStr);
381 // If there are variable uses, we need to create a temporary string with the
383 StringRef RegExToMatch = RegExStr;
385 if (!VariableUses.empty()) {
388 unsigned InsertOffset = 0;
389 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
392 if (VariableUses[i].first[0] == '@') {
393 if (!EvaluateExpression(VariableUses[i].first, Value))
394 return StringRef::npos;
396 StringMap<StringRef>::iterator it =
397 VariableTable.find(VariableUses[i].first);
398 // If the variable is undefined, return an error.
399 if (it == VariableTable.end())
400 return StringRef::npos;
402 // Look up the value and escape it so that we can plop it into the regex.
403 AddFixedStringToRegEx(it->second, Value);
406 // Plop it into the regex at the adjusted offset.
407 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
408 Value.begin(), Value.end());
409 InsertOffset += Value.size();
412 // Match the newly constructed regex.
413 RegExToMatch = TmpStr;
417 SmallVector<StringRef, 4> MatchInfo;
418 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
419 return StringRef::npos;
421 // Successful regex match.
422 assert(!MatchInfo.empty() && "Didn't get any match");
423 StringRef FullMatch = MatchInfo[0];
425 // If this defines any variables, remember their values.
426 for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
427 E = VariableDefs.end();
429 assert(I->second < MatchInfo.size() && "Internal paren error");
430 VariableTable[I->first] = MatchInfo[I->second];
433 MatchLen = FullMatch.size();
434 return FullMatch.data()-Buffer.data();
437 unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
438 const StringMap<StringRef> &VariableTable) const {
439 // Just compute the number of matching characters. For regular expressions, we
440 // just compare against the regex itself and hope for the best.
442 // FIXME: One easy improvement here is have the regex lib generate a single
443 // example regular expression which matches, and use that as the example
445 StringRef ExampleString(FixedStr);
446 if (ExampleString.empty())
447 ExampleString = RegExStr;
449 // Only compare up to the first line in the buffer, or the string size.
450 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
451 BufferPrefix = BufferPrefix.split('\n').first;
452 return BufferPrefix.edit_distance(ExampleString);
455 void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
456 const StringMap<StringRef> &VariableTable) const{
457 // If this was a regular expression using variables, print the current
459 if (!VariableUses.empty()) {
460 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
461 SmallString<256> Msg;
462 raw_svector_ostream OS(Msg);
463 StringRef Var = VariableUses[i].first;
466 if (EvaluateExpression(Var, Value)) {
467 OS << "with expression \"";
468 OS.write_escaped(Var) << "\" equal to \"";
469 OS.write_escaped(Value) << "\"";
471 OS << "uses incorrect expression \"";
472 OS.write_escaped(Var) << "\"";
475 StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
477 // Check for undefined variable references.
478 if (it == VariableTable.end()) {
479 OS << "uses undefined variable \"";
480 OS.write_escaped(Var) << "\"";
482 OS << "with variable \"";
483 OS.write_escaped(Var) << "\" equal to \"";
484 OS.write_escaped(it->second) << "\"";
488 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
493 // Attempt to find the closest/best fuzzy match. Usually an error happens
494 // because some string in the output didn't exactly match. In these cases, we
495 // would like to show the user a best guess at what "should have" matched, to
496 // save them having to actually check the input manually.
497 size_t NumLinesForward = 0;
498 size_t Best = StringRef::npos;
499 double BestQuality = 0;
501 // Use an arbitrary 4k limit on how far we will search.
502 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
503 if (Buffer[i] == '\n')
506 // Patterns have leading whitespace stripped, so skip whitespace when
507 // looking for something which looks like a pattern.
508 if (Buffer[i] == ' ' || Buffer[i] == '\t')
511 // Compute the "quality" of this match as an arbitrary combination of the
512 // match distance and the number of lines skipped to get to this match.
513 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
514 double Quality = Distance + (NumLinesForward / 100.);
516 if (Quality < BestQuality || Best == StringRef::npos) {
518 BestQuality = Quality;
522 // Print the "possible intended match here" line if we found something
523 // reasonable and not equal to what we showed in the "scanning from here"
525 if (Best && Best != StringRef::npos && BestQuality < 50) {
526 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
527 SourceMgr::DK_Note, "possible intended match here");
529 // FIXME: If we wanted to be really friendly we would show why the match
530 // failed, as it can be hard to spot simple one character differences.
534 size_t Pattern::FindRegexVarEnd(StringRef Str) {
535 // Offset keeps track of the current offset within the input Str
537 // [...] Nesting depth
538 size_t BracketDepth = 0;
540 while (!Str.empty()) {
541 if (Str.startswith("]]") && BracketDepth == 0)
543 if (Str[0] == '\\') {
544 // Backslash escapes the next char within regexes, so skip them both.
555 assert(BracketDepth > 0 && "Invalid regex");
564 return StringRef::npos;
568 //===----------------------------------------------------------------------===//
570 //===----------------------------------------------------------------------===//
572 /// CheckString - This is a check that we found in the input file.
574 /// Pat - The pattern to match.
577 /// Loc - The location in the match file that the check string was specified.
580 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
581 /// to a CHECK: directive.
584 /// NotStrings - These are all of the strings that are disallowed from
585 /// occurring between this match string and the previous one (or start of
587 std::vector<Pattern> NotStrings;
589 CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
590 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
593 /// Canonicalize whitespaces in the input file. Line endings are replaced
594 /// with UNIX-style '\n'.
596 /// \param PreserveHorizontal Don't squash consecutive horizontal whitespace
597 /// characters to a single space.
598 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB,
599 bool PreserveHorizontal) {
600 SmallString<128> NewFile;
601 NewFile.reserve(MB->getBufferSize());
603 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
605 // Eliminate trailing dosish \r.
606 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
610 // If current char is not a horizontal whitespace or if horizontal
611 // whitespace canonicalization is disabled, dump it to output as is.
612 if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) {
613 NewFile.push_back(*Ptr);
617 // Otherwise, add one space and advance over neighboring space.
618 NewFile.push_back(' ');
619 while (Ptr+1 != End &&
620 (Ptr[1] == ' ' || Ptr[1] == '\t'))
624 // Free the old buffer and return a new one.
626 MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
633 /// ReadCheckFile - Read the check file, which specifies the sequence of
634 /// expected strings. The strings are added to the CheckStrings vector.
635 /// Returns true in case of an error, false otherwise.
636 static bool ReadCheckFile(SourceMgr &SM,
637 std::vector<CheckString> &CheckStrings) {
638 OwningPtr<MemoryBuffer> File;
640 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) {
641 errs() << "Could not open check file '" << CheckFilename << "': "
642 << ec.message() << '\n';
646 // If we want to canonicalize whitespace, strip excess whitespace from the
647 // buffer containing the CHECK lines. Remove DOS style line endings.
649 CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
651 SM.AddNewSourceBuffer(F, SMLoc());
653 // Find all instances of CheckPrefix followed by : in the file.
654 StringRef Buffer = F->getBuffer();
655 std::vector<Pattern> NotMatches;
657 // LineNumber keeps track of the line on which CheckPrefix instances are
659 unsigned LineNumber = 1;
662 // See if Prefix occurs in the memory buffer.
663 size_t PrefixLoc = Buffer.find(CheckPrefix);
664 // If we didn't find a match, we're done.
665 if (PrefixLoc == StringRef::npos)
668 LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
670 Buffer = Buffer.substr(PrefixLoc);
672 const char *CheckPrefixStart = Buffer.data();
674 // When we find a check prefix, keep track of whether we find CHECK: or
676 bool IsCheckNext = false, IsCheckNot = false;
678 // Verify that the : is present after the prefix.
679 if (Buffer[CheckPrefix.size()] == ':') {
680 Buffer = Buffer.substr(CheckPrefix.size()+1);
681 } else if (Buffer.size() > CheckPrefix.size()+6 &&
682 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
683 Buffer = Buffer.substr(CheckPrefix.size()+6);
685 } else if (Buffer.size() > CheckPrefix.size()+5 &&
686 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
687 Buffer = Buffer.substr(CheckPrefix.size()+5);
690 Buffer = Buffer.substr(1);
694 // Okay, we found the prefix, yay. Remember the rest of the line, but
695 // ignore leading and trailing whitespace.
696 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
698 // Scan ahead to the end of line.
699 size_t EOL = Buffer.find_first_of("\n\r");
701 // Remember the location of the start of the pattern, for diagnostics.
702 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
704 // Parse the pattern.
706 if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
709 Buffer = Buffer.substr(EOL);
711 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
712 if (IsCheckNext && CheckStrings.empty()) {
713 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
715 "found '"+CheckPrefix+"-NEXT:' without previous '"+
716 CheckPrefix+ ": line");
722 NotMatches.push_back(P);
726 // Okay, add the string we captured to the output vector and move on.
727 CheckStrings.push_back(CheckString(P,
730 std::swap(NotMatches, CheckStrings.back().NotStrings);
733 // Add an EOF pattern for any trailing CHECK-NOTs.
734 if (!NotMatches.empty()) {
735 CheckStrings.push_back(CheckString(Pattern(true),
736 SMLoc::getFromPointer(Buffer.data()),
738 std::swap(NotMatches, CheckStrings.back().NotStrings);
741 if (CheckStrings.empty()) {
742 errs() << "error: no check strings found with prefix '" << CheckPrefix
750 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
752 StringMap<StringRef> &VariableTable) {
753 // Otherwise, we have an error, emit an error message.
754 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
755 "expected string not found in input");
757 // Print the "scanning from here" line. If the current position is at the
758 // end of a line, advance to the start of the next line.
759 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
761 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
762 "scanning from here");
764 // Allow the pattern to print additional information if desired.
765 CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable);
768 /// CountNumNewlinesBetween - Count the number of newlines in the specified
770 static unsigned CountNumNewlinesBetween(StringRef Range) {
771 unsigned NumNewLines = 0;
774 Range = Range.substr(Range.find_first_of("\n\r"));
775 if (Range.empty()) return NumNewLines;
779 // Handle \n\r and \r\n as a single newline.
780 if (Range.size() > 1 &&
781 (Range[1] == '\n' || Range[1] == '\r') &&
782 (Range[0] != Range[1]))
783 Range = Range.substr(1);
784 Range = Range.substr(1);
788 int main(int argc, char **argv) {
789 sys::PrintStackTraceOnErrorSignal();
790 PrettyStackTraceProgram X(argc, argv);
791 cl::ParseCommandLineOptions(argc, argv);
795 // Read the expected strings from the check file.
796 std::vector<CheckString> CheckStrings;
797 if (ReadCheckFile(SM, CheckStrings))
800 // Open the file to check and add it to SourceMgr.
801 OwningPtr<MemoryBuffer> File;
803 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
804 errs() << "Could not open input file '" << InputFilename << "': "
805 << ec.message() << '\n';
809 if (File->getBufferSize() == 0) {
810 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
814 // Remove duplicate spaces in the input file if requested.
815 // Remove DOS style line endings.
817 CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
819 SM.AddNewSourceBuffer(F, SMLoc());
821 /// VariableTable - This holds all the current filecheck variables.
822 StringMap<StringRef> VariableTable;
824 // Check that we have all of the expected strings, in order, in the input
826 StringRef Buffer = F->getBuffer();
828 const char *LastMatch = Buffer.data();
830 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
831 const CheckString &CheckStr = CheckStrings[StrNo];
833 StringRef SearchFrom = Buffer;
835 // Find StrNo in the file.
837 size_t MatchPos = CheckStr.Pat.Match(Buffer, MatchLen, VariableTable);
838 Buffer = Buffer.substr(MatchPos);
840 // If we didn't find a match, reject the input.
841 if (MatchPos == StringRef::npos) {
842 PrintCheckFailed(SM, CheckStr, SearchFrom, VariableTable);
846 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
848 // If this check is a "CHECK-NEXT", verify that the previous match was on
849 // the previous line (i.e. that there is one newline between them).
850 if (CheckStr.IsCheckNext) {
851 // Count the number of newlines between the previous match and this one.
852 assert(LastMatch != F->getBufferStart() &&
853 "CHECK-NEXT can't be the first check in a file");
855 unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
856 if (NumNewLines == 0) {
857 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
858 CheckPrefix+"-NEXT: is on the same line as previous match");
859 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
860 SourceMgr::DK_Note, "'next' match was here");
861 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
862 "previous match was here");
866 if (NumNewLines != 1) {
867 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+
868 "-NEXT: is not on the line after the previous match");
869 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
870 SourceMgr::DK_Note, "'next' match was here");
871 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
872 "previous match was here");
877 // If this match had "not strings", verify that they don't exist in the
879 for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size();
880 ChunkNo != e; ++ChunkNo) {
882 size_t Pos = CheckStr.NotStrings[ChunkNo].Match(SkippedRegion, MatchLen,
884 if (Pos == StringRef::npos) continue;
886 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos), SourceMgr::DK_Error,
887 CheckPrefix+"-NOT: string occurred!");
888 SM.PrintMessage(CheckStr.NotStrings[ChunkNo].getLoc(), SourceMgr::DK_Note,
889 CheckPrefix+"-NOT: pattern specified here");
894 // Otherwise, everything is good. Step over the matched text and remember
895 // the position after the match as the end of the last match.
896 Buffer = Buffer.substr(MatchLen);
897 LastMatch = Buffer.data();