FileCheck.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  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.
  12. //
  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.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Support/CommandLine.h"
  19. #include "llvm/Support/MemoryBuffer.h"
  20. #include "llvm/Support/PrettyStackTrace.h"
  21. #include "llvm/Support/Regex.h"
  22. #include "llvm/Support/SourceMgr.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include "llvm/System/Signals.h"
  25. using namespace llvm;
  26. static cl::opt<std::string>
  27. CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
  28. static cl::opt<std::string>
  29. InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
  30. cl::init("-"), cl::value_desc("filename"));
  31. static cl::opt<std::string>
  32. CheckPrefix("check-prefix", cl::init("CHECK"),
  33. cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
  34. static cl::opt<bool>
  35. NoCanonicalizeWhiteSpace("strict-whitespace",
  36. cl::desc("Do not treat all horizontal whitespace as equivalent"));
  37. //===----------------------------------------------------------------------===//
  38. // Pattern Handling Code.
  39. //===----------------------------------------------------------------------===//
  40. class Pattern {
  41. /// Chunks - The pattern chunks to match. If the bool is false, it is a fixed
  42. /// string match, if it is true, it is a regex match.
  43. SmallVector<std::pair<StringRef, bool>, 4> Chunks;
  44. public:
  45. Pattern() { }
  46. bool ParsePattern(StringRef PatternStr, SourceMgr &SM);
  47. /// Match - Match the pattern string against the input buffer Buffer. This
  48. /// returns the position that is matched or npos if there is no match. If
  49. /// there is a match, the size of the matched string is returned in MatchLen.
  50. size_t Match(StringRef Buffer, size_t &MatchLen) const;
  51. };
  52. bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM) {
  53. // Ignore trailing whitespace.
  54. while (!PatternStr.empty() &&
  55. (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
  56. PatternStr = PatternStr.substr(0, PatternStr.size()-1);
  57. // Check that there is something on the line.
  58. if (PatternStr.empty()) {
  59. SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
  60. "found empty check string with prefix '"+CheckPrefix+":'",
  61. "error");
  62. return true;
  63. }
  64. // Scan the pattern to break it into regex and non-regex pieces.
  65. while (!PatternStr.empty()) {
  66. // Handle fixed string matches.
  67. if (PatternStr.size() < 2 ||
  68. PatternStr[0] != '{' || PatternStr[1] != '{') {
  69. // Find the end, which is the start of the next regex.
  70. size_t FixedMatchEnd = PatternStr.find("{{");
  71. Chunks.push_back(std::make_pair(PatternStr.substr(0, FixedMatchEnd),
  72. false));
  73. PatternStr = PatternStr.substr(FixedMatchEnd);
  74. continue;
  75. }
  76. // Otherwise, this is the start of a regex match. Scan for the }}.
  77. size_t End = PatternStr.find("}}");
  78. if (End == StringRef::npos) {
  79. SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
  80. "found start of regex string with no end '}}'", "error");
  81. return true;
  82. }
  83. Regex R(PatternStr.substr(2, End-2));
  84. std::string Error;
  85. if (!R.isValid(Error)) {
  86. SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()+2),
  87. "invalid regex: " + Error, "error");
  88. return true;
  89. }
  90. Chunks.push_back(std::make_pair(PatternStr.substr(2, End-2), true));
  91. PatternStr = PatternStr.substr(End+2);
  92. }
  93. return false;
  94. }
  95. /// Match - Match the pattern string against the input buffer Buffer. This
  96. /// returns the position that is matched or npos if there is no match. If
  97. /// there is a match, the size of the matched string is returned in MatchLen.
  98. size_t Pattern::Match(StringRef Buffer, size_t &MatchLen) const {
  99. size_t FirstMatch = StringRef::npos;
  100. MatchLen = 0;
  101. SmallVector<StringRef, 4> MatchInfo;
  102. while (!Buffer.empty()) {
  103. StringRef MatchAttempt = Buffer;
  104. unsigned ChunkNo = 0, e = Chunks.size();
  105. for (; ChunkNo != e; ++ChunkNo) {
  106. StringRef PatternStr = Chunks[ChunkNo].first;
  107. size_t ThisMatch = StringRef::npos;
  108. size_t ThisLength = StringRef::npos;
  109. if (!Chunks[ChunkNo].second) {
  110. // Fixed string match.
  111. ThisMatch = MatchAttempt.find(Chunks[ChunkNo].first);
  112. ThisLength = Chunks[ChunkNo].first.size();
  113. } else if (Regex(Chunks[ChunkNo].first, Regex::Sub).match(MatchAttempt, &MatchInfo)) {
  114. // Successful regex match.
  115. assert(!MatchInfo.empty() && "Didn't get any match");
  116. StringRef FullMatch = MatchInfo[0];
  117. MatchInfo.clear();
  118. ThisMatch = FullMatch.data()-MatchAttempt.data();
  119. ThisLength = FullMatch.size();
  120. }
  121. // Otherwise, what we do depends on if this is the first match or not. If
  122. // this is the first match, it doesn't match to match at the start of
  123. // MatchAttempt.
  124. if (ChunkNo == 0) {
  125. // If the first match fails then this pattern will never match in
  126. // Buffer.
  127. if (ThisMatch == StringRef::npos)
  128. return ThisMatch;
  129. FirstMatch = ThisMatch;
  130. MatchAttempt = MatchAttempt.substr(FirstMatch);
  131. ThisMatch = 0;
  132. }
  133. // If this chunk didn't match, then the entire pattern didn't match from
  134. // FirstMatch, try later in the buffer.
  135. if (ThisMatch == StringRef::npos)
  136. break;
  137. // Ok, if the match didn't match at the beginning of MatchAttempt, then we
  138. // have something like "ABC{{DEF}} and something was in-between. Reject
  139. // the match.
  140. if (ThisMatch != 0)
  141. break;
  142. // Otherwise, match the string and move to the next chunk.
  143. MatchLen += ThisLength;
  144. MatchAttempt = MatchAttempt.substr(ThisLength);
  145. }
  146. // If the whole thing matched, we win.
  147. if (ChunkNo == e)
  148. return FirstMatch;
  149. // Otherwise, try matching again after FirstMatch to see if this pattern
  150. // matches later in the buffer.
  151. Buffer = Buffer.substr(FirstMatch+1);
  152. }
  153. // If we ran out of stuff to scan, then we didn't match.
  154. return StringRef::npos;
  155. }
  156. //===----------------------------------------------------------------------===//
  157. // Check Strings.
  158. //===----------------------------------------------------------------------===//
  159. /// CheckString - This is a check that we found in the input file.
  160. struct CheckString {
  161. /// Pat - The pattern to match.
  162. Pattern Pat;
  163. /// Loc - The location in the match file that the check string was specified.
  164. SMLoc Loc;
  165. /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
  166. /// to a CHECK: directive.
  167. bool IsCheckNext;
  168. /// NotStrings - These are all of the strings that are disallowed from
  169. /// occurring between this match string and the previous one (or start of
  170. /// file).
  171. std::vector<std::pair<SMLoc, Pattern> > NotStrings;
  172. CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
  173. : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
  174. };
  175. /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
  176. /// memory buffer, free it, and return a new one.
  177. static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
  178. SmallVector<char, 16> NewFile;
  179. NewFile.reserve(MB->getBufferSize());
  180. for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
  181. Ptr != End; ++Ptr) {
  182. // If C is not a horizontal whitespace, skip it.
  183. if (*Ptr != ' ' && *Ptr != '\t') {
  184. NewFile.push_back(*Ptr);
  185. continue;
  186. }
  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'))
  191. ++Ptr;
  192. }
  193. // Free the old buffer and return a new one.
  194. MemoryBuffer *MB2 =
  195. MemoryBuffer::getMemBufferCopy(NewFile.data(),
  196. NewFile.data() + NewFile.size(),
  197. MB->getBufferIdentifier());
  198. delete MB;
  199. return MB2;
  200. }
  201. /// ReadCheckFile - Read the check file, which specifies the sequence of
  202. /// expected strings. The strings are added to the CheckStrings vector.
  203. static bool ReadCheckFile(SourceMgr &SM,
  204. std::vector<CheckString> &CheckStrings) {
  205. // Open the check file, and tell SourceMgr about it.
  206. std::string ErrorStr;
  207. MemoryBuffer *F =
  208. MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
  209. if (F == 0) {
  210. errs() << "Could not open check file '" << CheckFilename << "': "
  211. << ErrorStr << '\n';
  212. return true;
  213. }
  214. // If we want to canonicalize whitespace, strip excess whitespace from the
  215. // buffer containing the CHECK lines.
  216. if (!NoCanonicalizeWhiteSpace)
  217. F = CanonicalizeInputFile(F);
  218. SM.AddNewSourceBuffer(F, SMLoc());
  219. // Find all instances of CheckPrefix followed by : in the file.
  220. StringRef Buffer = F->getBuffer();
  221. std::vector<std::pair<SMLoc, Pattern> > NotMatches;
  222. while (1) {
  223. // See if Prefix occurs in the memory buffer.
  224. Buffer = Buffer.substr(Buffer.find(CheckPrefix));
  225. // If we didn't find a match, we're done.
  226. if (Buffer.empty())
  227. break;
  228. const char *CheckPrefixStart = Buffer.data();
  229. // When we find a check prefix, keep track of whether we find CHECK: or
  230. // CHECK-NEXT:
  231. bool IsCheckNext = false, IsCheckNot = false;
  232. // Verify that the : is present after the prefix.
  233. if (Buffer[CheckPrefix.size()] == ':') {
  234. Buffer = Buffer.substr(CheckPrefix.size()+1);
  235. } else if (Buffer.size() > CheckPrefix.size()+6 &&
  236. memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
  237. Buffer = Buffer.substr(CheckPrefix.size()+7);
  238. IsCheckNext = true;
  239. } else if (Buffer.size() > CheckPrefix.size()+5 &&
  240. memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
  241. Buffer = Buffer.substr(CheckPrefix.size()+6);
  242. IsCheckNot = true;
  243. } else {
  244. Buffer = Buffer.substr(1);
  245. continue;
  246. }
  247. // Okay, we found the prefix, yay. Remember the rest of the line, but
  248. // ignore leading and trailing whitespace.
  249. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
  250. // Scan ahead to the end of line.
  251. size_t EOL = Buffer.find_first_of("\n\r");
  252. // Parse the pattern.
  253. Pattern P;
  254. if (P.ParsePattern(Buffer.substr(0, EOL), SM))
  255. return true;
  256. Buffer = Buffer.substr(EOL);
  257. // Verify that CHECK-NEXT lines have at least one CHECK line before them.
  258. if (IsCheckNext && CheckStrings.empty()) {
  259. SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
  260. "found '"+CheckPrefix+"-NEXT:' without previous '"+
  261. CheckPrefix+ ": line", "error");
  262. return true;
  263. }
  264. // Handle CHECK-NOT.
  265. if (IsCheckNot) {
  266. NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
  267. P));
  268. continue;
  269. }
  270. // Okay, add the string we captured to the output vector and move on.
  271. CheckStrings.push_back(CheckString(P,
  272. SMLoc::getFromPointer(Buffer.data()),
  273. IsCheckNext));
  274. std::swap(NotMatches, CheckStrings.back().NotStrings);
  275. }
  276. if (CheckStrings.empty()) {
  277. errs() << "error: no check strings found with prefix '" << CheckPrefix
  278. << ":'\n";
  279. return true;
  280. }
  281. if (!NotMatches.empty()) {
  282. errs() << "error: '" << CheckPrefix
  283. << "-NOT:' not supported after last check line.\n";
  284. return true;
  285. }
  286. return false;
  287. }
  288. static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
  289. StringRef Buffer) {
  290. // Otherwise, we have an error, emit an error message.
  291. SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
  292. "error");
  293. // Print the "scanning from here" line. If the current position is at the
  294. // end of a line, advance to the start of the next line.
  295. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
  296. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
  297. "note");
  298. }
  299. /// CountNumNewlinesBetween - Count the number of newlines in the specified
  300. /// range.
  301. static unsigned CountNumNewlinesBetween(StringRef Range) {
  302. unsigned NumNewLines = 0;
  303. while (1) {
  304. // Scan for newline.
  305. Range = Range.substr(Range.find_first_of("\n\r"));
  306. if (Range.empty()) return NumNewLines;
  307. ++NumNewLines;
  308. // Handle \n\r and \r\n as a single newline.
  309. if (Range.size() > 1 &&
  310. (Range[1] == '\n' || Range[1] == '\r') &&
  311. (Range[0] != Range[1]))
  312. Range = Range.substr(1);
  313. Range = Range.substr(1);
  314. }
  315. }
  316. int main(int argc, char **argv) {
  317. sys::PrintStackTraceOnErrorSignal();
  318. PrettyStackTraceProgram X(argc, argv);
  319. cl::ParseCommandLineOptions(argc, argv);
  320. SourceMgr SM;
  321. // Read the expected strings from the check file.
  322. std::vector<CheckString> CheckStrings;
  323. if (ReadCheckFile(SM, CheckStrings))
  324. return 2;
  325. // Open the file to check and add it to SourceMgr.
  326. std::string ErrorStr;
  327. MemoryBuffer *F =
  328. MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
  329. if (F == 0) {
  330. errs() << "Could not open input file '" << InputFilename << "': "
  331. << ErrorStr << '\n';
  332. return true;
  333. }
  334. // Remove duplicate spaces in the input file if requested.
  335. if (!NoCanonicalizeWhiteSpace)
  336. F = CanonicalizeInputFile(F);
  337. SM.AddNewSourceBuffer(F, SMLoc());
  338. // Check that we have all of the expected strings, in order, in the input
  339. // file.
  340. StringRef Buffer = F->getBuffer();
  341. const char *LastMatch = Buffer.data();
  342. for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
  343. const CheckString &CheckStr = CheckStrings[StrNo];
  344. StringRef SearchFrom = Buffer;
  345. // Find StrNo in the file.
  346. size_t MatchLen = 0;
  347. Buffer = Buffer.substr(CheckStr.Pat.Match(Buffer, MatchLen));
  348. // If we didn't find a match, reject the input.
  349. if (Buffer.empty()) {
  350. PrintCheckFailed(SM, CheckStr, SearchFrom);
  351. return 1;
  352. }
  353. StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
  354. // If this check is a "CHECK-NEXT", verify that the previous match was on
  355. // the previous line (i.e. that there is one newline between them).
  356. if (CheckStr.IsCheckNext) {
  357. // Count the number of newlines between the previous match and this one.
  358. assert(LastMatch != F->getBufferStart() &&
  359. "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",
  364. "error");
  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");
  369. return 1;
  370. }
  371. if (NumNewLines != 1) {
  372. SM.PrintMessage(CheckStr.Loc,
  373. CheckPrefix+
  374. "-NEXT: is not on the line after the previous match",
  375. "error");
  376. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
  377. "'next' match was here", "note");
  378. SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
  379. "previous match was here", "note");
  380. return 1;
  381. }
  382. }
  383. // If this match had "not strings", verify that they don't exist in the
  384. // skipped region.
  385. for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size(); ChunkNo != e; ++ChunkNo) {
  386. size_t MatchLen = 0;
  387. size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion, MatchLen);
  388. if (Pos == StringRef::npos) continue;
  389. SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
  390. CheckPrefix+"-NOT: string occurred!", "error");
  391. SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first,
  392. CheckPrefix+"-NOT: pattern specified here", "note");
  393. return 1;
  394. }
  395. // Otherwise, everything is good. Step over the matched text and remember
  396. // the position after the match as the end of the last match.
  397. Buffer = Buffer.substr(MatchLen);
  398. LastMatch = Buffer.data();
  399. }
  400. return 0;
  401. }