Add -exact-match option to FileCheck to allow clients to do exact matches without...
[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/Support/CommandLine.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/PrettyStackTrace.h"
23 #include "llvm/Support/Regex.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/system_error.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringMap.h"
30 #include <algorithm>
31 using namespace llvm;
32
33 static cl::opt<std::string>
34 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
35
36 static cl::opt<std::string>
37 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
38               cl::init("-"), cl::value_desc("filename"));
39
40 static cl::opt<std::string>
41 CheckPrefix("check-prefix", cl::init("CHECK"),
42             cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
43
44 static cl::opt<bool>
45 NoCanonicalizeWhiteSpace("strict-whitespace",
46               cl::desc("Do not treat all horizontal whitespace as equivalent"));
47
48 static cl::opt<bool>
49 NoRegex("exact-match",
50         cl::desc("Look for exact matches without using regular expressions"));
51
52 //===----------------------------------------------------------------------===//
53 // Pattern Handling Code.
54 //===----------------------------------------------------------------------===//
55
56 class Pattern {
57   SMLoc PatternLoc;
58
59   /// MatchEOF - When set, this pattern only matches the end of file. This is
60   /// used for trailing CHECK-NOTs.
61   bool MatchEOF;
62
63   /// FixedStr - If non-empty, this pattern is a fixed string match with the
64   /// specified fixed string.
65   StringRef FixedStr;
66
67   /// RegEx - If non-empty, this is a regex pattern.
68   std::string RegExStr;
69
70   /// VariableUses - Entries in this vector map to uses of a variable in the
71   /// pattern, e.g. "foo[[bar]]baz".  In this case, the RegExStr will contain
72   /// "foobaz" and we'll get an entry in this vector that tells us to insert the
73   /// value of bar at offset 3.
74   std::vector<std::pair<StringRef, unsigned> > VariableUses;
75
76   /// VariableDefs - Entries in this vector map to definitions of a variable in
77   /// the pattern, e.g. "foo[[bar:.*]]baz".  In this case, the RegExStr will
78   /// contain "foo(.*)baz" and VariableDefs will contain the pair "bar",1.  The
79   /// index indicates what parenthesized value captures the variable value.
80   std::vector<std::pair<StringRef, unsigned> > VariableDefs;
81
82 public:
83
84   Pattern(bool matchEOF = false) : MatchEOF(matchEOF) { }
85
86   bool ParsePattern(StringRef PatternStr, SourceMgr &SM);
87
88   /// Match - Match the pattern string against the input buffer Buffer.  This
89   /// returns the position that is matched or npos if there is no match.  If
90   /// there is a match, the size of the matched string is returned in MatchLen.
91   ///
92   /// The VariableTable StringMap provides the current values of filecheck
93   /// variables and is updated if this match defines new values.
94   size_t Match(StringRef Buffer, size_t &MatchLen,
95                StringMap<StringRef> &VariableTable) const;
96
97   /// PrintFailureInfo - Print additional information about a failure to match
98   /// involving this pattern.
99   void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
100                         const StringMap<StringRef> &VariableTable) const;
101
102 private:
103   static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
104   bool AddRegExToRegEx(StringRef RegExStr, unsigned &CurParen, SourceMgr &SM);
105
106   /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
107   /// matching this pattern at the start of \arg Buffer; a distance of zero
108   /// should correspond to a perfect match.
109   unsigned ComputeMatchDistance(StringRef Buffer,
110                                const StringMap<StringRef> &VariableTable) const;
111 };
112
113
114 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM) {
115   PatternLoc = SMLoc::getFromPointer(PatternStr.data());
116
117   // Ignore trailing whitespace.
118   while (!PatternStr.empty() &&
119          (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
120     PatternStr = PatternStr.substr(0, PatternStr.size()-1);
121
122   // Check that there is something on the line.
123   if (PatternStr.empty()) {
124     SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
125                     "found empty check string with prefix '" +
126                     CheckPrefix+":'");
127     return true;
128   }
129
130   // Check to see if this is a fixed string, or if it has regex pieces.
131   if (PatternStr.size() < 2 || NoRegex ||
132       (PatternStr.find("{{") == StringRef::npos &&
133        PatternStr.find("[[") == StringRef::npos)) {
134     FixedStr = PatternStr;
135     return false;
136   }
137
138   // Paren value #0 is for the fully matched string.  Any new parenthesized
139   // values add from there.
140   unsigned CurParen = 1;
141
142   // Otherwise, there is at least one regex piece.  Build up the regex pattern
143   // by escaping scary characters in fixed strings, building up one big regex.
144   while (!PatternStr.empty()) {
145     // RegEx matches.
146     if (PatternStr.startswith("{{")) {
147
148       // Otherwise, this is the start of a regex match.  Scan for the }}.
149       size_t End = PatternStr.find("}}");
150       if (End == StringRef::npos) {
151         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
152                         SourceMgr::DK_Error,
153                         "found start of regex string with no end '}}'");
154         return true;
155       }
156
157       // Enclose {{}} patterns in parens just like [[]] even though we're not
158       // capturing the result for any purpose.  This is required in case the
159       // expression contains an alternation like: CHECK:  abc{{x|z}}def.  We
160       // want this to turn into: "abc(x|z)def" not "abcx|zdef".
161       RegExStr += '(';
162       ++CurParen;
163
164       if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
165         return true;
166       RegExStr += ')';
167
168       PatternStr = PatternStr.substr(End+2);
169       continue;
170     }
171
172     // Named RegEx matches.  These are of two forms: [[foo:.*]] which matches .*
173     // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
174     // second form is [[foo]] which is a reference to foo.  The variable name
175     // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
176     // it.  This is to catch some common errors.
177     if (PatternStr.startswith("[[")) {
178       // Verify that it is terminated properly.
179       size_t End = PatternStr.find("]]");
180       if (End == StringRef::npos) {
181         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
182                         SourceMgr::DK_Error,
183                         "invalid named regex reference, no ]] found");
184         return true;
185       }
186
187       StringRef MatchStr = PatternStr.substr(2, End-2);
188       PatternStr = PatternStr.substr(End+2);
189
190       // Get the regex name (e.g. "foo").
191       size_t NameEnd = MatchStr.find(':');
192       StringRef Name = MatchStr.substr(0, NameEnd);
193
194       if (Name.empty()) {
195         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
196                         "invalid name in named regex: empty name");
197         return true;
198       }
199
200       // Verify that the name is well formed.
201       for (unsigned i = 0, e = Name.size(); i != e; ++i)
202         if (Name[i] != '_' && !isalnum(Name[i])) {
203           SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
204                           SourceMgr::DK_Error, "invalid name in named regex");
205           return true;
206         }
207
208       // Name can't start with a digit.
209       if (isdigit(Name[0])) {
210         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
211                         "invalid name in named regex");
212         return true;
213       }
214
215       // Handle [[foo]].
216       if (NameEnd == StringRef::npos) {
217         VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
218         continue;
219       }
220
221       // Handle [[foo:.*]].
222       VariableDefs.push_back(std::make_pair(Name, CurParen));
223       RegExStr += '(';
224       ++CurParen;
225
226       if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
227         return true;
228
229       RegExStr += ')';
230     }
231
232     // Handle fixed string matches.
233     // Find the end, which is the start of the next regex.
234     size_t FixedMatchEnd = PatternStr.find("{{");
235     FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
236     AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
237     PatternStr = PatternStr.substr(FixedMatchEnd);
238     continue;
239   }
240
241   return false;
242 }
243
244 void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
245   // Add the characters from FixedStr to the regex, escaping as needed.  This
246   // avoids "leaning toothpicks" in common patterns.
247   for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
248     switch (FixedStr[i]) {
249     // These are the special characters matched in "p_ere_exp".
250     case '(':
251     case ')':
252     case '^':
253     case '$':
254     case '|':
255     case '*':
256     case '+':
257     case '?':
258     case '.':
259     case '[':
260     case '\\':
261     case '{':
262       TheStr += '\\';
263       // FALL THROUGH.
264     default:
265       TheStr += FixedStr[i];
266       break;
267     }
268   }
269 }
270
271 bool Pattern::AddRegExToRegEx(StringRef RegexStr, unsigned &CurParen,
272                               SourceMgr &SM) {
273   Regex R(RegexStr);
274   std::string Error;
275   if (!R.isValid(Error)) {
276     SM.PrintMessage(SMLoc::getFromPointer(RegexStr.data()), SourceMgr::DK_Error,
277                     "invalid regex: " + Error);
278     return true;
279   }
280
281   RegExStr += RegexStr.str();
282   CurParen += R.getNumMatches();
283   return false;
284 }
285
286 /// Match - Match the pattern string against the input buffer Buffer.  This
287 /// returns the position that is matched or npos if there is no match.  If
288 /// there is a match, the size of the matched string is returned in MatchLen.
289 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
290                       StringMap<StringRef> &VariableTable) const {
291   // If this is the EOF pattern, match it immediately.
292   if (MatchEOF) {
293     MatchLen = 0;
294     return Buffer.size();
295   }
296
297   // If this is a fixed string pattern, just match it now.
298   if (!FixedStr.empty()) {
299     MatchLen = FixedStr.size();
300     return Buffer.find(FixedStr);
301   }
302
303   // Regex match.
304
305   // If there are variable uses, we need to create a temporary string with the
306   // actual value.
307   StringRef RegExToMatch = RegExStr;
308   std::string TmpStr;
309   if (!VariableUses.empty()) {
310     TmpStr = RegExStr;
311
312     unsigned InsertOffset = 0;
313     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
314       StringMap<StringRef>::iterator it =
315         VariableTable.find(VariableUses[i].first);
316       // If the variable is undefined, return an error.
317       if (it == VariableTable.end())
318         return StringRef::npos;
319
320       // Look up the value and escape it so that we can plop it into the regex.
321       std::string Value;
322       AddFixedStringToRegEx(it->second, Value);
323
324       // Plop it into the regex at the adjusted offset.
325       TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
326                     Value.begin(), Value.end());
327       InsertOffset += Value.size();
328     }
329
330     // Match the newly constructed regex.
331     RegExToMatch = TmpStr;
332   }
333
334
335   SmallVector<StringRef, 4> MatchInfo;
336   if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
337     return StringRef::npos;
338
339   // Successful regex match.
340   assert(!MatchInfo.empty() && "Didn't get any match");
341   StringRef FullMatch = MatchInfo[0];
342
343   // If this defines any variables, remember their values.
344   for (unsigned i = 0, e = VariableDefs.size(); i != e; ++i) {
345     assert(VariableDefs[i].second < MatchInfo.size() &&
346            "Internal paren error");
347     VariableTable[VariableDefs[i].first] = MatchInfo[VariableDefs[i].second];
348   }
349
350   MatchLen = FullMatch.size();
351   return FullMatch.data()-Buffer.data();
352 }
353
354 unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
355                               const StringMap<StringRef> &VariableTable) const {
356   // Just compute the number of matching characters. For regular expressions, we
357   // just compare against the regex itself and hope for the best.
358   //
359   // FIXME: One easy improvement here is have the regex lib generate a single
360   // example regular expression which matches, and use that as the example
361   // string.
362   StringRef ExampleString(FixedStr);
363   if (ExampleString.empty())
364     ExampleString = RegExStr;
365
366   // Only compare up to the first line in the buffer, or the string size.
367   StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
368   BufferPrefix = BufferPrefix.split('\n').first;
369   return BufferPrefix.edit_distance(ExampleString);
370 }
371
372 void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
373                                const StringMap<StringRef> &VariableTable) const{
374   // If this was a regular expression using variables, print the current
375   // variable values.
376   if (!VariableUses.empty()) {
377     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
378       StringRef Var = VariableUses[i].first;
379       StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
380       SmallString<256> Msg;
381       raw_svector_ostream OS(Msg);
382
383       // Check for undefined variable references.
384       if (it == VariableTable.end()) {
385         OS << "uses undefined variable \"";
386         OS.write_escaped(Var) << "\"";;
387       } else {
388         OS << "with variable \"";
389         OS.write_escaped(Var) << "\" equal to \"";
390         OS.write_escaped(it->second) << "\"";
391       }
392
393       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
394                       OS.str());
395     }
396   }
397
398   // Attempt to find the closest/best fuzzy match.  Usually an error happens
399   // because some string in the output didn't exactly match. In these cases, we
400   // would like to show the user a best guess at what "should have" matched, to
401   // save them having to actually check the input manually.
402   size_t NumLinesForward = 0;
403   size_t Best = StringRef::npos;
404   double BestQuality = 0;
405
406   // Use an arbitrary 4k limit on how far we will search.
407   for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
408     if (Buffer[i] == '\n')
409       ++NumLinesForward;
410
411     // Patterns have leading whitespace stripped, so skip whitespace when
412     // looking for something which looks like a pattern.
413     if (Buffer[i] == ' ' || Buffer[i] == '\t')
414       continue;
415
416     // Compute the "quality" of this match as an arbitrary combination of the
417     // match distance and the number of lines skipped to get to this match.
418     unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
419     double Quality = Distance + (NumLinesForward / 100.);
420
421     if (Quality < BestQuality || Best == StringRef::npos) {
422       Best = i;
423       BestQuality = Quality;
424     }
425   }
426
427   // Print the "possible intended match here" line if we found something
428   // reasonable and not equal to what we showed in the "scanning from here"
429   // line.
430   if (Best && Best != StringRef::npos && BestQuality < 50) {
431       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
432                       SourceMgr::DK_Note, "possible intended match here");
433
434     // FIXME: If we wanted to be really friendly we would show why the match
435     // failed, as it can be hard to spot simple one character differences.
436   }
437 }
438
439 //===----------------------------------------------------------------------===//
440 // Check Strings.
441 //===----------------------------------------------------------------------===//
442
443 /// CheckString - This is a check that we found in the input file.
444 struct CheckString {
445   /// Pat - The pattern to match.
446   Pattern Pat;
447
448   /// Loc - The location in the match file that the check string was specified.
449   SMLoc Loc;
450
451   /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
452   /// to a CHECK: directive.
453   bool IsCheckNext;
454
455   /// NotStrings - These are all of the strings that are disallowed from
456   /// occurring between this match string and the previous one (or start of
457   /// file).
458   std::vector<std::pair<SMLoc, Pattern> > NotStrings;
459
460   CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
461     : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
462 };
463
464 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
465 /// memory buffer, free it, and return a new one.
466 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
467   SmallString<128> NewFile;
468   NewFile.reserve(MB->getBufferSize());
469
470   for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
471        Ptr != End; ++Ptr) {
472     // Eliminate trailing dosish \r.
473     if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
474       continue;
475     }
476
477     // If C is not a horizontal whitespace, skip it.
478     if (*Ptr != ' ' && *Ptr != '\t') {
479       NewFile.push_back(*Ptr);
480       continue;
481     }
482
483     // Otherwise, add one space and advance over neighboring space.
484     NewFile.push_back(' ');
485     while (Ptr+1 != End &&
486            (Ptr[1] == ' ' || Ptr[1] == '\t'))
487       ++Ptr;
488   }
489
490   // Free the old buffer and return a new one.
491   MemoryBuffer *MB2 =
492     MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
493
494   delete MB;
495   return MB2;
496 }
497
498
499 /// ReadCheckFile - Read the check file, which specifies the sequence of
500 /// expected strings.  The strings are added to the CheckStrings vector.
501 static bool ReadCheckFile(SourceMgr &SM,
502                           std::vector<CheckString> &CheckStrings) {
503   // Open the check file, and tell SourceMgr about it.
504   OwningPtr<MemoryBuffer> File;
505   if (error_code ec =
506         MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) {
507     errs() << "Could not open check file '" << CheckFilename << "': "
508            << ec.message() << '\n';
509     return true;
510   }
511   MemoryBuffer *F = File.take();
512
513   // If we want to canonicalize whitespace, strip excess whitespace from the
514   // buffer containing the CHECK lines.
515   if (!NoCanonicalizeWhiteSpace)
516     F = CanonicalizeInputFile(F);
517
518   SM.AddNewSourceBuffer(F, SMLoc());
519
520   // Find all instances of CheckPrefix followed by : in the file.
521   StringRef Buffer = F->getBuffer();
522
523   std::vector<std::pair<SMLoc, Pattern> > NotMatches;
524
525   while (1) {
526     // See if Prefix occurs in the memory buffer.
527     Buffer = Buffer.substr(Buffer.find(CheckPrefix));
528
529     // If we didn't find a match, we're done.
530     if (Buffer.empty())
531       break;
532
533     const char *CheckPrefixStart = Buffer.data();
534
535     // When we find a check prefix, keep track of whether we find CHECK: or
536     // CHECK-NEXT:
537     bool IsCheckNext = false, IsCheckNot = false;
538
539     // Verify that the : is present after the prefix.
540     if (Buffer[CheckPrefix.size()] == ':') {
541       Buffer = Buffer.substr(CheckPrefix.size()+1);
542     } else if (Buffer.size() > CheckPrefix.size()+6 &&
543                memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
544       Buffer = Buffer.substr(CheckPrefix.size()+7);
545       IsCheckNext = true;
546     } else if (Buffer.size() > CheckPrefix.size()+5 &&
547                memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
548       Buffer = Buffer.substr(CheckPrefix.size()+6);
549       IsCheckNot = true;
550     } else {
551       Buffer = Buffer.substr(1);
552       continue;
553     }
554
555     // Okay, we found the prefix, yay.  Remember the rest of the line, but
556     // ignore leading and trailing whitespace.
557     Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
558
559     // Scan ahead to the end of line.
560     size_t EOL = Buffer.find_first_of("\n\r");
561
562     // Remember the location of the start of the pattern, for diagnostics.
563     SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
564
565     // Parse the pattern.
566     Pattern P;
567     if (P.ParsePattern(Buffer.substr(0, EOL), SM))
568       return true;
569
570     Buffer = Buffer.substr(EOL);
571
572
573     // Verify that CHECK-NEXT lines have at least one CHECK line before them.
574     if (IsCheckNext && CheckStrings.empty()) {
575       SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
576                       SourceMgr::DK_Error,
577                       "found '"+CheckPrefix+"-NEXT:' without previous '"+
578                       CheckPrefix+ ": line");
579       return true;
580     }
581
582     // Handle CHECK-NOT.
583     if (IsCheckNot) {
584       NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
585                                           P));
586       continue;
587     }
588
589
590     // Okay, add the string we captured to the output vector and move on.
591     CheckStrings.push_back(CheckString(P,
592                                        PatternLoc,
593                                        IsCheckNext));
594     std::swap(NotMatches, CheckStrings.back().NotStrings);
595   }
596
597   // Add an EOF pattern for any trailing CHECK-NOTs.
598   if (!NotMatches.empty()) {
599     CheckStrings.push_back(CheckString(Pattern(true),
600                                        SMLoc::getFromPointer(Buffer.data()),
601                                        false));
602     std::swap(NotMatches, CheckStrings.back().NotStrings);
603   }
604
605   if (CheckStrings.empty()) {
606     errs() << "error: no check strings found with prefix '" << CheckPrefix
607            << ":'\n";
608     return true;
609   }
610
611   return false;
612 }
613
614 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
615                              StringRef Buffer,
616                              StringMap<StringRef> &VariableTable) {
617   // Otherwise, we have an error, emit an error message.
618   SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
619                   "expected string not found in input");
620
621   // Print the "scanning from here" line.  If the current position is at the
622   // end of a line, advance to the start of the next line.
623   Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
624
625   SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
626                   "scanning from here");
627
628   // Allow the pattern to print additional information if desired.
629   CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable);
630 }
631
632 /// CountNumNewlinesBetween - Count the number of newlines in the specified
633 /// range.
634 static unsigned CountNumNewlinesBetween(StringRef Range) {
635   unsigned NumNewLines = 0;
636   while (1) {
637     // Scan for newline.
638     Range = Range.substr(Range.find_first_of("\n\r"));
639     if (Range.empty()) return NumNewLines;
640
641     ++NumNewLines;
642
643     // Handle \n\r and \r\n as a single newline.
644     if (Range.size() > 1 &&
645         (Range[1] == '\n' || Range[1] == '\r') &&
646         (Range[0] != Range[1]))
647       Range = Range.substr(1);
648     Range = Range.substr(1);
649   }
650 }
651
652 int main(int argc, char **argv) {
653   sys::PrintStackTraceOnErrorSignal();
654   PrettyStackTraceProgram X(argc, argv);
655   cl::ParseCommandLineOptions(argc, argv);
656
657   SourceMgr SM;
658
659   // Read the expected strings from the check file.
660   std::vector<CheckString> CheckStrings;
661   if (ReadCheckFile(SM, CheckStrings))
662     return 2;
663
664   // Open the file to check and add it to SourceMgr.
665   OwningPtr<MemoryBuffer> File;
666   if (error_code ec =
667         MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
668     errs() << "Could not open input file '" << InputFilename << "': "
669            << ec.message() << '\n';
670     return true;
671   }
672   MemoryBuffer *F = File.take();
673
674   if (F->getBufferSize() == 0) {
675     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
676     return 1;
677   }
678   
679   // Remove duplicate spaces in the input file if requested.
680   if (!NoCanonicalizeWhiteSpace)
681     F = CanonicalizeInputFile(F);
682
683   SM.AddNewSourceBuffer(F, SMLoc());
684
685   /// VariableTable - This holds all the current filecheck variables.
686   StringMap<StringRef> VariableTable;
687
688   // Check that we have all of the expected strings, in order, in the input
689   // file.
690   StringRef Buffer = F->getBuffer();
691
692   const char *LastMatch = Buffer.data();
693
694   for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
695     const CheckString &CheckStr = CheckStrings[StrNo];
696
697     StringRef SearchFrom = Buffer;
698
699     // Find StrNo in the file.
700     size_t MatchLen = 0;
701     size_t MatchPos = CheckStr.Pat.Match(Buffer, MatchLen, VariableTable);
702     Buffer = Buffer.substr(MatchPos);
703
704     // If we didn't find a match, reject the input.
705     if (MatchPos == StringRef::npos) {
706       PrintCheckFailed(SM, CheckStr, SearchFrom, VariableTable);
707       return 1;
708     }
709
710     StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
711
712     // If this check is a "CHECK-NEXT", verify that the previous match was on
713     // the previous line (i.e. that there is one newline between them).
714     if (CheckStr.IsCheckNext) {
715       // Count the number of newlines between the previous match and this one.
716       assert(LastMatch != F->getBufferStart() &&
717              "CHECK-NEXT can't be the first check in a file");
718
719       unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
720       if (NumNewLines == 0) {
721         SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
722                     CheckPrefix+"-NEXT: is on the same line as previous match");
723         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
724                         SourceMgr::DK_Note, "'next' match was here");
725         SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
726                         "previous match was here");
727         return 1;
728       }
729
730       if (NumNewLines != 1) {
731         SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+
732                         "-NEXT: is not on the line after the previous match");
733         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
734                         SourceMgr::DK_Note, "'next' match was here");
735         SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
736                         "previous match was here");
737         return 1;
738       }
739     }
740
741     // If this match had "not strings", verify that they don't exist in the
742     // skipped region.
743     for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size();
744          ChunkNo != e; ++ChunkNo) {
745       size_t MatchLen = 0;
746       size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion,
747                                                              MatchLen,
748                                                              VariableTable);
749       if (Pos == StringRef::npos) continue;
750
751       SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos), SourceMgr::DK_Error,
752                       CheckPrefix+"-NOT: string occurred!");
753       SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first, SourceMgr::DK_Note,
754                       CheckPrefix+"-NOT: pattern specified here");
755       return 1;
756     }
757
758
759     // Otherwise, everything is good.  Step over the matched text and remember
760     // the position after the match as the end of the last match.
761     Buffer = Buffer.substr(MatchLen);
762     LastMatch = Buffer.data();
763   }
764
765   return 0;
766 }