add and document regex support for FileCheck. You can now do stuff like:
[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   /// Chunks - The pattern chunks to match.  If the bool is false, it is a fixed
49   /// string match, if it is true, it is a regex match.
50   SmallVector<std::pair<StringRef, bool>, 4> Chunks;
51 public:
52   
53   Pattern() { }
54   
55   bool ParsePattern(StringRef PatternStr, SourceMgr &SM);
56   
57   /// Match - Match the pattern string against the input buffer Buffer.  This
58   /// returns the position that is matched or npos if there is no match.  If
59   /// there is a match, the size of the matched string is returned in MatchLen.
60   size_t Match(StringRef Buffer, size_t &MatchLen) const;
61 };
62
63 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM) {
64   // Ignore trailing whitespace.
65   while (!PatternStr.empty() &&
66          (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
67     PatternStr = PatternStr.substr(0, PatternStr.size()-1);
68   
69   // Check that there is something on the line.
70   if (PatternStr.empty()) {
71     SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
72                     "found empty check string with prefix '"+CheckPrefix+":'",
73                     "error");
74     return true;
75   }
76   
77   // Scan the pattern to break it into regex and non-regex pieces.
78   while (!PatternStr.empty()) {
79     // Handle fixed string matches.
80     if (PatternStr.size() < 2 ||
81         PatternStr[0] != '{' || PatternStr[1] != '{') {
82       // Find the end, which is the start of the next regex.
83       size_t FixedMatchEnd = PatternStr.find("{{");
84       
85       Chunks.push_back(std::make_pair(PatternStr.substr(0, FixedMatchEnd),
86                                       false));
87       PatternStr = PatternStr.substr(FixedMatchEnd);
88       continue;
89     }
90     
91     // Otherwise, this is the start of a regex match.  Scan for the }}.
92     size_t End = PatternStr.find("}}");
93     if (End == StringRef::npos) {
94       SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
95                       "found start of regex string with no end '}}'", "error");
96       return true;
97     }
98     
99     Regex R(PatternStr.substr(2, End-2));
100     std::string Error;
101     if (!R.isValid(Error)) {
102       SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()+2),
103                       "invalid regex: " + Error, "error");
104       return true;
105     }
106     
107     Chunks.push_back(std::make_pair(PatternStr.substr(2, End-2), true));
108     PatternStr = PatternStr.substr(End+2);
109   }
110
111   return false;
112 }
113
114 /// Match - Match the pattern string against the input buffer Buffer.  This
115 /// returns the position that is matched or npos if there is no match.  If
116 /// there is a match, the size of the matched string is returned in MatchLen.
117 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen) const {
118   size_t FirstMatch = StringRef::npos;
119   MatchLen = 0;
120   
121   SmallVector<StringRef, 4> MatchInfo;
122   
123   while (!Buffer.empty()) {
124     StringRef MatchAttempt = Buffer;
125     
126     unsigned ChunkNo = 0, e = Chunks.size();
127     for (; ChunkNo != e; ++ChunkNo) {
128       StringRef PatternStr = Chunks[ChunkNo].first;
129       
130       size_t ThisMatch = StringRef::npos;
131       size_t ThisLength = StringRef::npos;
132       if (!Chunks[ChunkNo].second) {
133         // Fixed string match.
134         ThisMatch = MatchAttempt.find(Chunks[ChunkNo].first);
135         ThisLength = Chunks[ChunkNo].first.size();
136       } else if (Regex(Chunks[ChunkNo].first, Regex::Sub).match(MatchAttempt, &MatchInfo)) {
137         // Successful regex match.
138         assert(!MatchInfo.empty() && "Didn't get any match");
139         StringRef FullMatch = MatchInfo[0];
140         MatchInfo.clear();
141         
142         ThisMatch = FullMatch.data()-MatchAttempt.data();
143         ThisLength = FullMatch.size();
144       }
145       
146       // Otherwise, what we do depends on if this is the first match or not.  If
147       // this is the first match, it doesn't match to match at the start of
148       // MatchAttempt.
149       if (ChunkNo == 0) {
150         // If the first match fails then this pattern will never match in
151         // Buffer.
152         if (ThisMatch == StringRef::npos)
153           return ThisMatch;
154         
155         FirstMatch = ThisMatch;
156         MatchAttempt = MatchAttempt.substr(FirstMatch);
157         ThisMatch = 0;
158       }
159       
160       // If this chunk didn't match, then the entire pattern didn't match from
161       // FirstMatch, try later in the buffer.
162       if (ThisMatch == StringRef::npos)
163         break;
164       
165       // Ok, if the match didn't match at the beginning of MatchAttempt, then we
166       // have something like "ABC{{DEF}} and something was in-between.  Reject
167       // the match.
168       if (ThisMatch != 0)
169         break;
170       
171       // Otherwise, match the string and move to the next chunk.
172       MatchLen += ThisLength;
173       MatchAttempt = MatchAttempt.substr(ThisLength);
174     }
175
176     // If the whole thing matched, we win.
177     if (ChunkNo == e)
178       return FirstMatch;
179     
180     // Otherwise, try matching again after FirstMatch to see if this pattern
181     // matches later in the buffer.
182     Buffer = Buffer.substr(FirstMatch+1);
183   }
184   
185   // If we ran out of stuff to scan, then we didn't match.
186   return StringRef::npos;
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 }