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 /// NotStrings - These are all of the strings that are disallowed from
55 /// occurring between this match string and the previous one (or start of
57 std::vector<std::pair<SMLoc, std::string> > NotStrings;
59 CheckString(const std::string &S, SMLoc L, bool isCheckNext)
60 : Str(S), Loc(L), IsCheckNext(isCheckNext) {}
64 /// ReadCheckFile - Read the check file, which specifies the sequence of
65 /// expected strings. The strings are added to the CheckStrings vector.
66 static bool ReadCheckFile(SourceMgr &SM,
67 std::vector<CheckString> &CheckStrings) {
68 // Open the check file, and tell SourceMgr about it.
71 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
73 errs() << "Could not open check file '" << CheckFilename << "': "
77 SM.AddNewSourceBuffer(F, SMLoc());
79 // Find all instances of CheckPrefix followed by : in the file.
80 StringRef Buffer = F->getBuffer();
82 std::vector<std::pair<SMLoc, std::string> > NotMatches;
85 // See if Prefix occurs in the memory buffer.
86 Buffer = Buffer.substr(Buffer.find(CheckPrefix));
88 // If we didn't find a match, we're done.
92 const char *CheckPrefixStart = Buffer.data();
94 // When we find a check prefix, keep track of whether we find CHECK: or
96 bool IsCheckNext = false, IsCheckNot = false;
98 // Verify that the : is present after the prefix.
99 if (Buffer[CheckPrefix.size()] == ':') {
100 Buffer = Buffer.substr(CheckPrefix.size()+1);
101 } else if (Buffer.size() > CheckPrefix.size()+6 &&
102 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
103 Buffer = Buffer.substr(CheckPrefix.size()+7);
105 } else if (Buffer.size() > CheckPrefix.size()+5 &&
106 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
107 Buffer = Buffer.substr(CheckPrefix.size()+6);
110 Buffer = Buffer.substr(1);
114 // Okay, we found the prefix, yay. Remember the rest of the line, but
115 // ignore leading and trailing whitespace.
116 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
118 // Scan ahead to the end of line.
119 size_t EOL = Buffer.find_first_of("\n\r");
120 if (EOL == StringRef::npos) EOL = Buffer.size();
122 // Ignore trailing whitespace.
123 while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\t'))
126 // Check that there is something on the line.
128 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
129 "found empty check string with prefix '"+CheckPrefix+":'",
134 StringRef PatternStr = Buffer.substr(0, EOL);
138 NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
140 Buffer = Buffer.substr(EOL);
144 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
145 if (IsCheckNext && CheckStrings.empty()) {
146 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
147 "found '"+CheckPrefix+"-NEXT:' without previous '"+
148 CheckPrefix+ ": line", "error");
152 // Okay, add the string we captured to the output vector and move on.
153 CheckStrings.push_back(CheckString(PatternStr.str(),
154 SMLoc::getFromPointer(Buffer.data()),
156 std::swap(NotMatches, CheckStrings.back().NotStrings);
158 Buffer = Buffer.substr(EOL);
161 if (CheckStrings.empty()) {
162 errs() << "error: no check strings found with prefix '" << CheckPrefix
167 if (!NotMatches.empty()) {
168 errs() << "error: '" << CheckPrefix
169 << "-NOT:' not supported after last check line.\n";
176 // CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in
177 // the check strings with a single space.
178 static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {
179 for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {
180 std::string &Str = CheckStrings[i].Str;
182 for (unsigned C = 0; C != Str.size(); ++C) {
183 // If C is not a horizontal whitespace, skip it.
184 if (Str[C] != ' ' && Str[C] != '\t')
187 // Replace the character with space, then remove any other space
188 // characters after it.
191 while (C+1 != Str.size() &&
192 (Str[C+1] == ' ' || Str[C+1] == '\t'))
193 Str.erase(Str.begin()+C+1);
198 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
199 /// memory buffer, free it, and return a new one.
200 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
201 SmallVector<char, 16> NewFile;
202 NewFile.reserve(MB->getBufferSize());
204 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
206 // If C is not a horizontal whitespace, skip it.
207 if (*Ptr != ' ' && *Ptr != '\t') {
208 NewFile.push_back(*Ptr);
212 // Otherwise, add one space and advance over neighboring space.
213 NewFile.push_back(' ');
214 while (Ptr+1 != End &&
215 (Ptr[1] == ' ' || Ptr[1] == '\t'))
219 // Free the old buffer and return a new one.
221 MemoryBuffer::getMemBufferCopy(NewFile.data(),
222 NewFile.data() + NewFile.size(),
223 MB->getBufferIdentifier());
230 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
232 // Otherwise, we have an error, emit an error message.
233 SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
236 // Print the "scanning from here" line. If the current position is at the
237 // end of a line, advance to the start of the next line.
238 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
240 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
244 static unsigned CountNumNewlinesBetween(const char *Start, const char *End) {
245 unsigned NumNewLines = 0;
246 for (; Start != End; ++Start) {
248 if (Start[0] != '\n' && Start[0] != '\r')
253 // Handle \n\r and \r\n as a single newline.
254 if (Start+1 != End &&
255 (Start[0] == '\n' || Start[0] == '\r') &&
256 (Start[0] != Start[1]))
263 int main(int argc, char **argv) {
264 sys::PrintStackTraceOnErrorSignal();
265 PrettyStackTraceProgram X(argc, argv);
266 cl::ParseCommandLineOptions(argc, argv);
270 // Read the expected strings from the check file.
271 std::vector<CheckString> CheckStrings;
272 if (ReadCheckFile(SM, CheckStrings))
275 // Remove duplicate spaces in the check strings if requested.
276 if (!NoCanonicalizeWhiteSpace)
277 CanonicalizeCheckStrings(CheckStrings);
279 // Open the file to check and add it to SourceMgr.
280 std::string ErrorStr;
282 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
284 errs() << "Could not open input file '" << InputFilename << "': "
289 // Remove duplicate spaces in the input file if requested.
290 if (!NoCanonicalizeWhiteSpace)
291 F = CanonicalizeInputFile(F);
293 SM.AddNewSourceBuffer(F, SMLoc());
295 // Check that we have all of the expected strings, in order, in the input
297 StringRef Buffer = F->getBuffer();
299 const char *LastMatch = Buffer.data();
301 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
302 const CheckString &CheckStr = CheckStrings[StrNo];
304 StringRef SearchFrom = Buffer;
306 // Find StrNo in the file.
307 Buffer = Buffer.substr(Buffer.find(CheckStr.Str));
309 // If we didn't find a match, reject the input.
310 if (Buffer.empty()) {
311 PrintCheckFailed(SM, CheckStr, SearchFrom);
315 // If this check is a "CHECK-NEXT", verify that the previous match was on
316 // the previous line (i.e. that there is one newline between them).
317 if (CheckStr.IsCheckNext) {
318 // Count the number of newlines between the previous match and this one.
319 assert(LastMatch != F->getBufferStart() &&
320 "CHECK-NEXT can't be the first check in a file");
322 unsigned NumNewLines = CountNumNewlinesBetween(LastMatch, Buffer.data());
323 if (NumNewLines == 0) {
324 SM.PrintMessage(CheckStr.Loc,
325 CheckPrefix+"-NEXT: is on the same line as previous match",
327 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
328 "'next' match was here", "note");
329 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
330 "previous match was here", "note");
334 if (NumNewLines != 1) {
335 SM.PrintMessage(CheckStr.Loc,
337 "-NEXT: is not on the line after the previous match",
339 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
340 "'next' match was here", "note");
341 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
342 "previous match was here", "note");
347 // If this match had "not strings", verify that they don't exist in the
349 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
350 for (unsigned i = 0, e = CheckStr.NotStrings.size(); i != e; ++i) {
351 size_t Pos = SkippedRegion.find(CheckStr.NotStrings[i].second);
352 if (Pos == StringRef::npos) continue;
354 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
355 CheckPrefix+"-NOT: string occurred!", "error");
356 SM.PrintMessage(CheckStr.NotStrings[i].first,
357 CheckPrefix+"-NOT: pattern specified here", "note");
362 // Otherwise, everything is good. Remember this as the last match and move
363 // on to the next one.
364 LastMatch = Buffer.data();
365 Buffer = Buffer.substr(CheckStr.Str.size());