1 //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
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')"));
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.
44 /// Str - The string to match.
47 /// Loc - The location in the match file that the check string was specified.
50 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
51 /// to a CHECK: directive.
54 CheckString(const std::string &S, SMLoc L, bool isCheckNext)
55 : Str(S), Loc(L), IsCheckNext(isCheckNext) {}
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.
66 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
68 errs() << "Could not open check file '" << CheckFilename << "': "
72 SM.AddNewSourceBuffer(F, SMLoc());
74 // Find all instances of CheckPrefix followed by : in the file.
75 StringRef Buffer = F->getBuffer();
78 // See if Prefix occurs in the memory buffer.
79 Buffer = Buffer.substr(Buffer.find(CheckPrefix));
81 // If we didn't find a match, we're done.
85 const char *CheckPrefixStart = Buffer.data();
87 // When we find a check prefix, keep track of whether we find CHECK: or
91 // Verify that the : is present after the prefix.
92 if (Buffer[CheckPrefix.size()] == ':') {
93 Buffer = Buffer.substr(CheckPrefix.size()+1);
95 } else if (Buffer.size() > CheckPrefix.size()+6 &&
96 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
97 Buffer = Buffer.substr(CheckPrefix.size()+7);
100 Buffer = Buffer.substr(1);
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);
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();
113 // Ignore trailing whitespace.
114 while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\t'))
117 // Check that there is something on the line.
119 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
120 "found empty check string with prefix '"+CheckPrefix+":'",
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");
133 // Okay, add the string we captured to the output vector and move on.
134 CheckStrings.push_back(CheckString(std::string(Buffer.data(),
136 SMLoc::getFromPointer(Buffer.data()),
139 Buffer = Buffer.substr(EOL);
142 if (CheckStrings.empty()) {
143 errs() << "error: no check strings found with prefix '" << CheckPrefix
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;
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')
162 // Replace the character with space, then remove any other space
163 // characters after it.
166 while (C+1 != Str.size() &&
167 (Str[C+1] == ' ' || Str[C+1] == '\t'))
168 Str.erase(Str.begin()+C+1);
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());
179 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
181 // If C is not a horizontal whitespace, skip it.
182 if (*Ptr != ' ' && *Ptr != '\t') {
183 NewFile.push_back(*Ptr);
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'))
194 // Free the old buffer and return a new one.
196 MemoryBuffer::getMemBufferCopy(NewFile.data(),
197 NewFile.data() + NewFile.size(),
198 MB->getBufferIdentifier());
205 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
207 // Otherwise, we have an error, emit an error message.
208 SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
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"));
215 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
219 static unsigned CountNumNewlinesBetween(const char *Start, const char *End) {
220 unsigned NumNewLines = 0;
221 for (; Start != End; ++Start) {
223 if (Start[0] != '\n' && Start[0] != '\r')
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]))
238 int main(int argc, char **argv) {
239 sys::PrintStackTraceOnErrorSignal();
240 PrettyStackTraceProgram X(argc, argv);
241 cl::ParseCommandLineOptions(argc, argv);
245 // Read the expected strings from the check file.
246 std::vector<CheckString> CheckStrings;
247 if (ReadCheckFile(SM, CheckStrings))
250 // Remove duplicate spaces in the check strings if requested.
251 if (!NoCanonicalizeWhiteSpace)
252 CanonicalizeCheckStrings(CheckStrings);
254 // Open the file to check and add it to SourceMgr.
255 std::string ErrorStr;
257 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
259 errs() << "Could not open input file '" << InputFilename << "': "
264 // Remove duplicate spaces in the input file if requested.
265 if (!NoCanonicalizeWhiteSpace)
266 F = CanonicalizeInputFile(F);
268 SM.AddNewSourceBuffer(F, SMLoc());
270 // Check that we have all of the expected strings, in order, in the input
272 StringRef Buffer = F->getBuffer();
274 const char *LastMatch = 0;
275 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
276 const CheckString &CheckStr = CheckStrings[StrNo];
278 StringRef SearchFrom = Buffer;
280 // Find StrNo in the file.
281 Buffer = Buffer.substr(Buffer.find(CheckStr.Str));
283 // If we didn't find a match, reject the input.
284 if (Buffer.empty()) {
285 PrintCheckFailed(SM, CheckStr, SearchFrom);
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");
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",
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");
307 if (NumNewLines != 1) {
308 SM.PrintMessage(CheckStr.Loc,
310 "-NEXT: is not on the line after the previous match",
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");
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());