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 //===----------------------------------------------------------------------===//
43 // Pattern Handling Code.
44 //===----------------------------------------------------------------------===//
47 /// Str - The string to match.
53 bool ParsePattern(StringRef PatternStr, SourceMgr &SM);
55 /// Match - Match the pattern string against the input buffer Buffer. This
56 /// returns the position that is matched or npos if there is no match. If
57 /// there is a match, the size of the matched string is returned in MatchLen.
58 size_t Match(StringRef Buffer, size_t &MatchLen) const {
59 MatchLen = Str.size();
60 return Buffer.find(Str);
64 /// CanonicalizeCheckString - Replace all sequences of horizontal whitespace
65 /// in the check strings with a single space.
66 void CanonicalizeCheckString() {
67 for (unsigned C = 0; C != Str.size(); ++C) {
68 // If C is not a horizontal whitespace, skip it.
69 if (Str[C] != ' ' && Str[C] != '\t')
72 // Replace the character with space, then remove any other space
73 // characters after it.
76 while (C+1 != Str.size() &&
77 (Str[C+1] == ' ' || Str[C+1] == '\t'))
78 Str.erase(Str.begin()+C+1);
83 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM) {
84 // Ignore trailing whitespace.
85 while (!PatternStr.empty() &&
86 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
87 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
89 // Check that there is something on the line.
90 if (PatternStr.empty()) {
91 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
92 "found empty check string with prefix '"+CheckPrefix+":'",
97 Str = PatternStr.str();
99 // Remove duplicate spaces in the check strings if requested.
100 if (!NoCanonicalizeWhiteSpace)
101 CanonicalizeCheckString();
107 //===----------------------------------------------------------------------===//
109 //===----------------------------------------------------------------------===//
111 /// CheckString - This is a check that we found in the input file.
113 /// Pat - The pattern to match.
116 /// Loc - The location in the match file that the check string was specified.
119 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
120 /// to a CHECK: directive.
123 /// NotStrings - These are all of the strings that are disallowed from
124 /// occurring between this match string and the previous one (or start of
126 std::vector<std::pair<SMLoc, Pattern> > NotStrings;
128 CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
129 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
133 /// ReadCheckFile - Read the check file, which specifies the sequence of
134 /// expected strings. The strings are added to the CheckStrings vector.
135 static bool ReadCheckFile(SourceMgr &SM,
136 std::vector<CheckString> &CheckStrings) {
137 // Open the check file, and tell SourceMgr about it.
138 std::string ErrorStr;
140 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
142 errs() << "Could not open check file '" << CheckFilename << "': "
146 SM.AddNewSourceBuffer(F, SMLoc());
148 // Find all instances of CheckPrefix followed by : in the file.
149 StringRef Buffer = F->getBuffer();
151 std::vector<std::pair<SMLoc, Pattern> > NotMatches;
154 // See if Prefix occurs in the memory buffer.
155 Buffer = Buffer.substr(Buffer.find(CheckPrefix));
157 // If we didn't find a match, we're done.
161 const char *CheckPrefixStart = Buffer.data();
163 // When we find a check prefix, keep track of whether we find CHECK: or
165 bool IsCheckNext = false, IsCheckNot = false;
167 // Verify that the : is present after the prefix.
168 if (Buffer[CheckPrefix.size()] == ':') {
169 Buffer = Buffer.substr(CheckPrefix.size()+1);
170 } else if (Buffer.size() > CheckPrefix.size()+6 &&
171 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
172 Buffer = Buffer.substr(CheckPrefix.size()+7);
174 } else if (Buffer.size() > CheckPrefix.size()+5 &&
175 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
176 Buffer = Buffer.substr(CheckPrefix.size()+6);
179 Buffer = Buffer.substr(1);
183 // Okay, we found the prefix, yay. Remember the rest of the line, but
184 // ignore leading and trailing whitespace.
185 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
187 // Scan ahead to the end of line.
188 size_t EOL = Buffer.find_first_of("\n\r");
190 // Parse the pattern.
192 if (P.ParsePattern(Buffer.substr(0, EOL), SM))
195 Buffer = Buffer.substr(EOL);
198 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
199 if (IsCheckNext && CheckStrings.empty()) {
200 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
201 "found '"+CheckPrefix+"-NEXT:' without previous '"+
202 CheckPrefix+ ": line", "error");
208 NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
214 // Okay, add the string we captured to the output vector and move on.
215 CheckStrings.push_back(CheckString(P,
216 SMLoc::getFromPointer(Buffer.data()),
218 std::swap(NotMatches, CheckStrings.back().NotStrings);
221 if (CheckStrings.empty()) {
222 errs() << "error: no check strings found with prefix '" << CheckPrefix
227 if (!NotMatches.empty()) {
228 errs() << "error: '" << CheckPrefix
229 << "-NOT:' not supported after last check line.\n";
236 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
237 /// memory buffer, free it, and return a new one.
238 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
239 SmallVector<char, 16> NewFile;
240 NewFile.reserve(MB->getBufferSize());
242 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
244 // If C is not a horizontal whitespace, skip it.
245 if (*Ptr != ' ' && *Ptr != '\t') {
246 NewFile.push_back(*Ptr);
250 // Otherwise, add one space and advance over neighboring space.
251 NewFile.push_back(' ');
252 while (Ptr+1 != End &&
253 (Ptr[1] == ' ' || Ptr[1] == '\t'))
257 // Free the old buffer and return a new one.
259 MemoryBuffer::getMemBufferCopy(NewFile.data(),
260 NewFile.data() + NewFile.size(),
261 MB->getBufferIdentifier());
268 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
270 // Otherwise, we have an error, emit an error message.
271 SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
274 // Print the "scanning from here" line. If the current position is at the
275 // end of a line, advance to the start of the next line.
276 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
278 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
282 /// CountNumNewlinesBetween - Count the number of newlines in the specified
284 static unsigned CountNumNewlinesBetween(StringRef Range) {
285 unsigned NumNewLines = 0;
288 Range = Range.substr(Range.find_first_of("\n\r"));
289 if (Range.empty()) return NumNewLines;
293 // Handle \n\r and \r\n as a single newline.
294 if (Range.size() > 1 &&
295 (Range[1] == '\n' || Range[1] == '\r') &&
296 (Range[0] != Range[1]))
297 Range = Range.substr(1);
298 Range = Range.substr(1);
302 int main(int argc, char **argv) {
303 sys::PrintStackTraceOnErrorSignal();
304 PrettyStackTraceProgram X(argc, argv);
305 cl::ParseCommandLineOptions(argc, argv);
309 // Read the expected strings from the check file.
310 std::vector<CheckString> CheckStrings;
311 if (ReadCheckFile(SM, CheckStrings))
314 // Open the file to check and add it to SourceMgr.
315 std::string ErrorStr;
317 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
319 errs() << "Could not open input file '" << InputFilename << "': "
324 // Remove duplicate spaces in the input file if requested.
325 if (!NoCanonicalizeWhiteSpace)
326 F = CanonicalizeInputFile(F);
328 SM.AddNewSourceBuffer(F, SMLoc());
330 // Check that we have all of the expected strings, in order, in the input
332 StringRef Buffer = F->getBuffer();
334 const char *LastMatch = Buffer.data();
336 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
337 const CheckString &CheckStr = CheckStrings[StrNo];
339 StringRef SearchFrom = Buffer;
341 // Find StrNo in the file.
343 Buffer = Buffer.substr(CheckStr.Pat.Match(Buffer, MatchLen));
345 // If we didn't find a match, reject the input.
346 if (Buffer.empty()) {
347 PrintCheckFailed(SM, CheckStr, SearchFrom);
351 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
353 // If this check is a "CHECK-NEXT", verify that the previous match was on
354 // the previous line (i.e. that there is one newline between them).
355 if (CheckStr.IsCheckNext) {
356 // Count the number of newlines between the previous match and this one.
357 assert(LastMatch != F->getBufferStart() &&
358 "CHECK-NEXT can't be the first check in a file");
360 unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
361 if (NumNewLines == 0) {
362 SM.PrintMessage(CheckStr.Loc,
363 CheckPrefix+"-NEXT: is on the same line as previous match",
365 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
366 "'next' match was here", "note");
367 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
368 "previous match was here", "note");
372 if (NumNewLines != 1) {
373 SM.PrintMessage(CheckStr.Loc,
375 "-NEXT: is not on the line after the previous match",
377 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
378 "'next' match was here", "note");
379 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
380 "previous match was here", "note");
385 // If this match had "not strings", verify that they don't exist in the
387 for (unsigned i = 0, e = CheckStr.NotStrings.size(); i != e; ++i) {
389 size_t Pos = CheckStr.NotStrings[i].second.Match(SkippedRegion, MatchLen);
390 if (Pos == StringRef::npos) continue;
392 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
393 CheckPrefix+"-NOT: string occurred!", "error");
394 SM.PrintMessage(CheckStr.NotStrings[i].first,
395 CheckPrefix+"-NOT: pattern specified here", "note");
400 // Otherwise, everything is good. Step over the matched text and remember
401 // the position after the match as the end of the last match.
402 Buffer = Buffer.substr(MatchLen);
403 LastMatch = Buffer.data();