rewrite FileCheck in terms of StringRef instead of manual pointer pairs.
[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/SourceMgr.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/System/Signals.h"
25 using namespace llvm;
26
27 static cl::opt<std::string>
28 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
29
30 static cl::opt<std::string>
31 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
32               cl::init("-"), cl::value_desc("filename"));
33
34 static cl::opt<std::string>
35 CheckPrefix("check-prefix", cl::init("CHECK"),
36             cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
37
38 static cl::opt<bool>
39 NoCanonicalizeWhiteSpace("strict-whitespace",
40               cl::desc("Do not treat all horizontal whitespace as equivalent"));
41
42 /// CheckString - This is a check that we found in the input file.
43 struct CheckString {
44   /// Str - The string to match.
45   std::string Str;
46   
47   /// Loc - The location in the match file that the check string was specified.
48   SMLoc Loc;
49   
50   /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
51   /// to a CHECK: directive.
52   bool IsCheckNext;
53   
54   CheckString(const std::string &S, SMLoc L, bool isCheckNext)
55     : Str(S), Loc(L), IsCheckNext(isCheckNext) {}
56 };
57
58
59 /// ReadCheckFile - Read the check file, which specifies the sequence of
60 /// expected strings.  The strings are added to the CheckStrings vector.
61 static bool ReadCheckFile(SourceMgr &SM,
62                           std::vector<CheckString> &CheckStrings) {
63   // Open the check file, and tell SourceMgr about it.
64   std::string ErrorStr;
65   MemoryBuffer *F =
66     MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
67   if (F == 0) {
68     errs() << "Could not open check file '" << CheckFilename << "': " 
69            << ErrorStr << '\n';
70     return true;
71   }
72   SM.AddNewSourceBuffer(F, SMLoc());
73
74   // Find all instances of CheckPrefix followed by : in the file.
75   StringRef Buffer = F->getBuffer();
76
77   while (1) {
78     // See if Prefix occurs in the memory buffer.
79     Buffer = Buffer.substr(Buffer.find(CheckPrefix));
80     
81     // If we didn't find a match, we're done.
82     if (Buffer.empty())
83       break;
84     
85     const char *CheckPrefixStart = Buffer.data();
86     
87     // When we find a check prefix, keep track of whether we find CHECK: or
88     // CHECK-NEXT:
89     bool IsCheckNext;
90     
91     // Verify that the : is present after the prefix.
92     if (Buffer[CheckPrefix.size()] == ':') {
93       Buffer = Buffer.substr(CheckPrefix.size()+1);
94       IsCheckNext = false;
95     } else if (Buffer.size() > CheckPrefix.size()+6 &&
96                memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
97       Buffer = Buffer.substr(CheckPrefix.size()+7);
98       IsCheckNext = true;
99     } else {
100       Buffer = Buffer.substr(1);
101       continue;
102     }
103     
104     // Okay, we found the prefix, yay.  Remember the rest of the line, but
105     // ignore leading and trailing whitespace.
106     while (!Buffer.empty() && (Buffer[0] == ' ' || Buffer[0] == '\t'))
107       Buffer = Buffer.substr(1);
108     
109     // Scan ahead to the end of line.
110     size_t EOL = Buffer.find_first_of("\n\r");
111     if (EOL == StringRef::npos) EOL = Buffer.size();
112     
113     // Ignore trailing whitespace.
114     while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\t'))
115       --EOL;
116     
117     // Check that there is something on the line.
118     if (EOL == 0) {
119       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
120                       "found empty check string with prefix '"+CheckPrefix+":'",
121                       "error");
122       return true;
123     }
124     
125     // Verify that CHECK-NEXT lines have at least one CHECK line before them.
126     if (IsCheckNext && CheckStrings.empty()) {
127       SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
128                       "found '"+CheckPrefix+"-NEXT:' without previous '"+
129                       CheckPrefix+ ": line", "error");
130       return true;
131     }
132     
133     // Okay, add the string we captured to the output vector and move on.
134     CheckStrings.push_back(CheckString(std::string(Buffer.data(),
135                                                    Buffer.data()+EOL),
136                                        SMLoc::getFromPointer(Buffer.data()),
137                                        IsCheckNext));
138     
139     Buffer = Buffer.substr(EOL);
140   }
141   
142   if (CheckStrings.empty()) {
143     errs() << "error: no check strings found with prefix '" << CheckPrefix
144            << ":'\n";
145     return true;
146   }
147   
148   return false;
149 }
150
151 // CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in
152 // the check strings with a single space.
153 static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {
154   for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {
155     std::string &Str = CheckStrings[i].Str;
156     
157     for (unsigned C = 0; C != Str.size(); ++C) {
158       // If C is not a horizontal whitespace, skip it.
159       if (Str[C] != ' ' && Str[C] != '\t')
160         continue;
161       
162       // Replace the character with space, then remove any other space
163       // characters after it.
164       Str[C] = ' ';
165       
166       while (C+1 != Str.size() &&
167              (Str[C+1] == ' ' || Str[C+1] == '\t'))
168         Str.erase(Str.begin()+C+1);
169     }
170   }
171 }
172
173 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
174 /// memory buffer, free it, and return a new one.
175 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
176   SmallVector<char, 16> NewFile;
177   NewFile.reserve(MB->getBufferSize());
178   
179   for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
180        Ptr != End; ++Ptr) {
181     // If C is not a horizontal whitespace, skip it.
182     if (*Ptr != ' ' && *Ptr != '\t') {
183       NewFile.push_back(*Ptr);
184       continue;
185     }
186     
187     // Otherwise, add one space and advance over neighboring space.
188     NewFile.push_back(' ');
189     while (Ptr+1 != End &&
190            (Ptr[1] == ' ' || Ptr[1] == '\t'))
191       ++Ptr;
192   }
193   
194   // Free the old buffer and return a new one.
195   MemoryBuffer *MB2 =
196     MemoryBuffer::getMemBufferCopy(NewFile.data(), 
197                                    NewFile.data() + NewFile.size(),
198                                    MB->getBufferIdentifier());
199
200   delete MB;
201   return MB2;
202 }
203
204
205 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
206                              StringRef Buffer) {
207   // Otherwise, we have an error, emit an error message.
208   SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
209                   "error");
210   
211   // Print the "scanning from here" line.  If the current position is at the
212   // end of a line, advance to the start of the next line.
213   Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
214   
215   SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
216                   "note");
217 }
218
219 static unsigned CountNumNewlinesBetween(const char *Start, const char *End) {
220   unsigned NumNewLines = 0;
221   for (; Start != End; ++Start) {
222     // Scan for newline.
223     if (Start[0] != '\n' && Start[0] != '\r')
224       continue;
225     
226     ++NumNewLines;
227     
228     // Handle \n\r and \r\n as a single newline.
229     if (Start+1 != End &&
230         (Start[0] == '\n' || Start[0] == '\r') &&
231         (Start[0] != Start[1]))
232       ++Start;
233   }
234   
235   return NumNewLines;
236 }
237
238 int main(int argc, char **argv) {
239   sys::PrintStackTraceOnErrorSignal();
240   PrettyStackTraceProgram X(argc, argv);
241   cl::ParseCommandLineOptions(argc, argv);
242
243   SourceMgr SM;
244   
245   // Read the expected strings from the check file.
246   std::vector<CheckString> CheckStrings;
247   if (ReadCheckFile(SM, CheckStrings))
248     return 2;
249
250   // Remove duplicate spaces in the check strings if requested.
251   if (!NoCanonicalizeWhiteSpace)
252     CanonicalizeCheckStrings(CheckStrings);
253
254   // Open the file to check and add it to SourceMgr.
255   std::string ErrorStr;
256   MemoryBuffer *F =
257     MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
258   if (F == 0) {
259     errs() << "Could not open input file '" << InputFilename << "': " 
260            << ErrorStr << '\n';
261     return true;
262   }
263   
264   // Remove duplicate spaces in the input file if requested.
265   if (!NoCanonicalizeWhiteSpace)
266     F = CanonicalizeInputFile(F);
267   
268   SM.AddNewSourceBuffer(F, SMLoc());
269   
270   // Check that we have all of the expected strings, in order, in the input
271   // file.
272   StringRef Buffer = F->getBuffer();
273   
274   const char *LastMatch = 0;
275   for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
276     const CheckString &CheckStr = CheckStrings[StrNo];
277     
278     StringRef SearchFrom = Buffer;
279     
280     // Find StrNo in the file.
281     Buffer = Buffer.substr(Buffer.find(CheckStr.Str));
282     
283     // If we didn't find a match, reject the input.
284     if (Buffer.empty()) {
285       PrintCheckFailed(SM, CheckStr, SearchFrom);
286       return 1;
287     }
288     
289     // If this check is a "CHECK-NEXT", verify that the previous match was on
290     // the previous line (i.e. that there is one newline between them).
291     if (CheckStr.IsCheckNext) {
292       // Count the number of newlines between the previous match and this one.
293       assert(LastMatch && "CHECK-NEXT can't be the first check in a file");
294
295       unsigned NumNewLines = CountNumNewlinesBetween(LastMatch, Buffer.data());
296       if (NumNewLines == 0) {
297         SM.PrintMessage(CheckStr.Loc,
298                     CheckPrefix+"-NEXT: is on the same line as previous match",
299                         "error");
300         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
301                         "'next' match was here", "note");
302         SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
303                         "previous match was here", "note");
304         return 1;
305       }
306       
307       if (NumNewLines != 1) {
308         SM.PrintMessage(CheckStr.Loc,
309                         CheckPrefix+
310                         "-NEXT: is not on the line after the previous match",
311                         "error");
312         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
313                         "'next' match was here", "note");
314         SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
315                         "previous match was here", "note");
316         return 1;
317       }
318     }
319
320     // Otherwise, everything is good.  Remember this as the last match and move
321     // on to the next one.
322     LastMatch = Buffer.data();
323     Buffer = Buffer.substr(CheckStr.Str.size());
324   }
325   
326   return 0;
327 }