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 //===----------------------------------------------------------------------===//
51 /// FixedStr - If non-empty, this pattern is a fixed string match with the
52 /// specified fixed string.
55 /// RegEx - If non-empty, this is a regex pattern.
61 bool ParsePattern(StringRef PatternStr, SourceMgr &SM);
63 /// Match - Match the pattern string against the input buffer Buffer. This
64 /// returns the position that is matched or npos if there is no match. If
65 /// there is a match, the size of the matched string is returned in MatchLen.
66 size_t Match(StringRef Buffer, size_t &MatchLen) const;
69 void AddFixedStringToRegEx(StringRef FixedStr);
72 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM) {
74 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
76 // Ignore trailing whitespace.
77 while (!PatternStr.empty() &&
78 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
79 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
81 // Check that there is something on the line.
82 if (PatternStr.empty()) {
83 SM.PrintMessage(PatternLoc, "found empty check string with prefix '" +
84 CheckPrefix+":'", "error");
88 // Check to see if this is a fixed string, or if it has regex pieces.
89 if (PatternStr.size() < 2 || PatternStr.find("{{") == StringRef::npos) {
90 FixedStr = PatternStr;
94 // Otherwise, there is at least one regex piece. Build up the regex pattern
95 // by escaping scary characters in fixed strings, building up one big regex.
96 while (!PatternStr.empty()) {
97 // Handle fixed string matches.
98 if (PatternStr.size() < 2 ||
99 PatternStr[0] != '{' || PatternStr[1] != '{') {
100 // Find the end, which is the start of the next regex.
101 size_t FixedMatchEnd = PatternStr.find("{{");
102 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd));
103 PatternStr = PatternStr.substr(FixedMatchEnd);
107 // Otherwise, this is the start of a regex match. Scan for the }}.
108 size_t End = PatternStr.find("}}");
109 if (End == StringRef::npos) {
110 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
111 "found start of regex string with no end '}}'", "error");
115 StringRef RegexStr = PatternStr.substr(2, End-2);
118 if (!R.isValid(Error)) {
119 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()+2),
120 "invalid regex: " + Error, "error");
124 RegExStr += RegexStr.str();
125 PatternStr = PatternStr.substr(End+2);
131 void Pattern::AddFixedStringToRegEx(StringRef FixedStr) {
132 // Add the characters from FixedStr to the regex, escaping as needed. This
133 // avoids "leaning toothpicks" in common patterns.
134 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
135 switch (FixedStr[i]) {
136 // These are the special characters matched in "p_ere_exp".
152 RegExStr += FixedStr[i];
159 /// Match - Match the pattern string against the input buffer Buffer. This
160 /// returns the position that is matched or npos if there is no match. If
161 /// there is a match, the size of the matched string is returned in MatchLen.
162 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen) const {
163 // If this is a fixed string pattern, just match it now.
164 if (!FixedStr.empty()) {
165 MatchLen = FixedStr.size();
166 return Buffer.find(FixedStr);
170 SmallVector<StringRef, 4> MatchInfo;
171 if (!Regex(RegExStr, Regex::Sub|Regex::Newline).match(Buffer, &MatchInfo))
172 return StringRef::npos;
174 // Successful regex match.
175 assert(!MatchInfo.empty() && "Didn't get any match");
176 StringRef FullMatch = MatchInfo[0];
179 if (MatchInfo.size() != 1) {
180 SM->PrintMessage(PatternLoc, "regex cannot use grouping parens", "error");
185 MatchLen = FullMatch.size();
186 return FullMatch.data()-Buffer.data();
190 //===----------------------------------------------------------------------===//
192 //===----------------------------------------------------------------------===//
194 /// CheckString - This is a check that we found in the input file.
196 /// Pat - The pattern to match.
199 /// Loc - The location in the match file that the check string was specified.
202 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
203 /// to a CHECK: directive.
206 /// NotStrings - These are all of the strings that are disallowed from
207 /// occurring between this match string and the previous one (or start of
209 std::vector<std::pair<SMLoc, Pattern> > NotStrings;
211 CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
212 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
215 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
216 /// memory buffer, free it, and return a new one.
217 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
218 SmallVector<char, 16> NewFile;
219 NewFile.reserve(MB->getBufferSize());
221 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
223 // If C is not a horizontal whitespace, skip it.
224 if (*Ptr != ' ' && *Ptr != '\t') {
225 NewFile.push_back(*Ptr);
229 // Otherwise, add one space and advance over neighboring space.
230 NewFile.push_back(' ');
231 while (Ptr+1 != End &&
232 (Ptr[1] == ' ' || Ptr[1] == '\t'))
236 // Free the old buffer and return a new one.
238 MemoryBuffer::getMemBufferCopy(NewFile.data(),
239 NewFile.data() + NewFile.size(),
240 MB->getBufferIdentifier());
247 /// ReadCheckFile - Read the check file, which specifies the sequence of
248 /// expected strings. The strings are added to the CheckStrings vector.
249 static bool ReadCheckFile(SourceMgr &SM,
250 std::vector<CheckString> &CheckStrings) {
251 // Open the check file, and tell SourceMgr about it.
252 std::string ErrorStr;
254 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
256 errs() << "Could not open check file '" << CheckFilename << "': "
261 // If we want to canonicalize whitespace, strip excess whitespace from the
262 // buffer containing the CHECK lines.
263 if (!NoCanonicalizeWhiteSpace)
264 F = CanonicalizeInputFile(F);
266 SM.AddNewSourceBuffer(F, SMLoc());
268 // Find all instances of CheckPrefix followed by : in the file.
269 StringRef Buffer = F->getBuffer();
271 std::vector<std::pair<SMLoc, Pattern> > NotMatches;
274 // See if Prefix occurs in the memory buffer.
275 Buffer = Buffer.substr(Buffer.find(CheckPrefix));
277 // If we didn't find a match, we're done.
281 const char *CheckPrefixStart = Buffer.data();
283 // When we find a check prefix, keep track of whether we find CHECK: or
285 bool IsCheckNext = false, IsCheckNot = false;
287 // Verify that the : is present after the prefix.
288 if (Buffer[CheckPrefix.size()] == ':') {
289 Buffer = Buffer.substr(CheckPrefix.size()+1);
290 } else if (Buffer.size() > CheckPrefix.size()+6 &&
291 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
292 Buffer = Buffer.substr(CheckPrefix.size()+7);
294 } else if (Buffer.size() > CheckPrefix.size()+5 &&
295 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
296 Buffer = Buffer.substr(CheckPrefix.size()+6);
299 Buffer = Buffer.substr(1);
303 // Okay, we found the prefix, yay. Remember the rest of the line, but
304 // ignore leading and trailing whitespace.
305 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
307 // Scan ahead to the end of line.
308 size_t EOL = Buffer.find_first_of("\n\r");
310 // Parse the pattern.
312 if (P.ParsePattern(Buffer.substr(0, EOL), SM))
315 Buffer = Buffer.substr(EOL);
318 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
319 if (IsCheckNext && CheckStrings.empty()) {
320 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
321 "found '"+CheckPrefix+"-NEXT:' without previous '"+
322 CheckPrefix+ ": line", "error");
328 NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
334 // Okay, add the string we captured to the output vector and move on.
335 CheckStrings.push_back(CheckString(P,
336 SMLoc::getFromPointer(Buffer.data()),
338 std::swap(NotMatches, CheckStrings.back().NotStrings);
341 if (CheckStrings.empty()) {
342 errs() << "error: no check strings found with prefix '" << CheckPrefix
347 if (!NotMatches.empty()) {
348 errs() << "error: '" << CheckPrefix
349 << "-NOT:' not supported after last check line.\n";
356 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
358 // Otherwise, we have an error, emit an error message.
359 SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
362 // Print the "scanning from here" line. If the current position is at the
363 // end of a line, advance to the start of the next line.
364 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
366 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
370 /// CountNumNewlinesBetween - Count the number of newlines in the specified
372 static unsigned CountNumNewlinesBetween(StringRef Range) {
373 unsigned NumNewLines = 0;
376 Range = Range.substr(Range.find_first_of("\n\r"));
377 if (Range.empty()) return NumNewLines;
381 // Handle \n\r and \r\n as a single newline.
382 if (Range.size() > 1 &&
383 (Range[1] == '\n' || Range[1] == '\r') &&
384 (Range[0] != Range[1]))
385 Range = Range.substr(1);
386 Range = Range.substr(1);
390 int main(int argc, char **argv) {
391 sys::PrintStackTraceOnErrorSignal();
392 PrettyStackTraceProgram X(argc, argv);
393 cl::ParseCommandLineOptions(argc, argv);
397 // Read the expected strings from the check file.
398 std::vector<CheckString> CheckStrings;
399 if (ReadCheckFile(SM, CheckStrings))
402 // Open the file to check and add it to SourceMgr.
403 std::string ErrorStr;
405 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
407 errs() << "Could not open input file '" << InputFilename << "': "
412 // Remove duplicate spaces in the input file if requested.
413 if (!NoCanonicalizeWhiteSpace)
414 F = CanonicalizeInputFile(F);
416 SM.AddNewSourceBuffer(F, SMLoc());
418 // Check that we have all of the expected strings, in order, in the input
420 StringRef Buffer = F->getBuffer();
422 const char *LastMatch = Buffer.data();
424 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
425 const CheckString &CheckStr = CheckStrings[StrNo];
427 StringRef SearchFrom = Buffer;
429 // Find StrNo in the file.
431 Buffer = Buffer.substr(CheckStr.Pat.Match(Buffer, MatchLen));
433 // If we didn't find a match, reject the input.
434 if (Buffer.empty()) {
435 PrintCheckFailed(SM, CheckStr, SearchFrom);
439 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
441 // If this check is a "CHECK-NEXT", verify that the previous match was on
442 // the previous line (i.e. that there is one newline between them).
443 if (CheckStr.IsCheckNext) {
444 // Count the number of newlines between the previous match and this one.
445 assert(LastMatch != F->getBufferStart() &&
446 "CHECK-NEXT can't be the first check in a file");
448 unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
449 if (NumNewLines == 0) {
450 SM.PrintMessage(CheckStr.Loc,
451 CheckPrefix+"-NEXT: is on the same line as 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");
460 if (NumNewLines != 1) {
461 SM.PrintMessage(CheckStr.Loc,
463 "-NEXT: is not on the line after the previous match",
465 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
466 "'next' match was here", "note");
467 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
468 "previous match was here", "note");
473 // If this match had "not strings", verify that they don't exist in the
475 for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size(); ChunkNo != e; ++ChunkNo) {
477 size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion, MatchLen);
478 if (Pos == StringRef::npos) continue;
480 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
481 CheckPrefix+"-NOT: string occurred!", "error");
482 SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first,
483 CheckPrefix+"-NOT: pattern specified here", "note");
488 // Otherwise, everything is good. Step over the matched text and remember
489 // the position after the match as the end of the last match.
490 Buffer = Buffer.substr(MatchLen);
491 LastMatch = Buffer.data();