Big change #1 for personality function references:
[llvm/avr.git] / utils / FileCheck / FileCheck.cpp
blobc092dedc63fa467bde96d1bb9932c1ba52fdc12d
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.
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.
17 //===----------------------------------------------------------------------===//
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;
27 static cl::opt<std::string>
28 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
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"));
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')"));
38 static cl::opt<bool>
39 NoCanonicalizeWhiteSpace("strict-whitespace",
40 cl::desc("Do not treat all horizontal whitespace as equivalent"));
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;
47 /// Loc - The location in the match file that the check string was specified.
48 SMLoc Loc;
50 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
51 /// to a CHECK: directive.
52 bool IsCheckNext;
54 CheckString(const std::string &S, SMLoc L, bool isCheckNext)
55 : Str(S), Loc(L), IsCheckNext(isCheckNext) {}
59 /// FindFixedStringInBuffer - This works like strstr, except for two things:
60 /// 1) it handles 'nul' characters in memory buffers. 2) it returns the end of
61 /// the memory buffer on match failure instead of null.
62 static const char *FindFixedStringInBuffer(StringRef Str, const char *CurPtr,
63 const MemoryBuffer &MB) {
64 assert(!Str.empty() && "Can't find an empty string");
65 const char *BufEnd = MB.getBufferEnd();
67 while (1) {
68 // Scan for the first character in the match string.
69 CurPtr = (char*)memchr(CurPtr, Str[0], BufEnd-CurPtr);
71 // If we didn't find the first character of the string, then we failed to
72 // match.
73 if (CurPtr == 0) return BufEnd;
75 // If the match string is one character, then we win.
76 if (Str.size() == 1) return CurPtr;
78 // Otherwise, verify that the rest of the string matches.
79 if (Str.size() <= unsigned(BufEnd-CurPtr) &&
80 memcmp(CurPtr+1, Str.data()+1, Str.size()-1) == 0)
81 return CurPtr;
83 // If not, advance past this character and try again.
84 ++CurPtr;
88 /// ReadCheckFile - Read the check file, which specifies the sequence of
89 /// expected strings. The strings are added to the CheckStrings vector.
90 static bool ReadCheckFile(SourceMgr &SM,
91 std::vector<CheckString> &CheckStrings) {
92 // Open the check file, and tell SourceMgr about it.
93 std::string ErrorStr;
94 MemoryBuffer *F =
95 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
96 if (F == 0) {
97 errs() << "Could not open check file '" << CheckFilename << "': "
98 << ErrorStr << '\n';
99 return true;
101 SM.AddNewSourceBuffer(F, SMLoc());
103 // Find all instances of CheckPrefix followed by : in the file.
104 const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd();
106 while (1) {
107 // See if Prefix occurs in the memory buffer.
108 const char *Ptr = FindFixedStringInBuffer(CheckPrefix, CurPtr, *F);
110 // If we didn't find a match, we're done.
111 if (Ptr == BufferEnd)
112 break;
114 const char *CheckPrefixStart = Ptr;
116 // When we find a check prefix, keep track of whether we find CHECK: or
117 // CHECK-NEXT:
118 bool IsCheckNext;
120 // Verify that the : is present after the prefix.
121 if (Ptr[CheckPrefix.size()] == ':') {
122 Ptr += CheckPrefix.size()+1;
123 IsCheckNext = false;
124 } else if (BufferEnd-Ptr > 6 &&
125 memcmp(Ptr+CheckPrefix.size(), "-NEXT:", 6) == 0) {
126 Ptr += CheckPrefix.size()+7;
127 IsCheckNext = true;
128 } else {
129 CurPtr = Ptr+1;
130 continue;
133 // Okay, we found the prefix, yay. Remember the rest of the line, but
134 // ignore leading and trailing whitespace.
135 while (*Ptr == ' ' || *Ptr == '\t')
136 ++Ptr;
138 // Scan ahead to the end of line.
139 CurPtr = Ptr;
140 while (CurPtr != BufferEnd && *CurPtr != '\n' && *CurPtr != '\r')
141 ++CurPtr;
143 // Ignore trailing whitespace.
144 while (CurPtr[-1] == ' ' || CurPtr[-1] == '\t')
145 --CurPtr;
147 // Check that there is something on the line.
148 if (Ptr >= CurPtr) {
149 SM.PrintMessage(SMLoc::getFromPointer(CurPtr),
150 "found empty check string with prefix '"+CheckPrefix+":'",
151 "error");
152 return true;
155 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
156 if (IsCheckNext && CheckStrings.empty()) {
157 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
158 "found '"+CheckPrefix+"-NEXT:' without previous '"+
159 CheckPrefix+ ": line", "error");
160 return true;
163 // Okay, add the string we captured to the output vector and move on.
164 CheckStrings.push_back(CheckString(std::string(Ptr, CurPtr),
165 SMLoc::getFromPointer(Ptr),
166 IsCheckNext));
169 if (CheckStrings.empty()) {
170 errs() << "error: no check strings found with prefix '" << CheckPrefix
171 << ":'\n";
172 return true;
175 return false;
178 // CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in
179 // the check strings with a single space.
180 static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {
181 for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {
182 std::string &Str = CheckStrings[i].Str;
184 for (unsigned C = 0; C != Str.size(); ++C) {
185 // If C is not a horizontal whitespace, skip it.
186 if (Str[C] != ' ' && Str[C] != '\t')
187 continue;
189 // Replace the character with space, then remove any other space
190 // characters after it.
191 Str[C] = ' ';
193 while (C+1 != Str.size() &&
194 (Str[C+1] == ' ' || Str[C+1] == '\t'))
195 Str.erase(Str.begin()+C+1);
200 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
201 /// memory buffer, free it, and return a new one.
202 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
203 SmallVector<char, 16> NewFile;
204 NewFile.reserve(MB->getBufferSize());
206 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
207 Ptr != End; ++Ptr) {
208 // If C is not a horizontal whitespace, skip it.
209 if (*Ptr != ' ' && *Ptr != '\t') {
210 NewFile.push_back(*Ptr);
211 continue;
214 // Otherwise, add one space and advance over neighboring space.
215 NewFile.push_back(' ');
216 while (Ptr+1 != End &&
217 (Ptr[1] == ' ' || Ptr[1] == '\t'))
218 ++Ptr;
221 // Free the old buffer and return a new one.
222 MemoryBuffer *MB2 =
223 MemoryBuffer::getMemBufferCopy(NewFile.data(),
224 NewFile.data() + NewFile.size(),
225 MB->getBufferIdentifier());
227 delete MB;
228 return MB2;
232 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
233 const char *CurPtr, const char *BufferEnd) {
234 // Otherwise, we have an error, emit an error message.
235 SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
236 "error");
238 // Print the "scanning from here" line. If the current position is at the
239 // end of a line, advance to the start of the next line.
240 const char *Scan = CurPtr;
241 while (Scan != BufferEnd &&
242 (*Scan == ' ' || *Scan == '\t'))
243 ++Scan;
244 if (*Scan == '\n' || *Scan == '\r')
245 CurPtr = Scan+1;
248 SM.PrintMessage(SMLoc::getFromPointer(CurPtr), "scanning from here",
249 "note");
252 static unsigned CountNumNewlinesBetween(const char *Start, const char *End) {
253 unsigned NumNewLines = 0;
254 for (; Start != End; ++Start) {
255 // Scan for newline.
256 if (Start[0] != '\n' && Start[0] != '\r')
257 continue;
259 ++NumNewLines;
261 // Handle \n\r and \r\n as a single newline.
262 if (Start+1 != End &&
263 (Start[0] == '\n' || Start[0] == '\r') &&
264 (Start[0] != Start[1]))
265 ++Start;
268 return NumNewLines;
271 int main(int argc, char **argv) {
272 sys::PrintStackTraceOnErrorSignal();
273 PrettyStackTraceProgram X(argc, argv);
274 cl::ParseCommandLineOptions(argc, argv);
276 SourceMgr SM;
278 // Read the expected strings from the check file.
279 std::vector<CheckString> CheckStrings;
280 if (ReadCheckFile(SM, CheckStrings))
281 return 2;
283 // Remove duplicate spaces in the check strings if requested.
284 if (!NoCanonicalizeWhiteSpace)
285 CanonicalizeCheckStrings(CheckStrings);
287 // Open the file to check and add it to SourceMgr.
288 std::string ErrorStr;
289 MemoryBuffer *F =
290 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
291 if (F == 0) {
292 errs() << "Could not open input file '" << InputFilename << "': "
293 << ErrorStr << '\n';
294 return true;
297 // Remove duplicate spaces in the input file if requested.
298 if (!NoCanonicalizeWhiteSpace)
299 F = CanonicalizeInputFile(F);
301 SM.AddNewSourceBuffer(F, SMLoc());
303 // Check that we have all of the expected strings, in order, in the input
304 // file.
305 const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd();
307 const char *LastMatch = 0;
308 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
309 const CheckString &CheckStr = CheckStrings[StrNo];
311 // Find StrNo in the file.
312 const char *Ptr = FindFixedStringInBuffer(CheckStr.Str, CurPtr, *F);
314 // If we didn't find a match, reject the input.
315 if (Ptr == BufferEnd) {
316 PrintCheckFailed(SM, CheckStr, CurPtr, BufferEnd);
317 return 1;
320 // If this check is a "CHECK-NEXT", verify that the previous match was on
321 // the previous line (i.e. that there is one newline between them).
322 if (CheckStr.IsCheckNext) {
323 // Count the number of newlines between the previous match and this one.
324 assert(LastMatch && "CHECK-NEXT can't be the first check in a file");
326 unsigned NumNewLines = CountNumNewlinesBetween(LastMatch, Ptr);
327 if (NumNewLines == 0) {
328 SM.PrintMessage(CheckStr.Loc,
329 CheckPrefix+"-NEXT: is on the same line as previous match",
330 "error");
331 SM.PrintMessage(SMLoc::getFromPointer(Ptr),
332 "'next' match was here", "note");
333 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
334 "previous match was here", "note");
335 return 1;
338 if (NumNewLines != 1) {
339 SM.PrintMessage(CheckStr.Loc,
340 CheckPrefix+
341 "-NEXT: is not on the line after the previous match",
342 "error");
343 SM.PrintMessage(SMLoc::getFromPointer(Ptr),
344 "'next' match was here", "note");
345 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
346 "previous match was here", "note");
347 return 1;
351 // Otherwise, everything is good. Remember this as the last match and move
352 // on to the next one.
353 LastMatch = Ptr;
354 CurPtr = Ptr + CheckStr.Str.size();
357 return 0;