Add missing #include's to cctype when using isdigit/alpha/etc.
[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/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"
31 #include <algorithm>
32 #include <cctype>
33 #include <map>
34 #include <string>
35 #include <vector>
36 using namespace llvm;
37
38 static cl::opt<std::string>
39 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
40
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"));
44
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')"));
48
49 static cl::opt<bool>
50 NoCanonicalizeWhiteSpace("strict-whitespace",
51               cl::desc("Do not treat all horizontal whitespace as equivalent"));
52
53 //===----------------------------------------------------------------------===//
54 // Pattern Handling Code.
55 //===----------------------------------------------------------------------===//
56
57 namespace Check {
58   enum CheckType {
59     CheckNone = 0,
60     CheckPlain,
61     CheckNext,
62     CheckNot,
63     CheckDAG,
64     CheckLabel,
65
66     /// MatchEOF - When set, this pattern only matches the end of file. This is
67     /// used for trailing CHECK-NOTs.
68     CheckEOF
69   };
70 }
71
72 class Pattern {
73   SMLoc PatternLoc;
74
75   Check::CheckType CheckTy;
76
77   /// FixedStr - If non-empty, this pattern is a fixed string match with the
78   /// specified fixed string.
79   StringRef FixedStr;
80
81   /// RegEx - If non-empty, this is a regex pattern.
82   std::string RegExStr;
83
84   /// \brief Contains the number of line this pattern is in.
85   unsigned LineNumber;
86
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;
92
93   /// VariableDefs - Maps definitions of variables to their parenthesized
94   /// capture numbers.
95   /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
96   std::map<StringRef, unsigned> VariableDefs;
97
98 public:
99
100   Pattern(Check::CheckType Ty)
101     : CheckTy(Ty) { }
102
103   /// getLoc - Return the location in source code.
104   SMLoc getLoc() const { return PatternLoc; }
105
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);
111
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.
115   ///
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;
120
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;
125
126   bool hasVariable() const { return !(VariableUses.empty() &&
127                                       VariableDefs.empty()); }
128
129   Check::CheckType getCheckTy() const { return CheckTy; }
130
131 private:
132   static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
133   bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
134   void AddBackrefToRegEx(unsigned BackrefNum);
135
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;
141
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;
145
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
150   /// found.
151   size_t FindRegexVarEnd(StringRef Str);
152 };
153
154
155 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
156                            unsigned LineNumber) {
157   this->LineNumber = LineNumber;
158   PatternLoc = SMLoc::getFromPointer(PatternStr.data());
159
160   // Ignore trailing whitespace.
161   while (!PatternStr.empty() &&
162          (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
163     PatternStr = PatternStr.substr(0, PatternStr.size()-1);
164
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 '" +
169                     CheckPrefix+":'");
170     return true;
171   }
172
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;
178     return false;
179   }
180
181   // Paren value #0 is for the fully matched string.  Any new parenthesized
182   // values add from there.
183   unsigned CurParen = 1;
184
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()) {
188     // RegEx matches.
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()),
194                         SourceMgr::DK_Error,
195                         "found start of regex string with no end '}}'");
196         return true;
197       }
198
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".
203       RegExStr += '(';
204       ++CurParen;
205
206       if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
207         return true;
208       RegExStr += ')';
209
210       PatternStr = PatternStr.substr(End+2);
211       continue;
212     }
213
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));
223
224       if (End == StringRef::npos) {
225         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
226                         SourceMgr::DK_Error,
227                         "invalid named regex reference, no ]] found");
228         return true;
229       }
230
231       StringRef MatchStr = PatternStr.substr(2, End);
232       PatternStr = PatternStr.substr(End+4);
233
234       // Get the regex name (e.g. "foo").
235       size_t NameEnd = MatchStr.find(':');
236       StringRef Name = MatchStr.substr(0, NameEnd);
237
238       if (Name.empty()) {
239         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
240                         "invalid name in named regex: empty name");
241         return true;
242       }
243
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()),
252                             SourceMgr::DK_Error,
253                             "invalid name in named regex definition");
254             return true;
255           }
256           IsExpression = true;
257           continue;
258         }
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");
263           return true;
264         }
265       }
266
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");
271         return true;
272       }
273
274       // Handle [[foo]].
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()),
282                             SourceMgr::DK_Error,
283                             "Can't back-reference more than 9 variables");
284             return true;
285           }
286           AddBackrefToRegEx(VarParenNum);
287         } else {
288           VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
289         }
290         continue;
291       }
292
293       // Handle [[foo:.*]].
294       VariableDefs[Name] = CurParen;
295       RegExStr += '(';
296       ++CurParen;
297
298       if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
299         return true;
300
301       RegExStr += ')';
302     }
303
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);
310   }
311
312   return false;
313 }
314
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".
321     case '(':
322     case ')':
323     case '^':
324     case '$':
325     case '|':
326     case '*':
327     case '+':
328     case '?':
329     case '.':
330     case '[':
331     case '\\':
332     case '{':
333       TheStr += '\\';
334       // FALL THROUGH.
335     default:
336       TheStr += FixedStr[i];
337       break;
338     }
339   }
340 }
341
342 bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
343                               SourceMgr &SM) {
344   Regex R(RS);
345   std::string Error;
346   if (!R.isValid(Error)) {
347     SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
348                     "invalid regex: " + Error);
349     return true;
350   }
351
352   RegExStr += RS.str();
353   CurParen += R.getNumMatches();
354   return false;
355 }
356
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);
361   RegExStr += Backref;
362 }
363
364 bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
365   // The only supported expression is @LINE([\+-]\d+)?
366   if (!Expr.startswith("@LINE"))
367     return false;
368   Expr = Expr.substr(StringRef("@LINE").size());
369   int Offset = 0;
370   if (!Expr.empty()) {
371     if (Expr[0] == '+')
372       Expr = Expr.substr(1);
373     else if (Expr[0] != '-')
374       return false;
375     if (Expr.getAsInteger(10, Offset))
376       return false;
377   }
378   Value = llvm::itostr(LineNumber + Offset);
379   return true;
380 }
381
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) {
389     MatchLen = 0;
390     return Buffer.size();
391   }
392
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);
397   }
398
399   // Regex match.
400
401   // If there are variable uses, we need to create a temporary string with the
402   // actual value.
403   StringRef RegExToMatch = RegExStr;
404   std::string TmpStr;
405   if (!VariableUses.empty()) {
406     TmpStr = RegExStr;
407
408     unsigned InsertOffset = 0;
409     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
410       std::string Value;
411
412       if (VariableUses[i].first[0] == '@') {
413         if (!EvaluateExpression(VariableUses[i].first, Value))
414           return StringRef::npos;
415       } else {
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;
421
422         // Look up the value and escape it so that we can plop it into the regex.
423         AddFixedStringToRegEx(it->second, Value);
424       }
425
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();
430     }
431
432     // Match the newly constructed regex.
433     RegExToMatch = TmpStr;
434   }
435
436
437   SmallVector<StringRef, 4> MatchInfo;
438   if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
439     return StringRef::npos;
440
441   // Successful regex match.
442   assert(!MatchInfo.empty() && "Didn't get any match");
443   StringRef FullMatch = MatchInfo[0];
444
445   // If this defines any variables, remember their values.
446   for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
447                                                      E = VariableDefs.end();
448        I != E; ++I) {
449     assert(I->second < MatchInfo.size() && "Internal paren error");
450     VariableTable[I->first] = MatchInfo[I->second];
451   }
452
453   MatchLen = FullMatch.size();
454   return FullMatch.data()-Buffer.data();
455 }
456
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.
461   //
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
464   // string.
465   StringRef ExampleString(FixedStr);
466   if (ExampleString.empty())
467     ExampleString = RegExStr;
468
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);
473 }
474
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
478   // variable values.
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;
484       if (Var[0] == '@') {
485         std::string Value;
486         if (EvaluateExpression(Var, Value)) {
487           OS << "with expression \"";
488           OS.write_escaped(Var) << "\" equal to \"";
489           OS.write_escaped(Value) << "\"";
490         } else {
491           OS << "uses incorrect expression \"";
492           OS.write_escaped(Var) << "\"";
493         }
494       } else {
495         StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
496
497         // Check for undefined variable references.
498         if (it == VariableTable.end()) {
499           OS << "uses undefined variable \"";
500           OS.write_escaped(Var) << "\"";
501         } else {
502           OS << "with variable \"";
503           OS.write_escaped(Var) << "\" equal to \"";
504           OS.write_escaped(it->second) << "\"";
505         }
506       }
507
508       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
509                       OS.str());
510     }
511   }
512
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;
520
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')
524       ++NumLinesForward;
525
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')
529       continue;
530
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.);
535
536     if (Quality < BestQuality || Best == StringRef::npos) {
537       Best = i;
538       BestQuality = Quality;
539     }
540   }
541
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"
544   // line.
545   if (Best && Best != StringRef::npos && BestQuality < 50) {
546       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
547                       SourceMgr::DK_Note, "possible intended match here");
548
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.
551   }
552 }
553
554 size_t Pattern::FindRegexVarEnd(StringRef Str) {
555   // Offset keeps track of the current offset within the input Str
556   size_t Offset = 0;
557   // [...] Nesting depth
558   size_t BracketDepth = 0;
559
560   while (!Str.empty()) {
561     if (Str.startswith("]]") && BracketDepth == 0)
562       return Offset;
563     if (Str[0] == '\\') {
564       // Backslash escapes the next char within regexes, so skip them both.
565       Str = Str.substr(2);
566       Offset += 2;
567     } else {
568       switch (Str[0]) {
569         default:
570           break;
571         case '[':
572           BracketDepth++;
573           break;
574         case ']':
575           assert(BracketDepth > 0 && "Invalid regex");
576           BracketDepth--;
577           break;
578       }
579       Str = Str.substr(1);
580       Offset++;
581     }
582   }
583
584   return StringRef::npos;
585 }
586
587
588 //===----------------------------------------------------------------------===//
589 // Check Strings.
590 //===----------------------------------------------------------------------===//
591
592 /// CheckString - This is a check that we found in the input file.
593 struct CheckString {
594   /// Pat - The pattern to match.
595   Pattern Pat;
596
597   /// Loc - The location in the match file that the check string was specified.
598   SMLoc Loc;
599
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;
603
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
606   /// file).
607   std::vector<Pattern> DagNotStrings;
608
609   CheckString(const Pattern &P, SMLoc L, Check::CheckType Ty)
610     : Pat(P), Loc(L), CheckTy(Ty) {}
611
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;
615
616   /// CheckNext - Verify there is a single line in the given buffer.
617   bool CheckNext(const SourceMgr &SM, StringRef Buffer) const;
618
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;
623
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;
628 };
629
630 /// Canonicalize whitespaces in the input file. Line endings are replaced
631 /// with UNIX-style '\n'.
632 ///
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());
639
640   for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
641        Ptr != End; ++Ptr) {
642     // Eliminate trailing dosish \r.
643     if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
644       continue;
645     }
646
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);
651       continue;
652     }
653
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'))
658       ++Ptr;
659   }
660
661   // Free the old buffer and return a new one.
662   MemoryBuffer *MB2 =
663     MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
664
665   delete MB;
666   return MB2;
667 }
668
669 static bool IsPartOfWord(char c) {
670   return (isalnum(c) || c == '-' || c == '_');
671 }
672
673 static Check::CheckType FindCheckType(StringRef &Buffer, StringRef Prefix) {
674   char NextChar = Buffer[Prefix.size()];
675
676   // Verify that the : is present after the prefix.
677   if (NextChar == ':') {
678     Buffer = Buffer.substr(Prefix.size() + 1);
679     return Check::CheckPlain;
680   }
681
682   if (NextChar != '-') {
683     Buffer = Buffer.drop_front(1);
684     return Check::CheckNone;
685   }
686
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;
691   }
692
693   if (Rest.startswith("NOT:")) {
694     Buffer = Rest.drop_front(sizeof("NOT:") - 1);
695     return Check::CheckNot;
696   }
697
698   if (Rest.startswith("DAG:")) {
699     Buffer = Rest.drop_front(sizeof("DAG:") - 1);
700     return Check::CheckDAG;
701   }
702
703   if (Rest.startswith("LABEL:")) {
704     Buffer = Rest.drop_front(sizeof("LABEL:") - 1);
705     return Check::CheckLabel;
706   }
707
708   Buffer = Buffer.drop_front(1);
709   return Check::CheckNone;
710 }
711
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;
718   if (error_code ec =
719         MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) {
720     errs() << "Could not open check file '" << CheckFilename << "': "
721            << ec.message() << '\n';
722     return true;
723   }
724
725   // If we want to canonicalize whitespace, strip excess whitespace from the
726   // buffer containing the CHECK lines. Remove DOS style line endings.
727   MemoryBuffer *F =
728     CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
729
730   SM.AddNewSourceBuffer(F, SMLoc());
731
732   // Find all instances of CheckPrefix followed by : in the file.
733   StringRef Buffer = F->getBuffer();
734   std::vector<Pattern> DagNotMatches;
735
736   // LineNumber keeps track of the line on which CheckPrefix instances are
737   // found.
738   unsigned LineNumber = 1;
739
740   while (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)
745       break;
746
747     LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
748
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));
752
753     const char *CheckPrefixStart = Buffer.data() + (PrefixLoc == 0 ? 0 : 1);
754
755     // Make sure we have actually found our prefix, and not a word containing
756     // our prefix.
757     if (PrefixLoc != 0 && IsPartOfWord(Buffer[0])) {
758       Buffer = Buffer.substr(CheckPrefix.size());
759       continue;
760     }
761
762     // When we find a check prefix, keep track of what kind of type of CHECK we
763     // have.
764     Check::CheckType CheckTy = FindCheckType(Buffer, CheckPrefix);
765     if (CheckTy == Check::CheckNone)
766       continue;
767
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"));
771
772     // Scan ahead to the end of line.
773     size_t EOL = Buffer.find_first_of("\n\r");
774
775     // Remember the location of the start of the pattern, for diagnostics.
776     SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
777
778     // Parse the pattern.
779     Pattern P(CheckTy);
780     if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
781       return true;
782
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),
786                       SourceMgr::DK_Error,
787                       "found '"+CheckPrefix+"-LABEL:' with variable definition"
788                       " or use");
789       return true;
790     }
791
792     Buffer = Buffer.substr(EOL);
793
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),
797                       SourceMgr::DK_Error,
798                       "found '"+CheckPrefix+"-NEXT:' without previous '"+
799                       CheckPrefix+ ": line");
800       return true;
801     }
802
803     // Handle CHECK-DAG/-NOT.
804     if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
805       DagNotMatches.push_back(P);
806       continue;
807     }
808
809     // Okay, add the string we captured to the output vector and move on.
810     CheckStrings.push_back(CheckString(P,
811                                        PatternLoc,
812                                        CheckTy));
813     std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
814   }
815
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()),
820                                        Check::CheckEOF));
821     std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
822   }
823
824   if (CheckStrings.empty()) {
825     errs() << "error: no check strings found with prefix '" << CheckPrefix
826            << ":'\n";
827     return true;
828   }
829
830   return false;
831 }
832
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");
839
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"));
843
844   SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
845                   "scanning from here");
846
847   // Allow the pattern to print additional information if desired.
848   Pat.PrintFailureInfo(SM, Buffer, VariableTable);
849 }
850
851 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
852                              StringRef Buffer,
853                              StringMap<StringRef> &VariableTable) {
854   PrintCheckFailed(SM, CheckStr.Loc, CheckStr.Pat, Buffer, VariableTable);
855 }
856
857 /// CountNumNewlinesBetween - Count the number of newlines in the specified
858 /// range.
859 static unsigned CountNumNewlinesBetween(StringRef Range) {
860   unsigned NumNewLines = 0;
861   while (1) {
862     // Scan for newline.
863     Range = Range.substr(Range.find_first_of("\n\r"));
864     if (Range.empty()) return NumNewLines;
865
866     ++NumNewLines;
867
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);
874   }
875 }
876
877 size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer,
878                           bool IsLabelScanMode, size_t &MatchLen,
879                           StringMap<StringRef> &VariableTable) const {
880   size_t LastPos = 0;
881   std::vector<const Pattern *> NotStrings;
882
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;
892   }
893
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;
900   }
901   MatchPos += LastPos;
902
903   // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
904   // or CHECK-NOT
905   if (!IsLabelScanMode) {
906     StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
907
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;
912
913     // If this match had "not strings", verify that they don't exist in the
914     // skipped region.
915     if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
916       return StringRef::npos;
917   }
918
919   return MatchPos;
920 }
921
922 bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
923   if (CheckTy != Check::CheckNext)
924     return false;
925
926   // Count the number of newlines between the previous match and this one.
927   assert(Buffer.data() !=
928          SM.getMemoryBuffer(
929            SM.FindBufferContainingLoc(
930              SMLoc::getFromPointer(Buffer.data())))->getBufferStart() &&
931          "CHECK-NEXT can't be the first check in a file");
932
933   unsigned NumNewLines = CountNumNewlinesBetween(Buffer);
934
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");
942     return true;
943   }
944
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");
952     return true;
953   }
954
955   return false;
956 }
957
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!");
965
966     size_t MatchLen = 0;
967     size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);
968
969     if (Pos == StringRef::npos) continue;
970
971     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos),
972                     SourceMgr::DK_Error,
973                     CheckPrefix+"-NOT: string occurred!");
974     SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note,
975                     CheckPrefix+"-NOT: pattern specified here");
976     return true;
977   }
978
979   return false;
980 }
981
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())
986     return 0;
987
988   size_t LastPos = 0;
989   size_t StartPos = LastPos;
990
991   for (unsigned ChunkNo = 0, e = DagNotStrings.size();
992        ChunkNo != e; ++ChunkNo) {
993     const Pattern &Pat = DagNotStrings[ChunkNo];
994
995     assert((Pat.getCheckTy() == Check::CheckDAG ||
996             Pat.getCheckTy() == Check::CheckNot) &&
997            "Invalid CHECK-DAG or CHECK-NOT!");
998
999     if (Pat.getCheckTy() == Check::CheckNot) {
1000       NotStrings.push_back(&Pat);
1001       continue;
1002     }
1003
1004     assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1005
1006     size_t MatchLen = 0, MatchPos;
1007
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;
1016     }
1017     // Re-calc it as the offset relative to the start of the original string.
1018     MatchPos += StartPos;
1019
1020     if (!NotStrings.empty()) {
1021       if (MatchPos < LastPos) {
1022         // Reordered?
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),
1028                         SourceMgr::DK_Note,
1029                         CheckPrefix+"-DAG: the farthest match of CHECK-DAG"
1030                         " is found here");
1031         SM.PrintMessage(NotStrings[0]->getLoc(), SourceMgr::DK_Note,
1032                         CheckPrefix+"-NOT: the crossed pattern specified"
1033                         " here");
1034         SM.PrintMessage(Pat.getLoc(), SourceMgr::DK_Note,
1035                         CheckPrefix+"-DAG: the reordered pattern specified"
1036                         " here");
1037         return StringRef::npos;
1038       }
1039       // All subsequent CHECK-DAGs should be matched from the farthest
1040       // position of all precedent CHECK-DAGs (including this one.)
1041       StartPos = LastPos;
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
1044       // region.
1045       StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1046       if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
1047         return StringRef::npos;
1048       // Clear "not strings".
1049       NotStrings.clear();
1050     }
1051
1052     // Update the last position with CHECK-DAG matches.
1053     LastPos = std::max(MatchPos + MatchLen, LastPos);
1054   }
1055
1056   return LastPos;
1057 }
1058
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);
1063 }
1064
1065 int main(int argc, char **argv) {
1066   sys::PrintStackTraceOnErrorSignal();
1067   PrettyStackTraceProgram X(argc, argv);
1068   cl::ParseCommandLineOptions(argc, argv);
1069
1070   if (!ValidateCheckPrefix()) {
1071     errs() << "Supplied check-prefix is invalid! Prefixes must start with a "
1072               "letter and contain only alphanumeric characters, hyphens and "
1073               "underscores\n";
1074     return 2;
1075   }
1076
1077   SourceMgr SM;
1078
1079   // Read the expected strings from the check file.
1080   std::vector<CheckString> CheckStrings;
1081   if (ReadCheckFile(SM, CheckStrings))
1082     return 2;
1083
1084   // Open the file to check and add it to SourceMgr.
1085   OwningPtr<MemoryBuffer> File;
1086   if (error_code ec =
1087         MemoryBuffer::getFileOrSTDIN(InputFilename, File)) {
1088     errs() << "Could not open input file '" << InputFilename << "': "
1089            << ec.message() << '\n';
1090     return 2;
1091   }
1092
1093   if (File->getBufferSize() == 0) {
1094     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
1095     return 2;
1096   }
1097
1098   // Remove duplicate spaces in the input file if requested.
1099   // Remove DOS style line endings.
1100   MemoryBuffer *F =
1101     CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
1102
1103   SM.AddNewSourceBuffer(F, SMLoc());
1104
1105   /// VariableTable - This holds all the current filecheck variables.
1106   StringMap<StringRef> VariableTable;
1107
1108   // Check that we have all of the expected strings, in order, in the input
1109   // file.
1110   StringRef Buffer = F->getBuffer();
1111
1112   bool hasError = false;
1113
1114   unsigned i = 0, j = 0, e = CheckStrings.size();
1115
1116   while (true) {
1117     StringRef CheckRegion;
1118     if (j == e) {
1119       CheckRegion = Buffer;
1120     } else {
1121       const CheckString &CheckLabelStr = CheckStrings[j];
1122       if (CheckLabelStr.CheckTy != Check::CheckLabel) {
1123         ++j;
1124         continue;
1125       }
1126
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) {
1132         hasError = true;
1133         break;
1134       }
1135
1136       CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1137       Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1138       ++j;
1139     }
1140
1141     for ( ; i != j; ++i) {
1142       const CheckString &CheckStr = CheckStrings[i];
1143
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,
1148                                        VariableTable);
1149
1150       if (MatchPos == StringRef::npos) {
1151         hasError = true;
1152         i = j;
1153         break;
1154       }
1155
1156       CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1157     }
1158
1159     if (j == e)
1160       break;
1161   }
1162
1163   return hasError ? 1 : 0;
1164 }