rewrite FindStringInBuffer to use an explicit loop instead of
[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   CheckString(const std::string &S, SMLoc L) : Str(S), Loc(L) {}
51 };
52
53
54 /// FindFixedStringInBuffer - This works like strstr, except for two things:
55 /// 1) it handles 'nul' characters in memory buffers.  2) it returns the end of
56 /// the memory buffer on match failure instead of null.
57 static const char *FindFixedStringInBuffer(StringRef Str, const char *CurPtr,
58                                            const MemoryBuffer &MB) {
59   assert(!Str.empty() && "Can't find an empty string");
60   const char *BufEnd = MB.getBufferEnd();
61   
62   while (1) {
63     // Scan for the first character in the match string.
64     CurPtr = (char*)memchr(CurPtr, Str[0], BufEnd-CurPtr);
65     
66     // If we didn't find the first character of the string, then we failed to
67     // match.
68     if (CurPtr == 0) return BufEnd;
69
70     // If the match string is one character, then we win.
71     if (Str.size() == 1) return CurPtr;
72     
73     // Otherwise, verify that the rest of the string matches.
74     if (Str.size() <= unsigned(BufEnd-CurPtr) &&
75         memcmp(CurPtr+1, Str.data()+1, Str.size()-1) == 0)
76       return CurPtr;
77     
78     // If not, advance past this character and try again.
79     ++CurPtr;
80   }
81 }
82
83 /// ReadCheckFile - Read the check file, which specifies the sequence of
84 /// expected strings.  The strings are added to the CheckStrings vector.
85 static bool ReadCheckFile(SourceMgr &SM,
86                           std::vector<CheckString> &CheckStrings) {
87   // Open the check file, and tell SourceMgr about it.
88   std::string ErrorStr;
89   MemoryBuffer *F =
90     MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
91   if (F == 0) {
92     errs() << "Could not open check file '" << CheckFilename << "': " 
93            << ErrorStr << '\n';
94     return true;
95   }
96   SM.AddNewSourceBuffer(F, SMLoc());
97
98   // Find all instances of CheckPrefix followed by : in the file.  The
99   // MemoryBuffer is guaranteed to be nul terminated, but may have nul's
100   // embedded into it.  We don't support check strings with embedded nuls.
101   std::string Prefix = CheckPrefix + ":";
102   const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd();
103
104   while (1) {
105     // See if Prefix occurs in the memory buffer.
106     const char *Ptr = FindFixedStringInBuffer(Prefix, CurPtr, *F);
107     
108     // If we didn't find a match, we're done.
109     if (Ptr == BufferEnd)
110       break;
111     
112     // Okay, we found the prefix, yay.  Remember the rest of the line, but
113     // ignore leading and trailing whitespace.
114     Ptr += Prefix.size();
115     while (*Ptr == ' ' || *Ptr == '\t')
116       ++Ptr;
117     
118     // Scan ahead to the end of line.
119     CurPtr = Ptr;
120     while (CurPtr != BufferEnd && *CurPtr != '\n' && *CurPtr != '\r')
121       ++CurPtr;
122     
123     // Ignore trailing whitespace.
124     while (CurPtr[-1] == ' ' || CurPtr[-1] == '\t')
125       --CurPtr;
126     
127     // Check that there is something on the line.
128     if (Ptr >= CurPtr) {
129       SM.PrintMessage(SMLoc::getFromPointer(CurPtr),
130                       "found empty check string with prefix '"+Prefix+"'",
131                       "error");
132       return true;
133     }
134     
135     // Okay, add the string we captured to the output vector and move on.
136     CheckStrings.push_back(CheckString(std::string(Ptr, CurPtr),
137                                        SMLoc::getFromPointer(Ptr)));
138   }
139   
140   if (CheckStrings.empty()) {
141     errs() << "error: no check strings found with prefix '" << Prefix << "'\n";
142     return true;
143   }
144   
145   return false;
146 }
147
148 // CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in
149 // the check strings with a single space.
150 static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {
151   for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {
152     std::string &Str = CheckStrings[i].Str;
153     
154     for (unsigned C = 0; C != Str.size(); ++C) {
155       // If C is not a horizontal whitespace, skip it.
156       if (Str[C] != ' ' && Str[C] != '\t')
157         continue;
158       
159       // Replace the character with space, then remove any other space
160       // characters after it.
161       Str[C] = ' ';
162       
163       while (C+1 != Str.size() &&
164              (Str[C+1] == ' ' || Str[C+1] == '\t'))
165         Str.erase(Str.begin()+C+1);
166     }
167   }
168 }
169
170 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
171 /// memory buffer, free it, and return a new one.
172 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
173   SmallVector<char, 16> NewFile;
174   NewFile.reserve(MB->getBufferSize());
175   
176   for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
177        Ptr != End; ++Ptr) {
178     // If C is not a horizontal whitespace, skip it.
179     if (*Ptr != ' ' && *Ptr != '\t') {
180       NewFile.push_back(*Ptr);
181       continue;
182     }
183     
184     // Otherwise, add one space and advance over neighboring space.
185     NewFile.push_back(' ');
186     while (Ptr+1 != End &&
187            (Ptr[1] == ' ' || Ptr[1] == '\t'))
188       ++Ptr;
189   }
190   
191   // Free the old buffer and return a new one.
192   MemoryBuffer *MB2 =
193     MemoryBuffer::getMemBufferCopy(NewFile.data(), 
194                                    NewFile.data() + NewFile.size(),
195                                    MB->getBufferIdentifier());
196
197   delete MB;
198   return MB2;
199 }
200
201
202 int main(int argc, char **argv) {
203   sys::PrintStackTraceOnErrorSignal();
204   PrettyStackTraceProgram X(argc, argv);
205   cl::ParseCommandLineOptions(argc, argv);
206
207   SourceMgr SM;
208   
209   // Read the expected strings from the check file.
210   std::vector<CheckString> CheckStrings;
211   if (ReadCheckFile(SM, CheckStrings))
212     return 2;
213
214   // Remove duplicate spaces in the check strings if requested.
215   if (!NoCanonicalizeWhiteSpace)
216     CanonicalizeCheckStrings(CheckStrings);
217
218   // Open the file to check and add it to SourceMgr.
219   std::string ErrorStr;
220   MemoryBuffer *F =
221     MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
222   if (F == 0) {
223     errs() << "Could not open input file '" << InputFilename << "': " 
224            << ErrorStr << '\n';
225     return true;
226   }
227   
228   // Remove duplicate spaces in the input file if requested.
229   if (!NoCanonicalizeWhiteSpace)
230     F = CanonicalizeInputFile(F);
231   
232   SM.AddNewSourceBuffer(F, SMLoc());
233   
234   // Check that we have all of the expected strings, in order, in the input
235   // file.
236   const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd();
237   
238   for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
239     const CheckString &CheckStr = CheckStrings[StrNo];
240     
241     // Find StrNo in the file.
242     const char *Ptr = FindFixedStringInBuffer(CheckStr.Str, CurPtr, *F);
243     
244     // If we found a match, we're done, move on.
245     if (Ptr != BufferEnd) {
246       CurPtr = Ptr + CheckStr.Str.size();
247       continue;
248     }
249     
250     // Otherwise, we have an error, emit an error message.
251     SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
252                     "error");
253     
254     // Print the "scanning from here" line.  If the current position is at the
255     // end of a line, advance to the start of the next line.
256     const char *Scan = CurPtr;
257     while (Scan != BufferEnd &&
258            (*Scan == ' ' || *Scan == '\t'))
259       ++Scan;
260     if (*Scan == '\n' || *Scan == '\r')
261       CurPtr = Scan+1;
262     
263     
264     SM.PrintMessage(SMLoc::getFromPointer(CurPtr), "scanning from here",
265                     "note");
266     return 1;
267   }
268   
269   return 0;
270 }