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/Regex.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/System/Signals.h"
28 static cl::opt<std::string>
29 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
31 static cl::opt<std::string>
32 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
33 cl::init("-"), cl::value_desc("filename"));
35 static cl::opt<std::string>
36 CheckPrefix("check-prefix", cl::init("CHECK"),
37 cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
40 NoCanonicalizeWhiteSpace("strict-whitespace",
41 cl::desc("Do not treat all horizontal whitespace as equivalent"));
43 //===----------------------------------------------------------------------===//
44 // Pattern Handling Code.
45 //===----------------------------------------------------------------------===//
48 /// FixedStr - If non-empty, this pattern is a fixed string match with the
49 /// specified fixed string.
52 /// RegEx - If non-empty, this is a regex pattern.
58 bool ParsePattern(StringRef PatternStr, SourceMgr &SM);
60 /// Match - Match the pattern string against the input buffer Buffer. This
61 /// returns the position that is matched or npos if there is no match. If
62 /// there is a match, the size of the matched string is returned in MatchLen.
63 size_t Match(StringRef Buffer, size_t &MatchLen) const;
66 void AddFixedStringToRegEx(StringRef FixedStr);
69 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM) {
70 // Ignore trailing whitespace.
71 while (!PatternStr.empty() &&
72 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
73 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
75 // Check that there is something on the line.
76 if (PatternStr.empty()) {
77 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
78 "found empty check string with prefix '"+CheckPrefix+":'",
83 // Check to see if this is a fixed string, or if it has regex pieces.
84 if (PatternStr.size() < 2 || PatternStr.find("{{") == StringRef::npos) {
85 FixedStr = PatternStr;
89 // Otherwise, there is at least one regex piece. Build up the regex pattern
90 // by escaping scary characters in fixed strings, building up one big regex.
91 while (!PatternStr.empty()) {
92 // Handle fixed string matches.
93 if (PatternStr.size() < 2 ||
94 PatternStr[0] != '{' || PatternStr[1] != '{') {
95 // Find the end, which is the start of the next regex.
96 size_t FixedMatchEnd = PatternStr.find("{{");
97 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd));
98 PatternStr = PatternStr.substr(FixedMatchEnd);
102 // Otherwise, this is the start of a regex match. Scan for the }}.
103 size_t End = PatternStr.find("}}");
104 if (End == StringRef::npos) {
105 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
106 "found start of regex string with no end '}}'", "error");
110 StringRef RegexStr = PatternStr.substr(2, End-2);
113 if (!R.isValid(Error)) {
114 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()+2),
115 "invalid regex: " + Error, "error");
119 RegExStr += RegexStr.str();
120 PatternStr = PatternStr.substr(End+2);
126 void Pattern::AddFixedStringToRegEx(StringRef FixedStr) {
127 // Add the characters from FixedStr to the regex, escaping as needed. This
128 // avoids "leaning toothpicks" in common patterns.
129 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
130 switch (FixedStr[i]) {
131 // These are the special characters matched in "p_ere_exp".
147 RegExStr += FixedStr[i];
154 /// Match - Match the pattern string against the input buffer Buffer. This
155 /// returns the position that is matched or npos if there is no match. If
156 /// there is a match, the size of the matched string is returned in MatchLen.
157 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen) const {
158 // If this is a fixed string pattern, just match it now.
159 if (!FixedStr.empty()) {
160 MatchLen = FixedStr.size();
161 return Buffer.find(FixedStr);
165 SmallVector<StringRef, 4> MatchInfo;
166 if (!Regex(RegExStr, Regex::Sub|Regex::Newline).match(Buffer, &MatchInfo))
167 return StringRef::npos;
169 // Successful regex match.
170 assert(!MatchInfo.empty() && "Didn't get any match");
171 StringRef FullMatch = MatchInfo[0];
173 MatchLen = FullMatch.size();
174 return FullMatch.data()-Buffer.data();
178 //===----------------------------------------------------------------------===//
180 //===----------------------------------------------------------------------===//
182 /// CheckString - This is a check that we found in the input file.
184 /// Pat - The pattern to match.
187 /// Loc - The location in the match file that the check string was specified.
190 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
191 /// to a CHECK: directive.
194 /// NotStrings - These are all of the strings that are disallowed from
195 /// occurring between this match string and the previous one (or start of
197 std::vector<std::pair<SMLoc, Pattern> > NotStrings;
199 CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
200 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
203 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
204 /// memory buffer, free it, and return a new one.
205 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
206 SmallVector<char, 16> NewFile;
207 NewFile.reserve(MB->getBufferSize());
209 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
211 // If C is not a horizontal whitespace, skip it.
212 if (*Ptr != ' ' && *Ptr != '\t') {
213 NewFile.push_back(*Ptr);
217 // Otherwise, add one space and advance over neighboring space.
218 NewFile.push_back(' ');
219 while (Ptr+1 != End &&
220 (Ptr[1] == ' ' || Ptr[1] == '\t'))
224 // Free the old buffer and return a new one.
226 MemoryBuffer::getMemBufferCopy(NewFile.data(),
227 NewFile.data() + NewFile.size(),
228 MB->getBufferIdentifier());
235 /// ReadCheckFile - Read the check file, which specifies the sequence of
236 /// expected strings. The strings are added to the CheckStrings vector.
237 static bool ReadCheckFile(SourceMgr &SM,
238 std::vector<CheckString> &CheckStrings) {
239 // Open the check file, and tell SourceMgr about it.
240 std::string ErrorStr;
242 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
244 errs() << "Could not open check file '" << CheckFilename << "': "
249 // If we want to canonicalize whitespace, strip excess whitespace from the
250 // buffer containing the CHECK lines.
251 if (!NoCanonicalizeWhiteSpace)
252 F = CanonicalizeInputFile(F);
254 SM.AddNewSourceBuffer(F, SMLoc());
256 // Find all instances of CheckPrefix followed by : in the file.
257 StringRef Buffer = F->getBuffer();
259 std::vector<std::pair<SMLoc, Pattern> > NotMatches;
262 // See if Prefix occurs in the memory buffer.
263 Buffer = Buffer.substr(Buffer.find(CheckPrefix));
265 // If we didn't find a match, we're done.
269 const char *CheckPrefixStart = Buffer.data();
271 // When we find a check prefix, keep track of whether we find CHECK: or
273 bool IsCheckNext = false, IsCheckNot = false;
275 // Verify that the : is present after the prefix.
276 if (Buffer[CheckPrefix.size()] == ':') {
277 Buffer = Buffer.substr(CheckPrefix.size()+1);
278 } else if (Buffer.size() > CheckPrefix.size()+6 &&
279 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
280 Buffer = Buffer.substr(CheckPrefix.size()+7);
282 } else if (Buffer.size() > CheckPrefix.size()+5 &&
283 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
284 Buffer = Buffer.substr(CheckPrefix.size()+6);
287 Buffer = Buffer.substr(1);
291 // Okay, we found the prefix, yay. Remember the rest of the line, but
292 // ignore leading and trailing whitespace.
293 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
295 // Scan ahead to the end of line.
296 size_t EOL = Buffer.find_first_of("\n\r");
298 // Parse the pattern.
300 if (P.ParsePattern(Buffer.substr(0, EOL), SM))
303 Buffer = Buffer.substr(EOL);
306 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
307 if (IsCheckNext && CheckStrings.empty()) {
308 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
309 "found '"+CheckPrefix+"-NEXT:' without previous '"+
310 CheckPrefix+ ": line", "error");
316 NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
322 // Okay, add the string we captured to the output vector and move on.
323 CheckStrings.push_back(CheckString(P,
324 SMLoc::getFromPointer(Buffer.data()),
326 std::swap(NotMatches, CheckStrings.back().NotStrings);
329 if (CheckStrings.empty()) {
330 errs() << "error: no check strings found with prefix '" << CheckPrefix
335 if (!NotMatches.empty()) {
336 errs() << "error: '" << CheckPrefix
337 << "-NOT:' not supported after last check line.\n";
344 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
346 // Otherwise, we have an error, emit an error message.
347 SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
350 // Print the "scanning from here" line. If the current position is at the
351 // end of a line, advance to the start of the next line.
352 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
354 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
358 /// CountNumNewlinesBetween - Count the number of newlines in the specified
360 static unsigned CountNumNewlinesBetween(StringRef Range) {
361 unsigned NumNewLines = 0;
364 Range = Range.substr(Range.find_first_of("\n\r"));
365 if (Range.empty()) return NumNewLines;
369 // Handle \n\r and \r\n as a single newline.
370 if (Range.size() > 1 &&
371 (Range[1] == '\n' || Range[1] == '\r') &&
372 (Range[0] != Range[1]))
373 Range = Range.substr(1);
374 Range = Range.substr(1);
378 int main(int argc, char **argv) {
379 sys::PrintStackTraceOnErrorSignal();
380 PrettyStackTraceProgram X(argc, argv);
381 cl::ParseCommandLineOptions(argc, argv);
385 // Read the expected strings from the check file.
386 std::vector<CheckString> CheckStrings;
387 if (ReadCheckFile(SM, CheckStrings))
390 // Open the file to check and add it to SourceMgr.
391 std::string ErrorStr;
393 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
395 errs() << "Could not open input file '" << InputFilename << "': "
400 // Remove duplicate spaces in the input file if requested.
401 if (!NoCanonicalizeWhiteSpace)
402 F = CanonicalizeInputFile(F);
404 SM.AddNewSourceBuffer(F, SMLoc());
406 // Check that we have all of the expected strings, in order, in the input
408 StringRef Buffer = F->getBuffer();
410 const char *LastMatch = Buffer.data();
412 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
413 const CheckString &CheckStr = CheckStrings[StrNo];
415 StringRef SearchFrom = Buffer;
417 // Find StrNo in the file.
419 Buffer = Buffer.substr(CheckStr.Pat.Match(Buffer, MatchLen));
421 // If we didn't find a match, reject the input.
422 if (Buffer.empty()) {
423 PrintCheckFailed(SM, CheckStr, SearchFrom);
427 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
429 // If this check is a "CHECK-NEXT", verify that the previous match was on
430 // the previous line (i.e. that there is one newline between them).
431 if (CheckStr.IsCheckNext) {
432 // Count the number of newlines between the previous match and this one.
433 assert(LastMatch != F->getBufferStart() &&
434 "CHECK-NEXT can't be the first check in a file");
436 unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
437 if (NumNewLines == 0) {
438 SM.PrintMessage(CheckStr.Loc,
439 CheckPrefix+"-NEXT: is on the same line as previous match",
441 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
442 "'next' match was here", "note");
443 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
444 "previous match was here", "note");
448 if (NumNewLines != 1) {
449 SM.PrintMessage(CheckStr.Loc,
451 "-NEXT: is not on the line after the previous match",
453 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
454 "'next' match was here", "note");
455 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
456 "previous match was here", "note");
461 // If this match had "not strings", verify that they don't exist in the
463 for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size(); ChunkNo != e; ++ChunkNo) {
465 size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion, MatchLen);
466 if (Pos == StringRef::npos) continue;
468 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
469 CheckPrefix+"-NOT: string occurred!", "error");
470 SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first,
471 CheckPrefix+"-NOT: pattern specified here", "note");
476 // Otherwise, everything is good. Step over the matched text and remember
477 // the position after the match as the end of the last match.
478 Buffer = Buffer.substr(MatchLen);
479 LastMatch = Buffer.data();