remove support for "NoSub" from regex. It seems like a minor optimization
[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/Support/CommandLine.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/PrettyStackTrace.h"
22 #include "llvm/Support/Regex.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/System/Signals.h"
26 using namespace llvm;
27
28 static cl::opt<std::string>
29 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
30
31 static cl::opt<std::string>
32 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
33               cl::init("-"), cl::value_desc("filename"));
34
35 static cl::opt<std::string>
36 CheckPrefix("check-prefix", cl::init("CHECK"),
37             cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
38
39 static cl::opt<bool>
40 NoCanonicalizeWhiteSpace("strict-whitespace",
41               cl::desc("Do not treat all horizontal whitespace as equivalent"));
42
43 //===----------------------------------------------------------------------===//
44 // Pattern Handling Code.
45 //===----------------------------------------------------------------------===//
46
47 class Pattern {
48   SourceMgr *SM;
49   SMLoc PatternLoc;
50   
51   /// FixedStr - If non-empty, this pattern is a fixed string match with the
52   /// specified fixed string.
53   StringRef FixedStr;
54   
55   /// RegEx - If non-empty, this is a regex pattern.
56   std::string RegExStr;
57 public:
58   
59   Pattern() { }
60   
61   bool ParsePattern(StringRef PatternStr, SourceMgr &SM);
62   
63   /// Match - Match the pattern string against the input buffer Buffer.  This
64   /// returns the position that is matched or npos if there is no match.  If
65   /// there is a match, the size of the matched string is returned in MatchLen.
66   size_t Match(StringRef Buffer, size_t &MatchLen) const;
67   
68 private:
69   void AddFixedStringToRegEx(StringRef FixedStr);
70 };
71
72 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM) {
73   this->SM = &SM;
74   PatternLoc = SMLoc::getFromPointer(PatternStr.data());
75   
76   // Ignore trailing whitespace.
77   while (!PatternStr.empty() &&
78          (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
79     PatternStr = PatternStr.substr(0, PatternStr.size()-1);
80   
81   // Check that there is something on the line.
82   if (PatternStr.empty()) {
83     SM.PrintMessage(PatternLoc, "found empty check string with prefix '" +
84                     CheckPrefix+":'", "error");
85     return true;
86   }
87   
88   // Check to see if this is a fixed string, or if it has regex pieces.
89   if (PatternStr.size() < 2 || PatternStr.find("{{") == StringRef::npos) {
90     FixedStr = PatternStr;
91     return false;
92   }
93   
94   // Otherwise, there is at least one regex piece.  Build up the regex pattern
95   // by escaping scary characters in fixed strings, building up one big regex.
96   while (!PatternStr.empty()) {
97     // Handle fixed string matches.
98     if (PatternStr.size() < 2 ||
99         PatternStr[0] != '{' || PatternStr[1] != '{') {
100       // Find the end, which is the start of the next regex.
101       size_t FixedMatchEnd = PatternStr.find("{{");
102       AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd));
103       PatternStr = PatternStr.substr(FixedMatchEnd);
104       continue;
105     }
106     
107     // Otherwise, this is the start of a regex match.  Scan for the }}.
108     size_t End = PatternStr.find("}}");
109     if (End == StringRef::npos) {
110       SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
111                       "found start of regex string with no end '}}'", "error");
112       return true;
113     }
114     
115     StringRef RegexStr = PatternStr.substr(2, End-2);
116     Regex R(RegexStr);
117     std::string Error;
118     if (!R.isValid(Error)) {
119       SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()+2),
120                       "invalid regex: " + Error, "error");
121       return true;
122     }
123     
124     RegExStr += RegexStr.str();
125     PatternStr = PatternStr.substr(End+2);
126   }
127
128   return false;
129 }
130
131 void Pattern::AddFixedStringToRegEx(StringRef FixedStr) {
132   // Add the characters from FixedStr to the regex, escaping as needed.  This
133   // avoids "leaning toothpicks" in common patterns.
134   for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
135     switch (FixedStr[i]) {
136     // These are the special characters matched in "p_ere_exp".
137     case '(':
138     case ')':
139     case '^':
140     case '$':
141     case '|':
142     case '*':
143     case '+':
144     case '?':
145     case '.':
146     case '[':
147     case '\\':
148     case '{':
149       RegExStr += '\\';
150       // FALL THROUGH.
151     default:
152       RegExStr += FixedStr[i];
153       break;
154     }
155   }
156 }
157
158
159 /// Match - Match the pattern string against the input buffer Buffer.  This
160 /// returns the position that is matched or npos if there is no match.  If
161 /// there is a match, the size of the matched string is returned in MatchLen.
162 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen) const {
163   // If this is a fixed string pattern, just match it now.
164   if (!FixedStr.empty()) {
165     MatchLen = FixedStr.size();
166     return Buffer.find(FixedStr);
167   }
168   
169   // Regex match.
170   SmallVector<StringRef, 4> MatchInfo;
171   if (!Regex(RegExStr, Regex::Newline).match(Buffer, &MatchInfo))
172     return StringRef::npos;
173   
174   // Successful regex match.
175   assert(!MatchInfo.empty() && "Didn't get any match");
176   StringRef FullMatch = MatchInfo[0];
177   
178   
179   if (MatchInfo.size() != 1) {
180     SM->PrintMessage(PatternLoc, "regex cannot use grouping parens", "error");
181     exit(1);
182   }
183     
184   
185   MatchLen = FullMatch.size();
186   return FullMatch.data()-Buffer.data();
187 }
188
189
190 //===----------------------------------------------------------------------===//
191 // Check Strings.
192 //===----------------------------------------------------------------------===//
193
194 /// CheckString - This is a check that we found in the input file.
195 struct CheckString {
196   /// Pat - The pattern to match.
197   Pattern Pat;
198   
199   /// Loc - The location in the match file that the check string was specified.
200   SMLoc Loc;
201   
202   /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
203   /// to a CHECK: directive.
204   bool IsCheckNext;
205   
206   /// NotStrings - These are all of the strings that are disallowed from
207   /// occurring between this match string and the previous one (or start of
208   /// file).
209   std::vector<std::pair<SMLoc, Pattern> > NotStrings;
210   
211   CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
212     : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
213 };
214
215 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
216 /// memory buffer, free it, and return a new one.
217 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
218   SmallVector<char, 16> NewFile;
219   NewFile.reserve(MB->getBufferSize());
220   
221   for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
222        Ptr != End; ++Ptr) {
223     // If C is not a horizontal whitespace, skip it.
224     if (*Ptr != ' ' && *Ptr != '\t') {
225       NewFile.push_back(*Ptr);
226       continue;
227     }
228     
229     // Otherwise, add one space and advance over neighboring space.
230     NewFile.push_back(' ');
231     while (Ptr+1 != End &&
232            (Ptr[1] == ' ' || Ptr[1] == '\t'))
233       ++Ptr;
234   }
235   
236   // Free the old buffer and return a new one.
237   MemoryBuffer *MB2 =
238     MemoryBuffer::getMemBufferCopy(NewFile.data(), 
239                                    NewFile.data() + NewFile.size(),
240                                    MB->getBufferIdentifier());
241   
242   delete MB;
243   return MB2;
244 }
245
246
247 /// ReadCheckFile - Read the check file, which specifies the sequence of
248 /// expected strings.  The strings are added to the CheckStrings vector.
249 static bool ReadCheckFile(SourceMgr &SM,
250                           std::vector<CheckString> &CheckStrings) {
251   // Open the check file, and tell SourceMgr about it.
252   std::string ErrorStr;
253   MemoryBuffer *F =
254     MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
255   if (F == 0) {
256     errs() << "Could not open check file '" << CheckFilename << "': " 
257            << ErrorStr << '\n';
258     return true;
259   }
260   
261   // If we want to canonicalize whitespace, strip excess whitespace from the
262   // buffer containing the CHECK lines.
263   if (!NoCanonicalizeWhiteSpace)
264     F = CanonicalizeInputFile(F);
265   
266   SM.AddNewSourceBuffer(F, SMLoc());
267
268   // Find all instances of CheckPrefix followed by : in the file.
269   StringRef Buffer = F->getBuffer();
270
271   std::vector<std::pair<SMLoc, Pattern> > NotMatches;
272   
273   while (1) {
274     // See if Prefix occurs in the memory buffer.
275     Buffer = Buffer.substr(Buffer.find(CheckPrefix));
276     
277     // If we didn't find a match, we're done.
278     if (Buffer.empty())
279       break;
280     
281     const char *CheckPrefixStart = Buffer.data();
282     
283     // When we find a check prefix, keep track of whether we find CHECK: or
284     // CHECK-NEXT:
285     bool IsCheckNext = false, IsCheckNot = false;
286     
287     // Verify that the : is present after the prefix.
288     if (Buffer[CheckPrefix.size()] == ':') {
289       Buffer = Buffer.substr(CheckPrefix.size()+1);
290     } else if (Buffer.size() > CheckPrefix.size()+6 &&
291                memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
292       Buffer = Buffer.substr(CheckPrefix.size()+7);
293       IsCheckNext = true;
294     } else if (Buffer.size() > CheckPrefix.size()+5 &&
295                memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
296       Buffer = Buffer.substr(CheckPrefix.size()+6);
297       IsCheckNot = true;
298     } else {
299       Buffer = Buffer.substr(1);
300       continue;
301     }
302     
303     // Okay, we found the prefix, yay.  Remember the rest of the line, but
304     // ignore leading and trailing whitespace.
305     Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
306     
307     // Scan ahead to the end of line.
308     size_t EOL = Buffer.find_first_of("\n\r");
309
310     // Parse the pattern.
311     Pattern P;
312     if (P.ParsePattern(Buffer.substr(0, EOL), SM))
313       return true;
314     
315     Buffer = Buffer.substr(EOL);
316
317     
318     // Verify that CHECK-NEXT lines have at least one CHECK line before them.
319     if (IsCheckNext && CheckStrings.empty()) {
320       SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
321                       "found '"+CheckPrefix+"-NEXT:' without previous '"+
322                       CheckPrefix+ ": line", "error");
323       return true;
324     }
325     
326     // Handle CHECK-NOT.
327     if (IsCheckNot) {
328       NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
329                                           P));
330       continue;
331     }
332     
333     
334     // Okay, add the string we captured to the output vector and move on.
335     CheckStrings.push_back(CheckString(P,
336                                        SMLoc::getFromPointer(Buffer.data()),
337                                        IsCheckNext));
338     std::swap(NotMatches, CheckStrings.back().NotStrings);
339   }
340   
341   if (CheckStrings.empty()) {
342     errs() << "error: no check strings found with prefix '" << CheckPrefix
343            << ":'\n";
344     return true;
345   }
346   
347   if (!NotMatches.empty()) {
348     errs() << "error: '" << CheckPrefix
349            << "-NOT:' not supported after last check line.\n";
350     return true;
351   }
352   
353   return false;
354 }
355
356 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
357                              StringRef Buffer) {
358   // Otherwise, we have an error, emit an error message.
359   SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
360                   "error");
361   
362   // Print the "scanning from here" line.  If the current position is at the
363   // end of a line, advance to the start of the next line.
364   Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
365   
366   SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
367                   "note");
368 }
369
370 /// CountNumNewlinesBetween - Count the number of newlines in the specified
371 /// range.
372 static unsigned CountNumNewlinesBetween(StringRef Range) {
373   unsigned NumNewLines = 0;
374   while (1) {
375     // Scan for newline.
376     Range = Range.substr(Range.find_first_of("\n\r"));
377     if (Range.empty()) return NumNewLines;
378     
379     ++NumNewLines;
380     
381     // Handle \n\r and \r\n as a single newline.
382     if (Range.size() > 1 &&
383         (Range[1] == '\n' || Range[1] == '\r') &&
384         (Range[0] != Range[1]))
385       Range = Range.substr(1);
386     Range = Range.substr(1);
387   }
388 }
389
390 int main(int argc, char **argv) {
391   sys::PrintStackTraceOnErrorSignal();
392   PrettyStackTraceProgram X(argc, argv);
393   cl::ParseCommandLineOptions(argc, argv);
394
395   SourceMgr SM;
396   
397   // Read the expected strings from the check file.
398   std::vector<CheckString> CheckStrings;
399   if (ReadCheckFile(SM, CheckStrings))
400     return 2;
401
402   // Open the file to check and add it to SourceMgr.
403   std::string ErrorStr;
404   MemoryBuffer *F =
405     MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
406   if (F == 0) {
407     errs() << "Could not open input file '" << InputFilename << "': " 
408            << ErrorStr << '\n';
409     return true;
410   }
411   
412   // Remove duplicate spaces in the input file if requested.
413   if (!NoCanonicalizeWhiteSpace)
414     F = CanonicalizeInputFile(F);
415   
416   SM.AddNewSourceBuffer(F, SMLoc());
417   
418   // Check that we have all of the expected strings, in order, in the input
419   // file.
420   StringRef Buffer = F->getBuffer();
421   
422   const char *LastMatch = Buffer.data();
423   
424   for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
425     const CheckString &CheckStr = CheckStrings[StrNo];
426     
427     StringRef SearchFrom = Buffer;
428     
429     // Find StrNo in the file.
430     size_t MatchLen = 0;
431     Buffer = Buffer.substr(CheckStr.Pat.Match(Buffer, MatchLen));
432     
433     // If we didn't find a match, reject the input.
434     if (Buffer.empty()) {
435       PrintCheckFailed(SM, CheckStr, SearchFrom);
436       return 1;
437     }
438
439     StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
440
441     // If this check is a "CHECK-NEXT", verify that the previous match was on
442     // the previous line (i.e. that there is one newline between them).
443     if (CheckStr.IsCheckNext) {
444       // Count the number of newlines between the previous match and this one.
445       assert(LastMatch != F->getBufferStart() &&
446              "CHECK-NEXT can't be the first check in a file");
447
448       unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
449       if (NumNewLines == 0) {
450         SM.PrintMessage(CheckStr.Loc,
451                     CheckPrefix+"-NEXT: is on the same line as previous match",
452                         "error");
453         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
454                         "'next' match was here", "note");
455         SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
456                         "previous match was here", "note");
457         return 1;
458       }
459       
460       if (NumNewLines != 1) {
461         SM.PrintMessage(CheckStr.Loc,
462                         CheckPrefix+
463                         "-NEXT: is not on the line after the previous match",
464                         "error");
465         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
466                         "'next' match was here", "note");
467         SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
468                         "previous match was here", "note");
469         return 1;
470       }
471     }
472     
473     // If this match had "not strings", verify that they don't exist in the
474     // skipped region.
475     for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size(); ChunkNo != e; ++ChunkNo) {
476       size_t MatchLen = 0;
477       size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion, MatchLen);
478       if (Pos == StringRef::npos) continue;
479      
480       SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
481                       CheckPrefix+"-NOT: string occurred!", "error");
482       SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first,
483                       CheckPrefix+"-NOT: pattern specified here", "note");
484       return 1;
485     }
486     
487
488     // Otherwise, everything is good.  Step over the matched text and remember
489     // the position after the match as the end of the last match.
490     Buffer = Buffer.substr(MatchLen);
491     LastMatch = Buffer.data();
492   }
493   
494   return 0;
495 }