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"
38 static cl::opt<std::string>
39 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
41 static cl::opt<std::string>
42 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
43 cl::init("-"), cl::value_desc("filename"));
45 static cl::opt<std::string>
46 CheckPrefix("check-prefix", cl::init("CHECK"),
47 cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
50 NoCanonicalizeWhiteSpace("strict-whitespace",
51 cl::desc("Do not treat all horizontal whitespace as equivalent"));
53 //===----------------------------------------------------------------------===//
54 // Pattern Handling Code.
55 //===----------------------------------------------------------------------===//
66 /// MatchEOF - When set, this pattern only matches the end of file. This is
67 /// used for trailing CHECK-NOTs.
75 Check::CheckType CheckTy;
77 /// FixedStr - If non-empty, this pattern is a fixed string match with the
78 /// specified fixed string.
81 /// RegEx - If non-empty, this is a regex pattern.
84 /// \brief Contains the number of line this pattern is in.
87 /// VariableUses - Entries in this vector map to uses of a variable in the
88 /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain
89 /// "foobaz" and we'll get an entry in this vector that tells us to insert the
90 /// value of bar at offset 3.
91 std::vector<std::pair<StringRef, unsigned> > VariableUses;
93 /// VariableDefs - Maps definitions of variables to their parenthesized
95 /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
96 std::map<StringRef, unsigned> VariableDefs;
100 Pattern(Check::CheckType Ty)
103 /// getLoc - Return the location in source code.
104 SMLoc getLoc() const { return PatternLoc; }
106 /// ParsePattern - Parse the given string into the Pattern. SM provides the
107 /// SourceMgr used for error reports, and LineNumber is the line number in
108 /// the input file from which the pattern string was read.
109 /// Returns true in case of an error, false otherwise.
110 bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
112 /// Match - Match the pattern string against the input buffer Buffer. This
113 /// returns the position that is matched or npos if there is no match. If
114 /// there is a match, the size of the matched string is returned in MatchLen.
116 /// The VariableTable StringMap provides the current values of filecheck
117 /// variables and is updated if this match defines new values.
118 size_t Match(StringRef Buffer, size_t &MatchLen,
119 StringMap<StringRef> &VariableTable) const;
121 /// PrintFailureInfo - Print additional information about a failure to match
122 /// involving this pattern.
123 void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
124 const StringMap<StringRef> &VariableTable) const;
126 bool hasVariable() const { return !(VariableUses.empty() &&
127 VariableDefs.empty()); }
129 Check::CheckType getCheckTy() const { return CheckTy; }
132 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
133 bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
134 void AddBackrefToRegEx(unsigned BackrefNum);
136 /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
137 /// matching this pattern at the start of \arg Buffer; a distance of zero
138 /// should correspond to a perfect match.
139 unsigned ComputeMatchDistance(StringRef Buffer,
140 const StringMap<StringRef> &VariableTable) const;
142 /// \brief Evaluates expression and stores the result to \p Value.
143 /// \return true on success. false when the expression has invalid syntax.
144 bool EvaluateExpression(StringRef Expr, std::string &Value) const;
146 /// \brief Finds the closing sequence of a regex variable usage or
147 /// definition. Str has to point in the beginning of the definition
148 /// (right after the opening sequence).
149 /// \return offset of the closing sequence within Str, or npos if it was not
151 size_t FindRegexVarEnd(StringRef Str);
155 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
156 unsigned LineNumber) {
157 this->LineNumber = LineNumber;
158 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
160 // Ignore trailing whitespace.
161 while (!PatternStr.empty() &&
162 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
163 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
165 // Check that there is something on the line.
166 if (PatternStr.empty()) {
167 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
168 "found empty check string with prefix '" +
173 // Check to see if this is a fixed string, or if it has regex pieces.
174 if (PatternStr.size() < 2 ||
175 (PatternStr.find("{{") == StringRef::npos &&
176 PatternStr.find("[[") == StringRef::npos)) {
177 FixedStr = PatternStr;
181 // Paren value #0 is for the fully matched string. Any new parenthesized
182 // values add from there.
183 unsigned CurParen = 1;
185 // Otherwise, there is at least one regex piece. Build up the regex pattern
186 // by escaping scary characters in fixed strings, building up one big regex.
187 while (!PatternStr.empty()) {
189 if (PatternStr.startswith("{{")) {
190 // This is the start of a regex match. Scan for the }}.
191 size_t End = PatternStr.find("}}");
192 if (End == StringRef::npos) {
193 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
195 "found start of regex string with no end '}}'");
199 // Enclose {{}} patterns in parens just like [[]] even though we're not
200 // capturing the result for any purpose. This is required in case the
201 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
202 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
206 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
210 PatternStr = PatternStr.substr(End+2);
214 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
215 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
216 // second form is [[foo]] which is a reference to foo. The variable name
217 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
218 // it. This is to catch some common errors.
219 if (PatternStr.startswith("[[")) {
220 // Find the closing bracket pair ending the match. End is going to be an
221 // offset relative to the beginning of the match string.
222 size_t End = FindRegexVarEnd(PatternStr.substr(2));
224 if (End == StringRef::npos) {
225 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
227 "invalid named regex reference, no ]] found");
231 StringRef MatchStr = PatternStr.substr(2, End);
232 PatternStr = PatternStr.substr(End+4);
234 // Get the regex name (e.g. "foo").
235 size_t NameEnd = MatchStr.find(':');
236 StringRef Name = MatchStr.substr(0, NameEnd);
239 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
240 "invalid name in named regex: empty name");
244 // Verify that the name/expression is well formed. FileCheck currently
245 // supports @LINE, @LINE+number, @LINE-number expressions. The check here
246 // is relaxed, more strict check is performed in \c EvaluateExpression.
247 bool IsExpression = false;
248 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
249 if (i == 0 && Name[i] == '@') {
250 if (NameEnd != StringRef::npos) {
251 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
253 "invalid name in named regex definition");
259 if (Name[i] != '_' && !isalnum(Name[i]) &&
260 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
261 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
262 SourceMgr::DK_Error, "invalid name in named regex");
267 // Name can't start with a digit.
268 if (isdigit(static_cast<unsigned char>(Name[0]))) {
269 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
270 "invalid name in named regex");
275 if (NameEnd == StringRef::npos) {
276 // Handle variables that were defined earlier on the same line by
277 // emitting a backreference.
278 if (VariableDefs.find(Name) != VariableDefs.end()) {
279 unsigned VarParenNum = VariableDefs[Name];
280 if (VarParenNum < 1 || VarParenNum > 9) {
281 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
283 "Can't back-reference more than 9 variables");
286 AddBackrefToRegEx(VarParenNum);
288 VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
293 // Handle [[foo:.*]].
294 VariableDefs[Name] = CurParen;
298 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
304 // Handle fixed string matches.
305 // Find the end, which is the start of the next regex.
306 size_t FixedMatchEnd = PatternStr.find("{{");
307 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
308 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
309 PatternStr = PatternStr.substr(FixedMatchEnd);
315 void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
316 // Add the characters from FixedStr to the regex, escaping as needed. This
317 // avoids "leaning toothpicks" in common patterns.
318 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
319 switch (FixedStr[i]) {
320 // These are the special characters matched in "p_ere_exp".
336 TheStr += FixedStr[i];
342 bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
346 if (!R.isValid(Error)) {
347 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
348 "invalid regex: " + Error);
352 RegExStr += RS.str();
353 CurParen += R.getNumMatches();
357 void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
358 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
359 std::string Backref = std::string("\\") +
360 std::string(1, '0' + BackrefNum);
364 bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
365 // The only supported expression is @LINE([\+-]\d+)?
366 if (!Expr.startswith("@LINE"))
368 Expr = Expr.substr(StringRef("@LINE").size());
372 Expr = Expr.substr(1);
373 else if (Expr[0] != '-')
375 if (Expr.getAsInteger(10, Offset))
378 Value = llvm::itostr(LineNumber + Offset);
382 /// Match - Match the pattern string against the input buffer Buffer. This
383 /// returns the position that is matched or npos if there is no match. If
384 /// there is a match, the size of the matched string is returned in MatchLen.
385 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
386 StringMap<StringRef> &VariableTable) const {
387 // If this is the EOF pattern, match it immediately.
388 if (CheckTy == Check::CheckEOF) {
390 return Buffer.size();
393 // If this is a fixed string pattern, just match it now.
394 if (!FixedStr.empty()) {
395 MatchLen = FixedStr.size();
396 return Buffer.find(FixedStr);
401 // If there are variable uses, we need to create a temporary string with the
403 StringRef RegExToMatch = RegExStr;
405 if (!VariableUses.empty()) {
408 unsigned InsertOffset = 0;
409 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
412 if (VariableUses[i].first[0] == '@') {
413 if (!EvaluateExpression(VariableUses[i].first, Value))
414 return StringRef::npos;
416 StringMap<StringRef>::iterator it =
417 VariableTable.find(VariableUses[i].first);
418 // If the variable is undefined, return an error.
419 if (it == VariableTable.end())
420 return StringRef::npos;
422 // Look up the value and escape it so that we can plop it into the regex.
423 AddFixedStringToRegEx(it->second, Value);
426 // Plop it into the regex at the adjusted offset.
427 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
428 Value.begin(), Value.end());
429 InsertOffset += Value.size();
432 // Match the newly constructed regex.
433 RegExToMatch = TmpStr;
437 SmallVector<StringRef, 4> MatchInfo;
438 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
439 return StringRef::npos;
441 // Successful regex match.
442 assert(!MatchInfo.empty() && "Didn't get any match");
443 StringRef FullMatch = MatchInfo[0];
445 // If this defines any variables, remember their values.
446 for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
447 E = VariableDefs.end();
449 assert(I->second < MatchInfo.size() && "Internal paren error");
450 VariableTable[I->first] = MatchInfo[I->second];
453 MatchLen = FullMatch.size();
454 return FullMatch.data()-Buffer.data();
457 unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
458 const StringMap<StringRef> &VariableTable) const {
459 // Just compute the number of matching characters. For regular expressions, we
460 // just compare against the regex itself and hope for the best.
462 // FIXME: One easy improvement here is have the regex lib generate a single
463 // example regular expression which matches, and use that as the example
465 StringRef ExampleString(FixedStr);
466 if (ExampleString.empty())
467 ExampleString = RegExStr;
469 // Only compare up to the first line in the buffer, or the string size.
470 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
471 BufferPrefix = BufferPrefix.split('\n').first;
472 return BufferPrefix.edit_distance(ExampleString);
475 void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
476 const StringMap<StringRef> &VariableTable) const{
477 // If this was a regular expression using variables, print the current
479 if (!VariableUses.empty()) {
480 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
481 SmallString<256> Msg;
482 raw_svector_ostream OS(Msg);
483 StringRef Var = VariableUses[i].first;
486 if (EvaluateExpression(Var, Value)) {
487 OS << "with expression \"";
488 OS.write_escaped(Var) << "\" equal to \"";
489 OS.write_escaped(Value) << "\"";
491 OS << "uses incorrect expression \"";
492 OS.write_escaped(Var) << "\"";
495 StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
497 // Check for undefined variable references.
498 if (it == VariableTable.end()) {
499 OS << "uses undefined variable \"";
500 OS.write_escaped(Var) << "\"";
502 OS << "with variable \"";
503 OS.write_escaped(Var) << "\" equal to \"";
504 OS.write_escaped(it->second) << "\"";
508 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
513 // Attempt to find the closest/best fuzzy match. Usually an error happens
514 // because some string in the output didn't exactly match. In these cases, we
515 // would like to show the user a best guess at what "should have" matched, to
516 // save them having to actually check the input manually.
517 size_t NumLinesForward = 0;
518 size_t Best = StringRef::npos;
519 double BestQuality = 0;
521 // Use an arbitrary 4k limit on how far we will search.
522 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
523 if (Buffer[i] == '\n')
526 // Patterns have leading whitespace stripped, so skip whitespace when
527 // looking for something which looks like a pattern.
528 if (Buffer[i] == ' ' || Buffer[i] == '\t')
531 // Compute the "quality" of this match as an arbitrary combination of the
532 // match distance and the number of lines skipped to get to this match.
533 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
534 double Quality = Distance + (NumLinesForward / 100.);
536 if (Quality < BestQuality || Best == StringRef::npos) {
538 BestQuality = Quality;
542 // Print the "possible intended match here" line if we found something
543 // reasonable and not equal to what we showed in the "scanning from here"
545 if (Best && Best != StringRef::npos && BestQuality < 50) {
546 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
547 SourceMgr::DK_Note, "possible intended match here");
549 // FIXME: If we wanted to be really friendly we would show why the match
550 // failed, as it can be hard to spot simple one character differences.
554 size_t Pattern::FindRegexVarEnd(StringRef Str) {
555 // Offset keeps track of the current offset within the input Str
557 // [...] Nesting depth
558 size_t BracketDepth = 0;
560 while (!Str.empty()) {
561 if (Str.startswith("]]") && BracketDepth == 0)
563 if (Str[0] == '\\') {
564 // Backslash escapes the next char within regexes, so skip them both.
575 assert(BracketDepth > 0 && "Invalid regex");
584 return StringRef::npos;
588 //===----------------------------------------------------------------------===//
590 //===----------------------------------------------------------------------===//
592 /// CheckString - This is a check that we found in the input file.
594 /// Pat - The pattern to match.
597 /// Loc - The location in the match file that the check string was specified.
600 /// CheckTy - Specify what kind of check this is. e.g. CHECK-NEXT: directive,
601 /// as opposed to a CHECK: directive.
602 Check::CheckType CheckTy;
604 /// DagNotStrings - These are all of the strings that are disallowed from
605 /// occurring between this match string and the previous one (or start of
607 std::vector<Pattern> DagNotStrings;
609 CheckString(const Pattern &P, SMLoc L, Check::CheckType Ty)
610 : Pat(P), Loc(L), CheckTy(Ty) {}
612 /// Check - Match check string and its "not strings" and/or "dag strings".
613 size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode,
614 size_t &MatchLen, StringMap<StringRef> &VariableTable) const;
616 /// CheckNext - Verify there is a single line in the given buffer.
617 bool CheckNext(const SourceMgr &SM, StringRef Buffer) const;
619 /// CheckNot - Verify there's no "not strings" in the given buffer.
620 bool CheckNot(const SourceMgr &SM, StringRef Buffer,
621 const std::vector<const Pattern *> &NotStrings,
622 StringMap<StringRef> &VariableTable) const;
624 /// CheckDag - Match "dag strings" and their mixed "not strings".
625 size_t CheckDag(const SourceMgr &SM, StringRef Buffer,
626 std::vector<const Pattern *> &NotStrings,
627 StringMap<StringRef> &VariableTable) const;
630 /// Canonicalize whitespaces in the input file. Line endings are replaced
631 /// with UNIX-style '\n'.
633 /// \param PreserveHorizontal Don't squash consecutive horizontal whitespace
634 /// characters to a single space.
635 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB,
636 bool PreserveHorizontal) {
637 SmallString<128> NewFile;
638 NewFile.reserve(MB->getBufferSize());
640 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
642 // Eliminate trailing dosish \r.
643 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
647 // If current char is not a horizontal whitespace or if horizontal
648 // whitespace canonicalization is disabled, dump it to output as is.
649 if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) {
650 NewFile.push_back(*Ptr);
654 // Otherwise, add one space and advance over neighboring space.
655 NewFile.push_back(' ');
656 while (Ptr+1 != End &&
657 (Ptr[1] == ' ' || Ptr[1] == '\t'))
661 // Free the old buffer and return a new one.
663 MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
669 static bool IsPartOfWord(char c) {
670 return (isalnum(c) || c == '-' || c == '_');
673 static Check::CheckType FindCheckType(StringRef &Buffer, StringRef Prefix) {
674 char NextChar = Buffer[Prefix.size()];
676 // Verify that the : is present after the prefix.
677 if (NextChar == ':') {
678 Buffer = Buffer.substr(Prefix.size() + 1);
679 return Check::CheckPlain;
682 if (NextChar != '-') {
683 Buffer = Buffer.drop_front(1);
684 return Check::CheckNone;
687 StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
688 if (Rest.startswith("NEXT:")) {
689 Buffer = Rest.drop_front(sizeof("NEXT:") - 1);
690 return Check::CheckNext;
693 if (Rest.startswith("NOT:")) {
694 Buffer = Rest.drop_front(sizeof("NOT:") - 1);
695 return Check::CheckNot;
698 if (Rest.startswith("DAG:")) {
699 Buffer = Rest.drop_front(sizeof("DAG:") - 1);
700 return Check::CheckDAG;
703 if (Rest.startswith("LABEL:")) {
704 Buffer = Rest.drop_front(sizeof("LABEL:") - 1);
705 return Check::CheckLabel;
708 Buffer = Buffer.drop_front(1);
709 return Check::CheckNone;
712 /// ReadCheckFile - Read the check file, which specifies the sequence of
713 /// expected strings. The strings are added to the CheckStrings vector.
714 /// Returns true in case of an error, false otherwise.
715 static bool ReadCheckFile(SourceMgr &SM,
716 std::vector<CheckString> &CheckStrings) {
717 OwningPtr<MemoryBuffer> File;
719 MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) {
720 errs() << "Could not open check file '" << CheckFilename << "': "
721 << ec.message() << '\n';
725 // If we want to canonicalize whitespace, strip excess whitespace from the
726 // buffer containing the CHECK lines. Remove DOS style line endings.
728 CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
730 SM.AddNewSourceBuffer(F, SMLoc());
732 // Find all instances of CheckPrefix followed by : in the file.
733 StringRef Buffer = F->getBuffer();
734 std::vector<Pattern> DagNotMatches;
736 // LineNumber keeps track of the line on which CheckPrefix instances are
738 unsigned LineNumber = 1;
741 // See if Prefix occurs in the memory buffer.
742 size_t PrefixLoc = Buffer.find(CheckPrefix);
743 // If we didn't find a match, we're done.
744 if (PrefixLoc == StringRef::npos)
747 LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
749 // Keep the charcter before our prefix so we can validate that we have
750 // found our prefix, and account for cases when PrefixLoc is 0.
751 Buffer = Buffer.substr(std::min(PrefixLoc-1, PrefixLoc));
753 const char *CheckPrefixStart = Buffer.data() + (PrefixLoc == 0 ? 0 : 1);
755 // Make sure we have actually found our prefix, and not a word containing
757 if (PrefixLoc != 0 && IsPartOfWord(Buffer[0])) {
758 Buffer = Buffer.substr(CheckPrefix.size());
762 // When we find a check prefix, keep track of what kind of type of CHECK we
764 Check::CheckType CheckTy = FindCheckType(Buffer, CheckPrefix);
765 if (CheckTy == Check::CheckNone)
768 // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
769 // leading and trailing whitespace.
770 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
772 // Scan ahead to the end of line.
773 size_t EOL = Buffer.find_first_of("\n\r");
775 // Remember the location of the start of the pattern, for diagnostics.
776 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
778 // Parse the pattern.
780 if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
783 // Verify that CHECK-LABEL lines do not define or use variables
784 if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
785 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
787 "found '"+CheckPrefix+"-LABEL:' with variable definition"
792 Buffer = Buffer.substr(EOL);
794 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
795 if ((CheckTy == Check::CheckNext) && CheckStrings.empty()) {
796 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
798 "found '"+CheckPrefix+"-NEXT:' without previous '"+
799 CheckPrefix+ ": line");
803 // Handle CHECK-DAG/-NOT.
804 if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
805 DagNotMatches.push_back(P);
809 // Okay, add the string we captured to the output vector and move on.
810 CheckStrings.push_back(CheckString(P,
813 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
816 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs.
817 if (!DagNotMatches.empty()) {
818 CheckStrings.push_back(CheckString(Pattern(Check::CheckEOF),
819 SMLoc::getFromPointer(Buffer.data()),
821 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
824 if (CheckStrings.empty()) {
825 errs() << "error: no check strings found with prefix '" << CheckPrefix
833 static void PrintCheckFailed(const SourceMgr &SM, const SMLoc &Loc,
834 const Pattern &Pat, StringRef Buffer,
835 StringMap<StringRef> &VariableTable) {
836 // Otherwise, we have an error, emit an error message.
837 SM.PrintMessage(Loc, SourceMgr::DK_Error,
838 "expected string not found in input");
840 // Print the "scanning from here" line. If the current position is at the
841 // end of a line, advance to the start of the next line.
842 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
844 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
845 "scanning from here");
847 // Allow the pattern to print additional information if desired.
848 Pat.PrintFailureInfo(SM, Buffer, VariableTable);
851 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
853 StringMap<StringRef> &VariableTable) {
854 PrintCheckFailed(SM, CheckStr.Loc, CheckStr.Pat, Buffer, VariableTable);
857 /// CountNumNewlinesBetween - Count the number of newlines in the specified
859 static unsigned CountNumNewlinesBetween(StringRef Range) {
860 unsigned NumNewLines = 0;
863 Range = Range.substr(Range.find_first_of("\n\r"));
864 if (Range.empty()) return NumNewLines;
868 // Handle \n\r and \r\n as a single newline.
869 if (Range.size() > 1 &&
870 (Range[1] == '\n' || Range[1] == '\r') &&
871 (Range[0] != Range[1]))
872 Range = Range.substr(1);
873 Range = Range.substr(1);
877 size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer,
878 bool IsLabelScanMode, size_t &MatchLen,
879 StringMap<StringRef> &VariableTable) const {
881 std::vector<const Pattern *> NotStrings;
883 // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
884 // bounds; we have not processed variable definitions within the bounded block
885 // yet so cannot handle any final CHECK-DAG yet; this is handled when going
886 // over the block again (including the last CHECK-LABEL) in normal mode.
887 if (!IsLabelScanMode) {
888 // Match "dag strings" (with mixed "not strings" if any).
889 LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable);
890 if (LastPos == StringRef::npos)
891 return StringRef::npos;
894 // Match itself from the last position after matching CHECK-DAG.
895 StringRef MatchBuffer = Buffer.substr(LastPos);
896 size_t MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
897 if (MatchPos == StringRef::npos) {
898 PrintCheckFailed(SM, *this, MatchBuffer, VariableTable);
899 return StringRef::npos;
903 // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
905 if (!IsLabelScanMode) {
906 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
908 // If this check is a "CHECK-NEXT", verify that the previous match was on
909 // the previous line (i.e. that there is one newline between them).
910 if (CheckNext(SM, SkippedRegion))
911 return StringRef::npos;
913 // If this match had "not strings", verify that they don't exist in the
915 if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
916 return StringRef::npos;
922 bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
923 if (CheckTy != Check::CheckNext)
926 // Count the number of newlines between the previous match and this one.
927 assert(Buffer.data() !=
929 SM.FindBufferContainingLoc(
930 SMLoc::getFromPointer(Buffer.data())))->getBufferStart() &&
931 "CHECK-NEXT can't be the first check in a file");
933 unsigned NumNewLines = CountNumNewlinesBetween(Buffer);
935 if (NumNewLines == 0) {
936 SM.PrintMessage(Loc, SourceMgr::DK_Error, CheckPrefix+
937 "-NEXT: is on the same line as previous match");
938 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
939 SourceMgr::DK_Note, "'next' match was here");
940 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
941 "previous match ended here");
945 if (NumNewLines != 1) {
946 SM.PrintMessage(Loc, SourceMgr::DK_Error, CheckPrefix+
947 "-NEXT: is not on the line after the previous match");
948 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
949 SourceMgr::DK_Note, "'next' match was here");
950 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
951 "previous match ended here");
958 bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer,
959 const std::vector<const Pattern *> &NotStrings,
960 StringMap<StringRef> &VariableTable) const {
961 for (unsigned ChunkNo = 0, e = NotStrings.size();
962 ChunkNo != e; ++ChunkNo) {
963 const Pattern *Pat = NotStrings[ChunkNo];
964 assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
967 size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);
969 if (Pos == StringRef::npos) continue;
971 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos),
973 CheckPrefix+"-NOT: string occurred!");
974 SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note,
975 CheckPrefix+"-NOT: pattern specified here");
982 size_t CheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
983 std::vector<const Pattern *> &NotStrings,
984 StringMap<StringRef> &VariableTable) const {
985 if (DagNotStrings.empty())
989 size_t StartPos = LastPos;
991 for (unsigned ChunkNo = 0, e = DagNotStrings.size();
992 ChunkNo != e; ++ChunkNo) {
993 const Pattern &Pat = DagNotStrings[ChunkNo];
995 assert((Pat.getCheckTy() == Check::CheckDAG ||
996 Pat.getCheckTy() == Check::CheckNot) &&
997 "Invalid CHECK-DAG or CHECK-NOT!");
999 if (Pat.getCheckTy() == Check::CheckNot) {
1000 NotStrings.push_back(&Pat);
1004 assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1006 size_t MatchLen = 0, MatchPos;
1008 // CHECK-DAG always matches from the start.
1009 StringRef MatchBuffer = Buffer.substr(StartPos);
1010 MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
1011 // With a group of CHECK-DAGs, a single mismatching means the match on
1012 // that group of CHECK-DAGs fails immediately.
1013 if (MatchPos == StringRef::npos) {
1014 PrintCheckFailed(SM, Pat.getLoc(), Pat, MatchBuffer, VariableTable);
1015 return StringRef::npos;
1017 // Re-calc it as the offset relative to the start of the original string.
1018 MatchPos += StartPos;
1020 if (!NotStrings.empty()) {
1021 if (MatchPos < LastPos) {
1023 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + MatchPos),
1024 SourceMgr::DK_Error,
1025 CheckPrefix+"-DAG: found a match of CHECK-DAG"
1026 " reordering across a CHECK-NOT");
1027 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + LastPos),
1029 CheckPrefix+"-DAG: the farthest match of CHECK-DAG"
1031 SM.PrintMessage(NotStrings[0]->getLoc(), SourceMgr::DK_Note,
1032 CheckPrefix+"-NOT: the crossed pattern specified"
1034 SM.PrintMessage(Pat.getLoc(), SourceMgr::DK_Note,
1035 CheckPrefix+"-DAG: the reordered pattern specified"
1037 return StringRef::npos;
1039 // All subsequent CHECK-DAGs should be matched from the farthest
1040 // position of all precedent CHECK-DAGs (including this one.)
1042 // If there's CHECK-NOTs between two CHECK-DAGs or from CHECK to
1043 // CHECK-DAG, verify that there's no 'not' strings occurred in that
1045 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1046 if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
1047 return StringRef::npos;
1048 // Clear "not strings".
1052 // Update the last position with CHECK-DAG matches.
1053 LastPos = std::max(MatchPos + MatchLen, LastPos);
1059 bool ValidateCheckPrefix() {
1060 // The check prefix must contain only alphanumeric, hyphens and underscores.
1061 Regex prefixValidator("^[a-zA-Z0-9_-]*$");
1062 return prefixValidator.match(CheckPrefix);
1065 int main(int argc, char **argv) {
1066 sys::PrintStackTraceOnErrorSignal();
1067 PrettyStackTraceProgram X(argc, argv);
1068 cl::ParseCommandLineOptions(argc, argv);
1070 if (!ValidateCheckPrefix()) {
1071 errs() << "Supplied check-prefix is invalid! Prefixes must start with a "
1072 "letter and contain only alphanumeric characters, hyphens and "
1079 // Read the expected strings from the check file.
1080 std::vector<CheckString> CheckStrings;
1081 if (ReadCheckFile(SM, CheckStrings))
1084 // Open the file to check and add it to SourceMgr.
1085 OwningPtr<MemoryBuffer> File;
1087 MemoryBuffer::getFileOrSTDIN(InputFilename, File)) {
1088 errs() << "Could not open input file '" << InputFilename << "': "
1089 << ec.message() << '\n';
1093 if (File->getBufferSize() == 0) {
1094 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
1098 // Remove duplicate spaces in the input file if requested.
1099 // Remove DOS style line endings.
1101 CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
1103 SM.AddNewSourceBuffer(F, SMLoc());
1105 /// VariableTable - This holds all the current filecheck variables.
1106 StringMap<StringRef> VariableTable;
1108 // Check that we have all of the expected strings, in order, in the input
1110 StringRef Buffer = F->getBuffer();
1112 bool hasError = false;
1114 unsigned i = 0, j = 0, e = CheckStrings.size();
1117 StringRef CheckRegion;
1119 CheckRegion = Buffer;
1121 const CheckString &CheckLabelStr = CheckStrings[j];
1122 if (CheckLabelStr.CheckTy != Check::CheckLabel) {
1127 // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1128 size_t MatchLabelLen = 0;
1129 size_t MatchLabelPos = CheckLabelStr.Check(SM, Buffer, true,
1130 MatchLabelLen, VariableTable);
1131 if (MatchLabelPos == StringRef::npos) {
1136 CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1137 Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1141 for ( ; i != j; ++i) {
1142 const CheckString &CheckStr = CheckStrings[i];
1144 // Check each string within the scanned region, including a second check
1145 // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1146 size_t MatchLen = 0;
1147 size_t MatchPos = CheckStr.Check(SM, CheckRegion, false, MatchLen,
1150 if (MatchPos == StringRef::npos) {
1156 CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1163 return hasError ? 1 : 0;