Expose FileCheck's AddFixedStringToRegEx as Regex::escape
[oota-llvm.git] / utils / FileCheck / FileCheck.cpp
1 //===- 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 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.
16 //
17 //===----------------------------------------------------------------------===//
18
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/ADT/StringSet.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/PrettyStackTrace.h"
27 #include "llvm/Support/Regex.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/system_error.h"
32 #include <algorithm>
33 #include <cctype>
34 #include <map>
35 #include <string>
36 #include <vector>
37 using namespace llvm;
38
39 static cl::opt<std::string>
40 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
41
42 static cl::opt<std::string>
43 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
44               cl::init("-"), cl::value_desc("filename"));
45
46 static cl::list<std::string>
47 CheckPrefixes("check-prefix",
48               cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
49
50 static cl::opt<bool>
51 NoCanonicalizeWhiteSpace("strict-whitespace",
52               cl::desc("Do not treat all horizontal whitespace as equivalent"));
53
54 typedef cl::list<std::string>::const_iterator prefix_iterator;
55
56 //===----------------------------------------------------------------------===//
57 // Pattern Handling Code.
58 //===----------------------------------------------------------------------===//
59
60 namespace Check {
61   enum CheckType {
62     CheckNone = 0,
63     CheckPlain,
64     CheckNext,
65     CheckNot,
66     CheckDAG,
67     CheckLabel,
68
69     /// MatchEOF - When set, this pattern only matches the end of file. This is
70     /// used for trailing CHECK-NOTs.
71     CheckEOF
72   };
73 }
74
75 class Pattern {
76   SMLoc PatternLoc;
77
78   Check::CheckType CheckTy;
79
80   /// FixedStr - If non-empty, this pattern is a fixed string match with the
81   /// specified fixed string.
82   StringRef FixedStr;
83
84   /// RegEx - If non-empty, this is a regex pattern.
85   std::string RegExStr;
86
87   /// \brief Contains the number of line this pattern is in.
88   unsigned LineNumber;
89
90   /// VariableUses - Entries in this vector map to uses of a variable in the
91   /// pattern, e.g. "foo[[bar]]baz".  In this case, the RegExStr will contain
92   /// "foobaz" and we'll get an entry in this vector that tells us to insert the
93   /// value of bar at offset 3.
94   std::vector<std::pair<StringRef, unsigned> > VariableUses;
95
96   /// VariableDefs - Maps definitions of variables to their parenthesized
97   /// capture numbers.
98   /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
99   std::map<StringRef, unsigned> VariableDefs;
100
101 public:
102
103   Pattern(Check::CheckType Ty)
104     : CheckTy(Ty) { }
105
106   /// getLoc - Return the location in source code.
107   SMLoc getLoc() const { return PatternLoc; }
108
109   /// ParsePattern - Parse the given string into the Pattern. Prefix provides
110   /// which prefix is being matched, SM provides the SourceMgr used for error
111   /// reports, and LineNumber is the line number in the input file from which
112   /// the pattern string was read.  Returns true in case of an error, false
113   /// otherwise.
114   bool ParsePattern(StringRef PatternStr,
115                     StringRef Prefix,
116                     SourceMgr &SM,
117                     unsigned LineNumber);
118
119   /// Match - Match the pattern string against the input buffer Buffer.  This
120   /// returns the position that is matched or npos if there is no match.  If
121   /// there is a match, the size of the matched string is returned in MatchLen.
122   ///
123   /// The VariableTable StringMap provides the current values of filecheck
124   /// variables and is updated if this match defines new values.
125   size_t Match(StringRef Buffer, size_t &MatchLen,
126                StringMap<StringRef> &VariableTable) const;
127
128   /// PrintFailureInfo - Print additional information about a failure to match
129   /// involving this pattern.
130   void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
131                         const StringMap<StringRef> &VariableTable) const;
132
133   bool hasVariable() const { return !(VariableUses.empty() &&
134                                       VariableDefs.empty()); }
135
136   Check::CheckType getCheckTy() const { return CheckTy; }
137
138 private:
139   bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
140   void AddBackrefToRegEx(unsigned BackrefNum);
141
142   /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
143   /// matching this pattern at the start of \arg Buffer; a distance of zero
144   /// should correspond to a perfect match.
145   unsigned ComputeMatchDistance(StringRef Buffer,
146                                const StringMap<StringRef> &VariableTable) const;
147
148   /// \brief Evaluates expression and stores the result to \p Value.
149   /// \return true on success. false when the expression has invalid syntax.
150   bool EvaluateExpression(StringRef Expr, std::string &Value) const;
151
152   /// \brief Finds the closing sequence of a regex variable usage or
153   /// definition. Str has to point in the beginning of the definition
154   /// (right after the opening sequence).
155   /// \return offset of the closing sequence within Str, or npos if it was not
156   /// found.
157   size_t FindRegexVarEnd(StringRef Str);
158 };
159
160
161 bool Pattern::ParsePattern(StringRef PatternStr,
162                            StringRef Prefix,
163                            SourceMgr &SM,
164                            unsigned LineNumber) {
165   this->LineNumber = LineNumber;
166   PatternLoc = SMLoc::getFromPointer(PatternStr.data());
167
168   // Ignore trailing whitespace.
169   while (!PatternStr.empty() &&
170          (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
171     PatternStr = PatternStr.substr(0, PatternStr.size()-1);
172
173   // Check that there is something on the line.
174   if (PatternStr.empty()) {
175     SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
176                     "found empty check string with prefix '" +
177                     Prefix + ":'");
178     return true;
179   }
180
181   // Check to see if this is a fixed string, or if it has regex pieces.
182   if (PatternStr.size() < 2 ||
183       (PatternStr.find("{{") == StringRef::npos &&
184        PatternStr.find("[[") == StringRef::npos)) {
185     FixedStr = PatternStr;
186     return false;
187   }
188
189   // Paren value #0 is for the fully matched string.  Any new parenthesized
190   // values add from there.
191   unsigned CurParen = 1;
192
193   // Otherwise, there is at least one regex piece.  Build up the regex pattern
194   // by escaping scary characters in fixed strings, building up one big regex.
195   while (!PatternStr.empty()) {
196     // RegEx matches.
197     if (PatternStr.startswith("{{")) {
198       // This is the start of a regex match.  Scan for the }}.
199       size_t End = PatternStr.find("}}");
200       if (End == StringRef::npos) {
201         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
202                         SourceMgr::DK_Error,
203                         "found start of regex string with no end '}}'");
204         return true;
205       }
206
207       // Enclose {{}} patterns in parens just like [[]] even though we're not
208       // capturing the result for any purpose.  This is required in case the
209       // expression contains an alternation like: CHECK:  abc{{x|z}}def.  We
210       // want this to turn into: "abc(x|z)def" not "abcx|zdef".
211       RegExStr += '(';
212       ++CurParen;
213
214       if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
215         return true;
216       RegExStr += ')';
217
218       PatternStr = PatternStr.substr(End+2);
219       continue;
220     }
221
222     // Named RegEx matches.  These are of two forms: [[foo:.*]] which matches .*
223     // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
224     // second form is [[foo]] which is a reference to foo.  The variable name
225     // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
226     // it.  This is to catch some common errors.
227     if (PatternStr.startswith("[[")) {
228       // Find the closing bracket pair ending the match.  End is going to be an
229       // offset relative to the beginning of the match string.
230       size_t End = FindRegexVarEnd(PatternStr.substr(2));
231
232       if (End == StringRef::npos) {
233         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
234                         SourceMgr::DK_Error,
235                         "invalid named regex reference, no ]] found");
236         return true;
237       }
238
239       StringRef MatchStr = PatternStr.substr(2, End);
240       PatternStr = PatternStr.substr(End+4);
241
242       // Get the regex name (e.g. "foo").
243       size_t NameEnd = MatchStr.find(':');
244       StringRef Name = MatchStr.substr(0, NameEnd);
245
246       if (Name.empty()) {
247         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
248                         "invalid name in named regex: empty name");
249         return true;
250       }
251
252       // Verify that the name/expression is well formed. FileCheck currently
253       // supports @LINE, @LINE+number, @LINE-number expressions. The check here
254       // is relaxed, more strict check is performed in \c EvaluateExpression.
255       bool IsExpression = false;
256       for (unsigned i = 0, e = Name.size(); i != e; ++i) {
257         if (i == 0 && Name[i] == '@') {
258           if (NameEnd != StringRef::npos) {
259             SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
260                             SourceMgr::DK_Error,
261                             "invalid name in named regex definition");
262             return true;
263           }
264           IsExpression = true;
265           continue;
266         }
267         if (Name[i] != '_' && !isalnum(Name[i]) &&
268             (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
269           SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
270                           SourceMgr::DK_Error, "invalid name in named regex");
271           return true;
272         }
273       }
274
275       // Name can't start with a digit.
276       if (isdigit(static_cast<unsigned char>(Name[0]))) {
277         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
278                         "invalid name in named regex");
279         return true;
280       }
281
282       // Handle [[foo]].
283       if (NameEnd == StringRef::npos) {
284         // Handle variables that were defined earlier on the same line by
285         // emitting a backreference.
286         if (VariableDefs.find(Name) != VariableDefs.end()) {
287           unsigned VarParenNum = VariableDefs[Name];
288           if (VarParenNum < 1 || VarParenNum > 9) {
289             SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
290                             SourceMgr::DK_Error,
291                             "Can't back-reference more than 9 variables");
292             return true;
293           }
294           AddBackrefToRegEx(VarParenNum);
295         } else {
296           VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
297         }
298         continue;
299       }
300
301       // Handle [[foo:.*]].
302       VariableDefs[Name] = CurParen;
303       RegExStr += '(';
304       ++CurParen;
305
306       if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
307         return true;
308
309       RegExStr += ')';
310     }
311
312     // Handle fixed string matches.
313     // Find the end, which is the start of the next regex.
314     size_t FixedMatchEnd = PatternStr.find("{{");
315     FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
316     RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
317     PatternStr = PatternStr.substr(FixedMatchEnd);
318   }
319
320   return false;
321 }
322
323 bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
324                               SourceMgr &SM) {
325   Regex R(RS);
326   std::string Error;
327   if (!R.isValid(Error)) {
328     SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
329                     "invalid regex: " + Error);
330     return true;
331   }
332
333   RegExStr += RS.str();
334   CurParen += R.getNumMatches();
335   return false;
336 }
337
338 void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
339   assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
340   std::string Backref = std::string("\\") +
341                         std::string(1, '0' + BackrefNum);
342   RegExStr += Backref;
343 }
344
345 bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
346   // The only supported expression is @LINE([\+-]\d+)?
347   if (!Expr.startswith("@LINE"))
348     return false;
349   Expr = Expr.substr(StringRef("@LINE").size());
350   int Offset = 0;
351   if (!Expr.empty()) {
352     if (Expr[0] == '+')
353       Expr = Expr.substr(1);
354     else if (Expr[0] != '-')
355       return false;
356     if (Expr.getAsInteger(10, Offset))
357       return false;
358   }
359   Value = llvm::itostr(LineNumber + Offset);
360   return true;
361 }
362
363 /// Match - Match the pattern string against the input buffer Buffer.  This
364 /// returns the position that is matched or npos if there is no match.  If
365 /// there is a match, the size of the matched string is returned in MatchLen.
366 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
367                       StringMap<StringRef> &VariableTable) const {
368   // If this is the EOF pattern, match it immediately.
369   if (CheckTy == Check::CheckEOF) {
370     MatchLen = 0;
371     return Buffer.size();
372   }
373
374   // If this is a fixed string pattern, just match it now.
375   if (!FixedStr.empty()) {
376     MatchLen = FixedStr.size();
377     return Buffer.find(FixedStr);
378   }
379
380   // Regex match.
381
382   // If there are variable uses, we need to create a temporary string with the
383   // actual value.
384   StringRef RegExToMatch = RegExStr;
385   std::string TmpStr;
386   if (!VariableUses.empty()) {
387     TmpStr = RegExStr;
388
389     unsigned InsertOffset = 0;
390     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
391       std::string Value;
392
393       if (VariableUses[i].first[0] == '@') {
394         if (!EvaluateExpression(VariableUses[i].first, Value))
395           return StringRef::npos;
396       } else {
397         StringMap<StringRef>::iterator it =
398           VariableTable.find(VariableUses[i].first);
399         // If the variable is undefined, return an error.
400         if (it == VariableTable.end())
401           return StringRef::npos;
402
403         // Look up the value and escape it so that we can put it into the regex.
404         Value += Regex::escape(it->second);
405       }
406
407       // Plop it into the regex at the adjusted offset.
408       TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
409                     Value.begin(), Value.end());
410       InsertOffset += Value.size();
411     }
412
413     // Match the newly constructed regex.
414     RegExToMatch = TmpStr;
415   }
416
417
418   SmallVector<StringRef, 4> MatchInfo;
419   if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
420     return StringRef::npos;
421
422   // Successful regex match.
423   assert(!MatchInfo.empty() && "Didn't get any match");
424   StringRef FullMatch = MatchInfo[0];
425
426   // If this defines any variables, remember their values.
427   for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
428                                                      E = VariableDefs.end();
429        I != E; ++I) {
430     assert(I->second < MatchInfo.size() && "Internal paren error");
431     VariableTable[I->first] = MatchInfo[I->second];
432   }
433
434   MatchLen = FullMatch.size();
435   return FullMatch.data()-Buffer.data();
436 }
437
438 unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
439                               const StringMap<StringRef> &VariableTable) const {
440   // Just compute the number of matching characters. For regular expressions, we
441   // just compare against the regex itself and hope for the best.
442   //
443   // FIXME: One easy improvement here is have the regex lib generate a single
444   // example regular expression which matches, and use that as the example
445   // string.
446   StringRef ExampleString(FixedStr);
447   if (ExampleString.empty())
448     ExampleString = RegExStr;
449
450   // Only compare up to the first line in the buffer, or the string size.
451   StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
452   BufferPrefix = BufferPrefix.split('\n').first;
453   return BufferPrefix.edit_distance(ExampleString);
454 }
455
456 void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
457                                const StringMap<StringRef> &VariableTable) const{
458   // If this was a regular expression using variables, print the current
459   // variable values.
460   if (!VariableUses.empty()) {
461     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
462       SmallString<256> Msg;
463       raw_svector_ostream OS(Msg);
464       StringRef Var = VariableUses[i].first;
465       if (Var[0] == '@') {
466         std::string Value;
467         if (EvaluateExpression(Var, Value)) {
468           OS << "with expression \"";
469           OS.write_escaped(Var) << "\" equal to \"";
470           OS.write_escaped(Value) << "\"";
471         } else {
472           OS << "uses incorrect expression \"";
473           OS.write_escaped(Var) << "\"";
474         }
475       } else {
476         StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
477
478         // Check for undefined variable references.
479         if (it == VariableTable.end()) {
480           OS << "uses undefined variable \"";
481           OS.write_escaped(Var) << "\"";
482         } else {
483           OS << "with variable \"";
484           OS.write_escaped(Var) << "\" equal to \"";
485           OS.write_escaped(it->second) << "\"";
486         }
487       }
488
489       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
490                       OS.str());
491     }
492   }
493
494   // Attempt to find the closest/best fuzzy match.  Usually an error happens
495   // because some string in the output didn't exactly match. In these cases, we
496   // would like to show the user a best guess at what "should have" matched, to
497   // save them having to actually check the input manually.
498   size_t NumLinesForward = 0;
499   size_t Best = StringRef::npos;
500   double BestQuality = 0;
501
502   // Use an arbitrary 4k limit on how far we will search.
503   for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
504     if (Buffer[i] == '\n')
505       ++NumLinesForward;
506
507     // Patterns have leading whitespace stripped, so skip whitespace when
508     // looking for something which looks like a pattern.
509     if (Buffer[i] == ' ' || Buffer[i] == '\t')
510       continue;
511
512     // Compute the "quality" of this match as an arbitrary combination of the
513     // match distance and the number of lines skipped to get to this match.
514     unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
515     double Quality = Distance + (NumLinesForward / 100.);
516
517     if (Quality < BestQuality || Best == StringRef::npos) {
518       Best = i;
519       BestQuality = Quality;
520     }
521   }
522
523   // Print the "possible intended match here" line if we found something
524   // reasonable and not equal to what we showed in the "scanning from here"
525   // line.
526   if (Best && Best != StringRef::npos && BestQuality < 50) {
527       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
528                       SourceMgr::DK_Note, "possible intended match here");
529
530     // FIXME: If we wanted to be really friendly we would show why the match
531     // failed, as it can be hard to spot simple one character differences.
532   }
533 }
534
535 size_t Pattern::FindRegexVarEnd(StringRef Str) {
536   // Offset keeps track of the current offset within the input Str
537   size_t Offset = 0;
538   // [...] Nesting depth
539   size_t BracketDepth = 0;
540
541   while (!Str.empty()) {
542     if (Str.startswith("]]") && BracketDepth == 0)
543       return Offset;
544     if (Str[0] == '\\') {
545       // Backslash escapes the next char within regexes, so skip them both.
546       Str = Str.substr(2);
547       Offset += 2;
548     } else {
549       switch (Str[0]) {
550         default:
551           break;
552         case '[':
553           BracketDepth++;
554           break;
555         case ']':
556           assert(BracketDepth > 0 && "Invalid regex");
557           BracketDepth--;
558           break;
559       }
560       Str = Str.substr(1);
561       Offset++;
562     }
563   }
564
565   return StringRef::npos;
566 }
567
568
569 //===----------------------------------------------------------------------===//
570 // Check Strings.
571 //===----------------------------------------------------------------------===//
572
573 /// CheckString - This is a check that we found in the input file.
574 struct CheckString {
575   /// Pat - The pattern to match.
576   Pattern Pat;
577
578   /// Prefix - Which prefix name this check matched.
579   StringRef Prefix;
580
581   /// Loc - The location in the match file that the check string was specified.
582   SMLoc Loc;
583
584   /// CheckTy - Specify what kind of check this is. e.g. CHECK-NEXT: directive,
585   /// as opposed to a CHECK: directive.
586   Check::CheckType CheckTy;
587
588   /// DagNotStrings - These are all of the strings that are disallowed from
589   /// occurring between this match string and the previous one (or start of
590   /// file).
591   std::vector<Pattern> DagNotStrings;
592
593
594   CheckString(const Pattern &P,
595               StringRef S,
596               SMLoc L,
597               Check::CheckType Ty)
598     : Pat(P), Prefix(S), Loc(L), CheckTy(Ty) {}
599
600   /// Check - Match check string and its "not strings" and/or "dag strings".
601   size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode,
602                size_t &MatchLen, StringMap<StringRef> &VariableTable) const;
603
604   /// CheckNext - Verify there is a single line in the given buffer.
605   bool CheckNext(const SourceMgr &SM, StringRef Buffer) const;
606
607   /// CheckNot - Verify there's no "not strings" in the given buffer.
608   bool CheckNot(const SourceMgr &SM, StringRef Buffer,
609                 const std::vector<const Pattern *> &NotStrings,
610                 StringMap<StringRef> &VariableTable) const;
611
612   /// CheckDag - Match "dag strings" and their mixed "not strings".
613   size_t CheckDag(const SourceMgr &SM, StringRef Buffer,
614                   std::vector<const Pattern *> &NotStrings,
615                   StringMap<StringRef> &VariableTable) const;
616 };
617
618 /// Canonicalize whitespaces in the input file. Line endings are replaced
619 /// with UNIX-style '\n'.
620 ///
621 /// \param PreserveHorizontal Don't squash consecutive horizontal whitespace
622 /// characters to a single space.
623 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB,
624                                            bool PreserveHorizontal) {
625   SmallString<128> NewFile;
626   NewFile.reserve(MB->getBufferSize());
627
628   for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
629        Ptr != End; ++Ptr) {
630     // Eliminate trailing dosish \r.
631     if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
632       continue;
633     }
634
635     // If current char is not a horizontal whitespace or if horizontal
636     // whitespace canonicalization is disabled, dump it to output as is.
637     if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) {
638       NewFile.push_back(*Ptr);
639       continue;
640     }
641
642     // Otherwise, add one space and advance over neighboring space.
643     NewFile.push_back(' ');
644     while (Ptr+1 != End &&
645            (Ptr[1] == ' ' || Ptr[1] == '\t'))
646       ++Ptr;
647   }
648
649   // Free the old buffer and return a new one.
650   MemoryBuffer *MB2 =
651     MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
652
653   delete MB;
654   return MB2;
655 }
656
657 static bool IsPartOfWord(char c) {
658   return (isalnum(c) || c == '-' || c == '_');
659 }
660
661 // Get the size of the prefix extension.
662 static size_t CheckTypeSize(Check::CheckType Ty) {
663   switch (Ty) {
664   case Check::CheckNone:
665     return 0;
666
667   case Check::CheckPlain:
668     return sizeof(":") - 1;
669
670   case Check::CheckNext:
671     return sizeof("-NEXT:") - 1;
672
673   case Check::CheckNot:
674     return sizeof("-NOT:") - 1;
675
676   case Check::CheckDAG:
677     return sizeof("-DAG:") - 1;
678
679   case Check::CheckLabel:
680     return sizeof("-LABEL:") - 1;
681
682   case Check::CheckEOF:
683     llvm_unreachable("Should not be using EOF size");
684   }
685
686   llvm_unreachable("Bad check type");
687 }
688
689 static Check::CheckType FindCheckType(StringRef Buffer, StringRef Prefix) {
690   char NextChar = Buffer[Prefix.size()];
691
692   // Verify that the : is present after the prefix.
693   if (NextChar == ':')
694     return Check::CheckPlain;
695
696   if (NextChar != '-')
697     return Check::CheckNone;
698
699   StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
700   if (Rest.startswith("NEXT:"))
701     return Check::CheckNext;
702
703   if (Rest.startswith("NOT:"))
704     return Check::CheckNot;
705
706   if (Rest.startswith("DAG:"))
707     return Check::CheckDAG;
708
709   if (Rest.startswith("LABEL:"))
710     return Check::CheckLabel;
711
712   return Check::CheckNone;
713 }
714
715 // From the given position, find the next character after the word.
716 static size_t SkipWord(StringRef Str, size_t Loc) {
717   while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
718     ++Loc;
719   return Loc;
720 }
721
722 // Try to find the first match in buffer for any prefix. If a valid match is
723 // found, return that prefix and set its type and location.  If there are almost
724 // matches (e.g. the actual prefix string is found, but is not an actual check
725 // string), but no valid match, return an empty string and set the position to
726 // resume searching from. If no partial matches are found, return an empty
727 // string and the location will be StringRef::npos. If one prefix is a substring
728 // of another, the maximal match should be found. e.g. if "A" and "AA" are
729 // prefixes then AA-CHECK: should match the second one.
730 static StringRef FindFirstCandidateMatch(StringRef &Buffer,
731                                          Check::CheckType &CheckTy,
732                                          size_t &CheckLoc) {
733   StringRef FirstPrefix;
734   size_t FirstLoc = StringRef::npos;
735   size_t SearchLoc = StringRef::npos;
736   Check::CheckType FirstTy = Check::CheckNone;
737
738   CheckTy = Check::CheckNone;
739   CheckLoc = StringRef::npos;
740
741   for (prefix_iterator I = CheckPrefixes.begin(), E = CheckPrefixes.end();
742        I != E; ++I) {
743     StringRef Prefix(*I);
744     size_t PrefixLoc = Buffer.find(Prefix);
745
746     if (PrefixLoc == StringRef::npos)
747       continue;
748
749     // Track where we are searching for invalid prefixes that look almost right.
750     // We need to only advance to the first partial match on the next attempt
751     // since a partial match could be a substring of a later, valid prefix.
752     // Need to skip to the end of the word, otherwise we could end up
753     // matching a prefix in a substring later.
754     if (PrefixLoc < SearchLoc)
755       SearchLoc = SkipWord(Buffer, PrefixLoc);
756
757     // We only want to find the first match to avoid skipping some.
758     if (PrefixLoc > FirstLoc)
759       continue;
760     // If one matching check-prefix is a prefix of another, choose the
761     // longer one.
762     if (PrefixLoc == FirstLoc && Prefix.size() < FirstPrefix.size())
763       continue;
764
765     StringRef Rest = Buffer.drop_front(PrefixLoc);
766     // Make sure we have actually found the prefix, and not a word containing
767     // it. This should also prevent matching the wrong prefix when one is a
768     // substring of another.
769     if (PrefixLoc != 0 && IsPartOfWord(Buffer[PrefixLoc - 1]))
770       FirstTy = Check::CheckNone;
771     else
772       FirstTy = FindCheckType(Rest, Prefix);
773
774     FirstLoc = PrefixLoc;
775     FirstPrefix = Prefix;
776   }
777
778   // If the first prefix is invalid, we should continue the search after it.
779   if (FirstTy == Check::CheckNone) {
780     CheckLoc = SearchLoc;
781     return "";
782   }
783
784   CheckTy = FirstTy;
785   CheckLoc = FirstLoc;
786   return FirstPrefix;
787 }
788
789 static StringRef FindFirstMatchingPrefix(StringRef &Buffer,
790                                          unsigned &LineNumber,
791                                          Check::CheckType &CheckTy,
792                                          size_t &CheckLoc) {
793   while (!Buffer.empty()) {
794     StringRef Prefix = FindFirstCandidateMatch(Buffer, CheckTy, CheckLoc);
795     // If we found a real match, we are done.
796     if (!Prefix.empty()) {
797       LineNumber += Buffer.substr(0, CheckLoc).count('\n');
798       return Prefix;
799     }
800
801     // We didn't find any almost matches either, we are also done.
802     if (CheckLoc == StringRef::npos)
803       return StringRef();
804
805     LineNumber += Buffer.substr(0, CheckLoc + 1).count('\n');
806
807     // Advance to the last possible match we found and try again.
808     Buffer = Buffer.drop_front(CheckLoc + 1);
809   }
810
811   return StringRef();
812 }
813
814 /// ReadCheckFile - Read the check file, which specifies the sequence of
815 /// expected strings.  The strings are added to the CheckStrings vector.
816 /// Returns true in case of an error, false otherwise.
817 static bool ReadCheckFile(SourceMgr &SM,
818                           std::vector<CheckString> &CheckStrings) {
819   OwningPtr<MemoryBuffer> File;
820   if (error_code ec =
821         MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) {
822     errs() << "Could not open check file '" << CheckFilename << "': "
823            << ec.message() << '\n';
824     return true;
825   }
826
827   // If we want to canonicalize whitespace, strip excess whitespace from the
828   // buffer containing the CHECK lines. Remove DOS style line endings.
829   MemoryBuffer *F =
830     CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
831
832   SM.AddNewSourceBuffer(F, SMLoc());
833
834   // Find all instances of CheckPrefix followed by : in the file.
835   StringRef Buffer = F->getBuffer();
836   std::vector<Pattern> DagNotMatches;
837
838   // LineNumber keeps track of the line on which CheckPrefix instances are
839   // found.
840   unsigned LineNumber = 1;
841
842   while (1) {
843     Check::CheckType CheckTy;
844     size_t PrefixLoc;
845
846     // See if a prefix occurs in the memory buffer.
847     StringRef UsedPrefix = FindFirstMatchingPrefix(Buffer,
848                                                    LineNumber,
849                                                    CheckTy,
850                                                    PrefixLoc);
851     if (UsedPrefix.empty())
852       break;
853
854     Buffer = Buffer.drop_front(PrefixLoc);
855
856     // Location to use for error messages.
857     const char *UsedPrefixStart = Buffer.data() + (PrefixLoc == 0 ? 0 : 1);
858
859     // PrefixLoc is to the start of the prefix. Skip to the end.
860     Buffer = Buffer.drop_front(UsedPrefix.size() + CheckTypeSize(CheckTy));
861
862     // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
863     // leading and trailing whitespace.
864     Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
865
866     // Scan ahead to the end of line.
867     size_t EOL = Buffer.find_first_of("\n\r");
868
869     // Remember the location of the start of the pattern, for diagnostics.
870     SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
871
872     // Parse the pattern.
873     Pattern P(CheckTy);
874     if (P.ParsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, LineNumber))
875       return true;
876
877     // Verify that CHECK-LABEL lines do not define or use variables
878     if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
879       SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
880                       SourceMgr::DK_Error,
881                       "found '" + UsedPrefix + "-LABEL:'"
882                       " with variable definition or use");
883       return true;
884     }
885
886     Buffer = Buffer.substr(EOL);
887
888     // Verify that CHECK-NEXT lines have at least one CHECK line before them.
889     if ((CheckTy == Check::CheckNext) && CheckStrings.empty()) {
890       SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
891                       SourceMgr::DK_Error,
892                       "found '" + UsedPrefix + "-NEXT:' without previous '"
893                       + UsedPrefix + ": line");
894       return true;
895     }
896
897     // Handle CHECK-DAG/-NOT.
898     if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
899       DagNotMatches.push_back(P);
900       continue;
901     }
902
903     // Okay, add the string we captured to the output vector and move on.
904     CheckStrings.push_back(CheckString(P,
905                                        UsedPrefix,
906                                        PatternLoc,
907                                        CheckTy));
908     std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
909   }
910
911   // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
912   // prefix as a filler for the error message.
913   if (!DagNotMatches.empty()) {
914     CheckStrings.push_back(CheckString(Pattern(Check::CheckEOF),
915                                        CheckPrefixes[0],
916                                        SMLoc::getFromPointer(Buffer.data()),
917                                        Check::CheckEOF));
918     std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
919   }
920
921   if (CheckStrings.empty()) {
922     errs() << "error: no check strings found with prefix"
923            << (CheckPrefixes.size() > 1 ? "es " : " ");
924     for (size_t I = 0, N = CheckPrefixes.size(); I != N; ++I) {
925       StringRef Prefix(CheckPrefixes[I]);
926       errs() << '\'' << Prefix << ":'";
927       if (I != N - 1)
928         errs() << ", ";
929     }
930
931     errs() << '\n';
932     return true;
933   }
934
935   return false;
936 }
937
938 static void PrintCheckFailed(const SourceMgr &SM, const SMLoc &Loc,
939                              const Pattern &Pat, StringRef Buffer,
940                              StringMap<StringRef> &VariableTable) {
941   // Otherwise, we have an error, emit an error message.
942   SM.PrintMessage(Loc, SourceMgr::DK_Error,
943                   "expected string not found in input");
944
945   // Print the "scanning from here" line.  If the current position is at the
946   // end of a line, advance to the start of the next line.
947   Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
948
949   SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
950                   "scanning from here");
951
952   // Allow the pattern to print additional information if desired.
953   Pat.PrintFailureInfo(SM, Buffer, VariableTable);
954 }
955
956 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
957                              StringRef Buffer,
958                              StringMap<StringRef> &VariableTable) {
959   PrintCheckFailed(SM, CheckStr.Loc, CheckStr.Pat, Buffer, VariableTable);
960 }
961
962 /// CountNumNewlinesBetween - Count the number of newlines in the specified
963 /// range.
964 static unsigned CountNumNewlinesBetween(StringRef Range) {
965   unsigned NumNewLines = 0;
966   while (1) {
967     // Scan for newline.
968     Range = Range.substr(Range.find_first_of("\n\r"));
969     if (Range.empty()) return NumNewLines;
970
971     ++NumNewLines;
972
973     // Handle \n\r and \r\n as a single newline.
974     if (Range.size() > 1 &&
975         (Range[1] == '\n' || Range[1] == '\r') &&
976         (Range[0] != Range[1]))
977       Range = Range.substr(1);
978     Range = Range.substr(1);
979   }
980 }
981
982 size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer,
983                           bool IsLabelScanMode, size_t &MatchLen,
984                           StringMap<StringRef> &VariableTable) const {
985   size_t LastPos = 0;
986   std::vector<const Pattern *> NotStrings;
987
988   // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
989   // bounds; we have not processed variable definitions within the bounded block
990   // yet so cannot handle any final CHECK-DAG yet; this is handled when going
991   // over the block again (including the last CHECK-LABEL) in normal mode.
992   if (!IsLabelScanMode) {
993     // Match "dag strings" (with mixed "not strings" if any).
994     LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable);
995     if (LastPos == StringRef::npos)
996       return StringRef::npos;
997   }
998
999   // Match itself from the last position after matching CHECK-DAG.
1000   StringRef MatchBuffer = Buffer.substr(LastPos);
1001   size_t MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
1002   if (MatchPos == StringRef::npos) {
1003     PrintCheckFailed(SM, *this, MatchBuffer, VariableTable);
1004     return StringRef::npos;
1005   }
1006   MatchPos += LastPos;
1007
1008   // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1009   // or CHECK-NOT
1010   if (!IsLabelScanMode) {
1011     StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1012
1013     // If this check is a "CHECK-NEXT", verify that the previous match was on
1014     // the previous line (i.e. that there is one newline between them).
1015     if (CheckNext(SM, SkippedRegion))
1016       return StringRef::npos;
1017
1018     // If this match had "not strings", verify that they don't exist in the
1019     // skipped region.
1020     if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
1021       return StringRef::npos;
1022   }
1023
1024   return MatchPos;
1025 }
1026
1027 bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1028   if (CheckTy != Check::CheckNext)
1029     return false;
1030
1031   // Count the number of newlines between the previous match and this one.
1032   assert(Buffer.data() !=
1033          SM.getMemoryBuffer(
1034            SM.FindBufferContainingLoc(
1035              SMLoc::getFromPointer(Buffer.data())))->getBufferStart() &&
1036          "CHECK-NEXT can't be the first check in a file");
1037
1038   unsigned NumNewLines = CountNumNewlinesBetween(Buffer);
1039
1040   if (NumNewLines == 0) {
1041     SM.PrintMessage(Loc, SourceMgr::DK_Error, Prefix +
1042                     "-NEXT: is on the same line as previous match");
1043     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
1044                     SourceMgr::DK_Note, "'next' match was here");
1045     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1046                     "previous match ended here");
1047     return true;
1048   }
1049
1050   if (NumNewLines != 1) {
1051     SM.PrintMessage(Loc, SourceMgr::DK_Error, Prefix +
1052                     "-NEXT: is not on the line after the previous match");
1053     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
1054                     SourceMgr::DK_Note, "'next' match was here");
1055     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1056                     "previous match ended here");
1057     return true;
1058   }
1059
1060   return false;
1061 }
1062
1063 bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer,
1064                            const std::vector<const Pattern *> &NotStrings,
1065                            StringMap<StringRef> &VariableTable) const {
1066   for (unsigned ChunkNo = 0, e = NotStrings.size();
1067        ChunkNo != e; ++ChunkNo) {
1068     const Pattern *Pat = NotStrings[ChunkNo];
1069     assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1070
1071     size_t MatchLen = 0;
1072     size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);
1073
1074     if (Pos == StringRef::npos) continue;
1075
1076     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos),
1077                     SourceMgr::DK_Error,
1078                     Prefix + "-NOT: string occurred!");
1079     SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note,
1080                     Prefix + "-NOT: pattern specified here");
1081     return true;
1082   }
1083
1084   return false;
1085 }
1086
1087 size_t CheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1088                              std::vector<const Pattern *> &NotStrings,
1089                              StringMap<StringRef> &VariableTable) const {
1090   if (DagNotStrings.empty())
1091     return 0;
1092
1093   size_t LastPos = 0;
1094   size_t StartPos = LastPos;
1095
1096   for (unsigned ChunkNo = 0, e = DagNotStrings.size();
1097        ChunkNo != e; ++ChunkNo) {
1098     const Pattern &Pat = DagNotStrings[ChunkNo];
1099
1100     assert((Pat.getCheckTy() == Check::CheckDAG ||
1101             Pat.getCheckTy() == Check::CheckNot) &&
1102            "Invalid CHECK-DAG or CHECK-NOT!");
1103
1104     if (Pat.getCheckTy() == Check::CheckNot) {
1105       NotStrings.push_back(&Pat);
1106       continue;
1107     }
1108
1109     assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1110
1111     size_t MatchLen = 0, MatchPos;
1112
1113     // CHECK-DAG always matches from the start.
1114     StringRef MatchBuffer = Buffer.substr(StartPos);
1115     MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
1116     // With a group of CHECK-DAGs, a single mismatching means the match on
1117     // that group of CHECK-DAGs fails immediately.
1118     if (MatchPos == StringRef::npos) {
1119       PrintCheckFailed(SM, Pat.getLoc(), Pat, MatchBuffer, VariableTable);
1120       return StringRef::npos;
1121     }
1122     // Re-calc it as the offset relative to the start of the original string.
1123     MatchPos += StartPos;
1124
1125     if (!NotStrings.empty()) {
1126       if (MatchPos < LastPos) {
1127         // Reordered?
1128         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + MatchPos),
1129                         SourceMgr::DK_Error,
1130                         Prefix + "-DAG: found a match of CHECK-DAG"
1131                         " reordering across a CHECK-NOT");
1132         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + LastPos),
1133                         SourceMgr::DK_Note,
1134                         Prefix + "-DAG: the farthest match of CHECK-DAG"
1135                         " is found here");
1136         SM.PrintMessage(NotStrings[0]->getLoc(), SourceMgr::DK_Note,
1137                         Prefix + "-NOT: the crossed pattern specified"
1138                         " here");
1139         SM.PrintMessage(Pat.getLoc(), SourceMgr::DK_Note,
1140                         Prefix + "-DAG: the reordered pattern specified"
1141                         " here");
1142         return StringRef::npos;
1143       }
1144       // All subsequent CHECK-DAGs should be matched from the farthest
1145       // position of all precedent CHECK-DAGs (including this one.)
1146       StartPos = LastPos;
1147       // If there's CHECK-NOTs between two CHECK-DAGs or from CHECK to
1148       // CHECK-DAG, verify that there's no 'not' strings occurred in that
1149       // region.
1150       StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1151       if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
1152         return StringRef::npos;
1153       // Clear "not strings".
1154       NotStrings.clear();
1155     }
1156
1157     // Update the last position with CHECK-DAG matches.
1158     LastPos = std::max(MatchPos + MatchLen, LastPos);
1159   }
1160
1161   return LastPos;
1162 }
1163
1164 // A check prefix must contain only alphanumeric, hyphens and underscores.
1165 static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1166   Regex Validator("^[a-zA-Z0-9_-]*$");
1167   return Validator.match(CheckPrefix);
1168 }
1169
1170 static bool ValidateCheckPrefixes() {
1171   StringSet<> PrefixSet;
1172
1173   for (prefix_iterator I = CheckPrefixes.begin(), E = CheckPrefixes.end();
1174        I != E; ++I) {
1175     StringRef Prefix(*I);
1176
1177     if (!PrefixSet.insert(Prefix))
1178       return false;
1179
1180     if (!ValidateCheckPrefix(Prefix))
1181       return false;
1182   }
1183
1184   return true;
1185 }
1186
1187 // I don't think there's a way to specify an initial value for cl::list,
1188 // so if nothing was specified, add the default
1189 static void AddCheckPrefixIfNeeded() {
1190   if (CheckPrefixes.empty())
1191     CheckPrefixes.push_back("CHECK");
1192 }
1193
1194 int main(int argc, char **argv) {
1195   sys::PrintStackTraceOnErrorSignal();
1196   PrettyStackTraceProgram X(argc, argv);
1197   cl::ParseCommandLineOptions(argc, argv);
1198
1199   if (!ValidateCheckPrefixes()) {
1200     errs() << "Supplied check-prefix is invalid! Prefixes must be unique and "
1201               "start with a letter and contain only alphanumeric characters, "
1202               "hyphens and underscores\n";
1203     return 2;
1204   }
1205
1206   AddCheckPrefixIfNeeded();
1207
1208   SourceMgr SM;
1209
1210   // Read the expected strings from the check file.
1211   std::vector<CheckString> CheckStrings;
1212   if (ReadCheckFile(SM, CheckStrings))
1213     return 2;
1214
1215   // Open the file to check and add it to SourceMgr.
1216   OwningPtr<MemoryBuffer> File;
1217   if (error_code ec =
1218         MemoryBuffer::getFileOrSTDIN(InputFilename, File)) {
1219     errs() << "Could not open input file '" << InputFilename << "': "
1220            << ec.message() << '\n';
1221     return 2;
1222   }
1223
1224   if (File->getBufferSize() == 0) {
1225     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
1226     return 2;
1227   }
1228
1229   // Remove duplicate spaces in the input file if requested.
1230   // Remove DOS style line endings.
1231   MemoryBuffer *F =
1232     CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
1233
1234   SM.AddNewSourceBuffer(F, SMLoc());
1235
1236   /// VariableTable - This holds all the current filecheck variables.
1237   StringMap<StringRef> VariableTable;
1238
1239   // Check that we have all of the expected strings, in order, in the input
1240   // file.
1241   StringRef Buffer = F->getBuffer();
1242
1243   bool hasError = false;
1244
1245   unsigned i = 0, j = 0, e = CheckStrings.size();
1246
1247   while (true) {
1248     StringRef CheckRegion;
1249     if (j == e) {
1250       CheckRegion = Buffer;
1251     } else {
1252       const CheckString &CheckLabelStr = CheckStrings[j];
1253       if (CheckLabelStr.CheckTy != Check::CheckLabel) {
1254         ++j;
1255         continue;
1256       }
1257
1258       // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1259       size_t MatchLabelLen = 0;
1260       size_t MatchLabelPos = CheckLabelStr.Check(SM, Buffer, true,
1261                                                  MatchLabelLen, VariableTable);
1262       if (MatchLabelPos == StringRef::npos) {
1263         hasError = true;
1264         break;
1265       }
1266
1267       CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1268       Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1269       ++j;
1270     }
1271
1272     for ( ; i != j; ++i) {
1273       const CheckString &CheckStr = CheckStrings[i];
1274
1275       // Check each string within the scanned region, including a second check
1276       // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1277       size_t MatchLen = 0;
1278       size_t MatchPos = CheckStr.Check(SM, CheckRegion, false, MatchLen,
1279                                        VariableTable);
1280
1281       if (MatchPos == StringRef::npos) {
1282         hasError = true;
1283         i = j;
1284         break;
1285       }
1286
1287       CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1288     }
1289
1290     if (j == e)
1291       break;
1292   }
1293
1294   return hasError ? 1 : 0;
1295 }