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