FileCheck.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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/ADT/OwningPtr.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringMap.h"
  22. #include "llvm/Support/CommandLine.h"
  23. #include "llvm/Support/MemoryBuffer.h"
  24. #include "llvm/Support/PrettyStackTrace.h"
  25. #include "llvm/Support/Regex.h"
  26. #include "llvm/Support/Signals.h"
  27. #include "llvm/Support/SourceMgr.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/Support/system_error.h"
  30. #include <algorithm>
  31. #include <map>
  32. #include <string>
  33. #include <vector>
  34. using namespace llvm;
  35. static cl::opt<std::string>
  36. CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
  37. static cl::opt<std::string>
  38. InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
  39. cl::init("-"), cl::value_desc("filename"));
  40. static cl::opt<std::string>
  41. CheckPrefix("check-prefix", cl::init("CHECK"),
  42. cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
  43. static cl::opt<bool>
  44. NoCanonicalizeWhiteSpace("strict-whitespace",
  45. cl::desc("Do not treat all horizontal whitespace as equivalent"));
  46. //===----------------------------------------------------------------------===//
  47. // Pattern Handling Code.
  48. //===----------------------------------------------------------------------===//
  49. class Pattern {
  50. SMLoc PatternLoc;
  51. /// MatchEOF - When set, this pattern only matches the end of file. This is
  52. /// used for trailing CHECK-NOTs.
  53. bool MatchEOF;
  54. /// FixedStr - If non-empty, this pattern is a fixed string match with the
  55. /// specified fixed string.
  56. StringRef FixedStr;
  57. /// RegEx - If non-empty, this is a regex pattern.
  58. std::string RegExStr;
  59. /// \brief Contains the number of line this pattern is in.
  60. unsigned LineNumber;
  61. /// VariableUses - Entries in this vector map to uses of a variable in the
  62. /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain
  63. /// "foobaz" and we'll get an entry in this vector that tells us to insert the
  64. /// value of bar at offset 3.
  65. std::vector<std::pair<StringRef, unsigned> > VariableUses;
  66. /// VariableDefs - Maps definitions of variables to their parenthesized
  67. /// capture numbers.
  68. /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
  69. std::map<StringRef, unsigned> VariableDefs;
  70. public:
  71. Pattern(bool matchEOF = false) : MatchEOF(matchEOF) { }
  72. /// ParsePattern - Parse the given string into the Pattern. SM provides the
  73. /// SourceMgr used for error reports, and LineNumber is the line number in
  74. /// the input file from which the pattern string was read.
  75. /// Returns true in case of an error, false otherwise.
  76. bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
  77. /// Match - Match the pattern string against the input buffer Buffer. This
  78. /// returns the position that is matched or npos if there is no match. If
  79. /// there is a match, the size of the matched string is returned in MatchLen.
  80. ///
  81. /// The VariableTable StringMap provides the current values of filecheck
  82. /// variables and is updated if this match defines new values.
  83. size_t Match(StringRef Buffer, size_t &MatchLen,
  84. StringMap<StringRef> &VariableTable) const;
  85. /// PrintFailureInfo - Print additional information about a failure to match
  86. /// involving this pattern.
  87. void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
  88. const StringMap<StringRef> &VariableTable) const;
  89. private:
  90. static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
  91. bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
  92. void AddBackrefToRegEx(unsigned BackrefNum);
  93. /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
  94. /// matching this pattern at the start of \arg Buffer; a distance of zero
  95. /// should correspond to a perfect match.
  96. unsigned ComputeMatchDistance(StringRef Buffer,
  97. const StringMap<StringRef> &VariableTable) const;
  98. /// \brief Evaluates expression and stores the result to \p Value.
  99. /// \return true on success. false when the expression has invalid syntax.
  100. bool EvaluateExpression(StringRef Expr, std::string &Value) const;
  101. /// \brief Finds the closing sequence of a regex variable usage or
  102. /// definition. Str has to point in the beginning of the definition
  103. /// (right after the opening sequence).
  104. /// \return offset of the closing sequence within Str, or npos if it was not
  105. /// found.
  106. size_t FindRegexVarEnd(StringRef Str);
  107. };
  108. bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
  109. unsigned LineNumber) {
  110. this->LineNumber = LineNumber;
  111. PatternLoc = SMLoc::getFromPointer(PatternStr.data());
  112. // Ignore trailing whitespace.
  113. while (!PatternStr.empty() &&
  114. (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
  115. PatternStr = PatternStr.substr(0, PatternStr.size()-1);
  116. // Check that there is something on the line.
  117. if (PatternStr.empty()) {
  118. SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
  119. "found empty check string with prefix '" +
  120. CheckPrefix+":'");
  121. return true;
  122. }
  123. // Check to see if this is a fixed string, or if it has regex pieces.
  124. if (PatternStr.size() < 2 ||
  125. (PatternStr.find("{{") == StringRef::npos &&
  126. PatternStr.find("[[") == StringRef::npos)) {
  127. FixedStr = PatternStr;
  128. return false;
  129. }
  130. // Paren value #0 is for the fully matched string. Any new parenthesized
  131. // values add from there.
  132. unsigned CurParen = 1;
  133. // Otherwise, there is at least one regex piece. Build up the regex pattern
  134. // by escaping scary characters in fixed strings, building up one big regex.
  135. while (!PatternStr.empty()) {
  136. // RegEx matches.
  137. if (PatternStr.startswith("{{")) {
  138. // This is the start of a regex match. Scan for the }}.
  139. size_t End = PatternStr.find("}}");
  140. if (End == StringRef::npos) {
  141. SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
  142. SourceMgr::DK_Error,
  143. "found start of regex string with no end '}}'");
  144. return true;
  145. }
  146. // Enclose {{}} patterns in parens just like [[]] even though we're not
  147. // capturing the result for any purpose. This is required in case the
  148. // expression contains an alternation like: CHECK: abc{{x|z}}def. We
  149. // want this to turn into: "abc(x|z)def" not "abcx|zdef".
  150. RegExStr += '(';
  151. ++CurParen;
  152. if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
  153. return true;
  154. RegExStr += ')';
  155. PatternStr = PatternStr.substr(End+2);
  156. continue;
  157. }
  158. // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
  159. // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
  160. // second form is [[foo]] which is a reference to foo. The variable name
  161. // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
  162. // it. This is to catch some common errors.
  163. if (PatternStr.startswith("[[")) {
  164. // Find the closing bracket pair ending the match. End is going to be an
  165. // offset relative to the beginning of the match string.
  166. size_t End = FindRegexVarEnd(PatternStr.substr(2));
  167. if (End == StringRef::npos) {
  168. SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
  169. SourceMgr::DK_Error,
  170. "invalid named regex reference, no ]] found");
  171. return true;
  172. }
  173. StringRef MatchStr = PatternStr.substr(2, End);
  174. PatternStr = PatternStr.substr(End+4);
  175. // Get the regex name (e.g. "foo").
  176. size_t NameEnd = MatchStr.find(':');
  177. StringRef Name = MatchStr.substr(0, NameEnd);
  178. if (Name.empty()) {
  179. SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
  180. "invalid name in named regex: empty name");
  181. return true;
  182. }
  183. // Verify that the name/expression is well formed. FileCheck currently
  184. // supports @LINE, @LINE+number, @LINE-number expressions. The check here
  185. // is relaxed, more strict check is performed in \c EvaluateExpression.
  186. bool IsExpression = false;
  187. for (unsigned i = 0, e = Name.size(); i != e; ++i) {
  188. if (i == 0 && Name[i] == '@') {
  189. if (NameEnd != StringRef::npos) {
  190. SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
  191. SourceMgr::DK_Error,
  192. "invalid name in named regex definition");
  193. return true;
  194. }
  195. IsExpression = true;
  196. continue;
  197. }
  198. if (Name[i] != '_' && !isalnum(Name[i]) &&
  199. (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
  200. SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
  201. SourceMgr::DK_Error, "invalid name in named regex");
  202. return true;
  203. }
  204. }
  205. // Name can't start with a digit.
  206. if (isdigit(Name[0])) {
  207. SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
  208. "invalid name in named regex");
  209. return true;
  210. }
  211. // Handle [[foo]].
  212. if (NameEnd == StringRef::npos) {
  213. // Handle variables that were defined earlier on the same line by
  214. // emitting a backreference.
  215. if (VariableDefs.find(Name) != VariableDefs.end()) {
  216. unsigned VarParenNum = VariableDefs[Name];
  217. if (VarParenNum < 1 || VarParenNum > 9) {
  218. SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
  219. SourceMgr::DK_Error,
  220. "Can't back-reference more than 9 variables");
  221. return true;
  222. }
  223. AddBackrefToRegEx(VarParenNum);
  224. } else {
  225. VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
  226. }
  227. continue;
  228. }
  229. // Handle [[foo:.*]].
  230. VariableDefs[Name] = CurParen;
  231. RegExStr += '(';
  232. ++CurParen;
  233. if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
  234. return true;
  235. RegExStr += ')';
  236. }
  237. // Handle fixed string matches.
  238. // Find the end, which is the start of the next regex.
  239. size_t FixedMatchEnd = PatternStr.find("{{");
  240. FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
  241. AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
  242. PatternStr = PatternStr.substr(FixedMatchEnd);
  243. }
  244. return false;
  245. }
  246. void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
  247. // Add the characters from FixedStr to the regex, escaping as needed. This
  248. // avoids "leaning toothpicks" in common patterns.
  249. for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
  250. switch (FixedStr[i]) {
  251. // These are the special characters matched in "p_ere_exp".
  252. case '(':
  253. case ')':
  254. case '^':
  255. case '$':
  256. case '|':
  257. case '*':
  258. case '+':
  259. case '?':
  260. case '.':
  261. case '[':
  262. case '\\':
  263. case '{':
  264. TheStr += '\\';
  265. // FALL THROUGH.
  266. default:
  267. TheStr += FixedStr[i];
  268. break;
  269. }
  270. }
  271. }
  272. bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
  273. SourceMgr &SM) {
  274. Regex R(RS);
  275. std::string Error;
  276. if (!R.isValid(Error)) {
  277. SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
  278. "invalid regex: " + Error);
  279. return true;
  280. }
  281. RegExStr += RS.str();
  282. CurParen += R.getNumMatches();
  283. return false;
  284. }
  285. void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
  286. assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
  287. std::string Backref = std::string("\\") +
  288. std::string(1, '0' + BackrefNum);
  289. RegExStr += Backref;
  290. }
  291. bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
  292. // The only supported expression is @LINE([\+-]\d+)?
  293. if (!Expr.startswith("@LINE"))
  294. return false;
  295. Expr = Expr.substr(StringRef("@LINE").size());
  296. int Offset = 0;
  297. if (!Expr.empty()) {
  298. if (Expr[0] == '+')
  299. Expr = Expr.substr(1);
  300. else if (Expr[0] != '-')
  301. return false;
  302. if (Expr.getAsInteger(10, Offset))
  303. return false;
  304. }
  305. Value = llvm::itostr(LineNumber + Offset);
  306. return true;
  307. }
  308. /// Match - Match the pattern string against the input buffer Buffer. This
  309. /// returns the position that is matched or npos if there is no match. If
  310. /// there is a match, the size of the matched string is returned in MatchLen.
  311. size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
  312. StringMap<StringRef> &VariableTable) const {
  313. // If this is the EOF pattern, match it immediately.
  314. if (MatchEOF) {
  315. MatchLen = 0;
  316. return Buffer.size();
  317. }
  318. // If this is a fixed string pattern, just match it now.
  319. if (!FixedStr.empty()) {
  320. MatchLen = FixedStr.size();
  321. return Buffer.find(FixedStr);
  322. }
  323. // Regex match.
  324. // If there are variable uses, we need to create a temporary string with the
  325. // actual value.
  326. StringRef RegExToMatch = RegExStr;
  327. std::string TmpStr;
  328. if (!VariableUses.empty()) {
  329. TmpStr = RegExStr;
  330. unsigned InsertOffset = 0;
  331. for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
  332. std::string Value;
  333. if (VariableUses[i].first[0] == '@') {
  334. if (!EvaluateExpression(VariableUses[i].first, Value))
  335. return StringRef::npos;
  336. } else {
  337. StringMap<StringRef>::iterator it =
  338. VariableTable.find(VariableUses[i].first);
  339. // If the variable is undefined, return an error.
  340. if (it == VariableTable.end())
  341. return StringRef::npos;
  342. // Look up the value and escape it so that we can plop it into the regex.
  343. AddFixedStringToRegEx(it->second, Value);
  344. }
  345. // Plop it into the regex at the adjusted offset.
  346. TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
  347. Value.begin(), Value.end());
  348. InsertOffset += Value.size();
  349. }
  350. // Match the newly constructed regex.
  351. RegExToMatch = TmpStr;
  352. }
  353. SmallVector<StringRef, 4> MatchInfo;
  354. if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
  355. return StringRef::npos;
  356. // Successful regex match.
  357. assert(!MatchInfo.empty() && "Didn't get any match");
  358. StringRef FullMatch = MatchInfo[0];
  359. // If this defines any variables, remember their values.
  360. for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
  361. E = VariableDefs.end();
  362. I != E; ++I) {
  363. assert(I->second < MatchInfo.size() && "Internal paren error");
  364. VariableTable[I->first] = MatchInfo[I->second];
  365. }
  366. MatchLen = FullMatch.size();
  367. return FullMatch.data()-Buffer.data();
  368. }
  369. unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
  370. const StringMap<StringRef> &VariableTable) const {
  371. // Just compute the number of matching characters. For regular expressions, we
  372. // just compare against the regex itself and hope for the best.
  373. //
  374. // FIXME: One easy improvement here is have the regex lib generate a single
  375. // example regular expression which matches, and use that as the example
  376. // string.
  377. StringRef ExampleString(FixedStr);
  378. if (ExampleString.empty())
  379. ExampleString = RegExStr;
  380. // Only compare up to the first line in the buffer, or the string size.
  381. StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
  382. BufferPrefix = BufferPrefix.split('\n').first;
  383. return BufferPrefix.edit_distance(ExampleString);
  384. }
  385. void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
  386. const StringMap<StringRef> &VariableTable) const{
  387. // If this was a regular expression using variables, print the current
  388. // variable values.
  389. if (!VariableUses.empty()) {
  390. for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
  391. SmallString<256> Msg;
  392. raw_svector_ostream OS(Msg);
  393. StringRef Var = VariableUses[i].first;
  394. if (Var[0] == '@') {
  395. std::string Value;
  396. if (EvaluateExpression(Var, Value)) {
  397. OS << "with expression \"";
  398. OS.write_escaped(Var) << "\" equal to \"";
  399. OS.write_escaped(Value) << "\"";
  400. } else {
  401. OS << "uses incorrect expression \"";
  402. OS.write_escaped(Var) << "\"";
  403. }
  404. } else {
  405. StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
  406. // Check for undefined variable references.
  407. if (it == VariableTable.end()) {
  408. OS << "uses undefined variable \"";
  409. OS.write_escaped(Var) << "\"";
  410. } else {
  411. OS << "with variable \"";
  412. OS.write_escaped(Var) << "\" equal to \"";
  413. OS.write_escaped(it->second) << "\"";
  414. }
  415. }
  416. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
  417. OS.str());
  418. }
  419. }
  420. // Attempt to find the closest/best fuzzy match. Usually an error happens
  421. // because some string in the output didn't exactly match. In these cases, we
  422. // would like to show the user a best guess at what "should have" matched, to
  423. // save them having to actually check the input manually.
  424. size_t NumLinesForward = 0;
  425. size_t Best = StringRef::npos;
  426. double BestQuality = 0;
  427. // Use an arbitrary 4k limit on how far we will search.
  428. for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
  429. if (Buffer[i] == '\n')
  430. ++NumLinesForward;
  431. // Patterns have leading whitespace stripped, so skip whitespace when
  432. // looking for something which looks like a pattern.
  433. if (Buffer[i] == ' ' || Buffer[i] == '\t')
  434. continue;
  435. // Compute the "quality" of this match as an arbitrary combination of the
  436. // match distance and the number of lines skipped to get to this match.
  437. unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
  438. double Quality = Distance + (NumLinesForward / 100.);
  439. if (Quality < BestQuality || Best == StringRef::npos) {
  440. Best = i;
  441. BestQuality = Quality;
  442. }
  443. }
  444. // Print the "possible intended match here" line if we found something
  445. // reasonable and not equal to what we showed in the "scanning from here"
  446. // line.
  447. if (Best && Best != StringRef::npos && BestQuality < 50) {
  448. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
  449. SourceMgr::DK_Note, "possible intended match here");
  450. // FIXME: If we wanted to be really friendly we would show why the match
  451. // failed, as it can be hard to spot simple one character differences.
  452. }
  453. }
  454. size_t Pattern::FindRegexVarEnd(StringRef Str) {
  455. // Offset keeps track of the current offset within the input Str
  456. size_t Offset = 0;
  457. // [...] Nesting depth
  458. size_t BracketDepth = 0;
  459. while (!Str.empty()) {
  460. if (Str.startswith("]]") && BracketDepth == 0)
  461. return Offset;
  462. if (Str[0] == '\\') {
  463. // Backslash escapes the next char within regexes, so skip them both.
  464. Str = Str.substr(2);
  465. Offset += 2;
  466. } else {
  467. switch (Str[0]) {
  468. default:
  469. break;
  470. case '[':
  471. BracketDepth++;
  472. break;
  473. case ']':
  474. assert(BracketDepth > 0 && "Invalid regex");
  475. BracketDepth--;
  476. break;
  477. }
  478. Str = Str.substr(1);
  479. Offset++;
  480. }
  481. }
  482. return StringRef::npos;
  483. }
  484. //===----------------------------------------------------------------------===//
  485. // Check Strings.
  486. //===----------------------------------------------------------------------===//
  487. /// CheckString - This is a check that we found in the input file.
  488. struct CheckString {
  489. /// Pat - The pattern to match.
  490. Pattern Pat;
  491. /// Loc - The location in the match file that the check string was specified.
  492. SMLoc Loc;
  493. /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
  494. /// to a CHECK: directive.
  495. bool IsCheckNext;
  496. /// NotStrings - These are all of the strings that are disallowed from
  497. /// occurring between this match string and the previous one (or start of
  498. /// file).
  499. std::vector<std::pair<SMLoc, Pattern> > NotStrings;
  500. CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
  501. : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
  502. };
  503. /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
  504. /// memory buffer, free it, and return a new one.
  505. static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
  506. SmallString<128> NewFile;
  507. NewFile.reserve(MB->getBufferSize());
  508. for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
  509. Ptr != End; ++Ptr) {
  510. // Eliminate trailing dosish \r.
  511. if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
  512. continue;
  513. }
  514. // If current char is not a horizontal whitespace, dump it to output as is.
  515. if (*Ptr != ' ' && *Ptr != '\t') {
  516. NewFile.push_back(*Ptr);
  517. continue;
  518. }
  519. // Otherwise, add one space and advance over neighboring space.
  520. NewFile.push_back(' ');
  521. while (Ptr+1 != End &&
  522. (Ptr[1] == ' ' || Ptr[1] == '\t'))
  523. ++Ptr;
  524. }
  525. // Free the old buffer and return a new one.
  526. MemoryBuffer *MB2 =
  527. MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
  528. delete MB;
  529. return MB2;
  530. }
  531. /// ReadCheckFile - Read the check file, which specifies the sequence of
  532. /// expected strings. The strings are added to the CheckStrings vector.
  533. /// Returns true in case of an error, false otherwise.
  534. static bool ReadCheckFile(SourceMgr &SM,
  535. std::vector<CheckString> &CheckStrings) {
  536. OwningPtr<MemoryBuffer> File;
  537. if (error_code ec =
  538. MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) {
  539. errs() << "Could not open check file '" << CheckFilename << "': "
  540. << ec.message() << '\n';
  541. return true;
  542. }
  543. MemoryBuffer *F = File.take();
  544. // If we want to canonicalize whitespace, strip excess whitespace from the
  545. // buffer containing the CHECK lines.
  546. if (!NoCanonicalizeWhiteSpace)
  547. F = CanonicalizeInputFile(F);
  548. SM.AddNewSourceBuffer(F, SMLoc());
  549. // Find all instances of CheckPrefix followed by : in the file.
  550. StringRef Buffer = F->getBuffer();
  551. std::vector<std::pair<SMLoc, Pattern> > NotMatches;
  552. // LineNumber keeps track of the line on which CheckPrefix instances are
  553. // found.
  554. unsigned LineNumber = 1;
  555. while (1) {
  556. // See if Prefix occurs in the memory buffer.
  557. size_t PrefixLoc = Buffer.find(CheckPrefix);
  558. // If we didn't find a match, we're done.
  559. if (PrefixLoc == StringRef::npos)
  560. break;
  561. LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
  562. Buffer = Buffer.substr(PrefixLoc);
  563. const char *CheckPrefixStart = Buffer.data();
  564. // When we find a check prefix, keep track of whether we find CHECK: or
  565. // CHECK-NEXT:
  566. bool IsCheckNext = false, IsCheckNot = false;
  567. // Verify that the : is present after the prefix.
  568. if (Buffer[CheckPrefix.size()] == ':') {
  569. Buffer = Buffer.substr(CheckPrefix.size()+1);
  570. } else if (Buffer.size() > CheckPrefix.size()+6 &&
  571. memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
  572. Buffer = Buffer.substr(CheckPrefix.size()+6);
  573. IsCheckNext = true;
  574. } else if (Buffer.size() > CheckPrefix.size()+5 &&
  575. memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
  576. Buffer = Buffer.substr(CheckPrefix.size()+5);
  577. IsCheckNot = true;
  578. } else {
  579. Buffer = Buffer.substr(1);
  580. continue;
  581. }
  582. // Okay, we found the prefix, yay. Remember the rest of the line, but
  583. // ignore leading and trailing whitespace.
  584. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
  585. // Scan ahead to the end of line.
  586. size_t EOL = Buffer.find_first_of("\n\r");
  587. // Remember the location of the start of the pattern, for diagnostics.
  588. SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
  589. // Parse the pattern.
  590. Pattern P;
  591. if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
  592. return true;
  593. Buffer = Buffer.substr(EOL);
  594. // Verify that CHECK-NEXT lines have at least one CHECK line before them.
  595. if (IsCheckNext && CheckStrings.empty()) {
  596. SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
  597. SourceMgr::DK_Error,
  598. "found '"+CheckPrefix+"-NEXT:' without previous '"+
  599. CheckPrefix+ ": line");
  600. return true;
  601. }
  602. // Handle CHECK-NOT.
  603. if (IsCheckNot) {
  604. NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
  605. P));
  606. continue;
  607. }
  608. // Okay, add the string we captured to the output vector and move on.
  609. CheckStrings.push_back(CheckString(P,
  610. PatternLoc,
  611. IsCheckNext));
  612. std::swap(NotMatches, CheckStrings.back().NotStrings);
  613. }
  614. // Add an EOF pattern for any trailing CHECK-NOTs.
  615. if (!NotMatches.empty()) {
  616. CheckStrings.push_back(CheckString(Pattern(true),
  617. SMLoc::getFromPointer(Buffer.data()),
  618. false));
  619. std::swap(NotMatches, CheckStrings.back().NotStrings);
  620. }
  621. if (CheckStrings.empty()) {
  622. errs() << "error: no check strings found with prefix '" << CheckPrefix
  623. << ":'\n";
  624. return true;
  625. }
  626. return false;
  627. }
  628. static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
  629. StringRef Buffer,
  630. StringMap<StringRef> &VariableTable) {
  631. // Otherwise, we have an error, emit an error message.
  632. SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
  633. "expected string not found in input");
  634. // Print the "scanning from here" line. If the current position is at the
  635. // end of a line, advance to the start of the next line.
  636. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
  637. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
  638. "scanning from here");
  639. // Allow the pattern to print additional information if desired.
  640. CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable);
  641. }
  642. /// CountNumNewlinesBetween - Count the number of newlines in the specified
  643. /// range.
  644. static unsigned CountNumNewlinesBetween(StringRef Range) {
  645. unsigned NumNewLines = 0;
  646. while (1) {
  647. // Scan for newline.
  648. Range = Range.substr(Range.find_first_of("\n\r"));
  649. if (Range.empty()) return NumNewLines;
  650. ++NumNewLines;
  651. // Handle \n\r and \r\n as a single newline.
  652. if (Range.size() > 1 &&
  653. (Range[1] == '\n' || Range[1] == '\r') &&
  654. (Range[0] != Range[1]))
  655. Range = Range.substr(1);
  656. Range = Range.substr(1);
  657. }
  658. }
  659. int main(int argc, char **argv) {
  660. sys::PrintStackTraceOnErrorSignal();
  661. PrettyStackTraceProgram X(argc, argv);
  662. cl::ParseCommandLineOptions(argc, argv);
  663. SourceMgr SM;
  664. // Read the expected strings from the check file.
  665. std::vector<CheckString> CheckStrings;
  666. if (ReadCheckFile(SM, CheckStrings))
  667. return 2;
  668. // Open the file to check and add it to SourceMgr.
  669. OwningPtr<MemoryBuffer> File;
  670. if (error_code ec =
  671. MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
  672. errs() << "Could not open input file '" << InputFilename << "': "
  673. << ec.message() << '\n';
  674. return 2;
  675. }
  676. MemoryBuffer *F = File.take();
  677. if (F->getBufferSize() == 0) {
  678. errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
  679. return 2;
  680. }
  681. // Remove duplicate spaces in the input file if requested.
  682. if (!NoCanonicalizeWhiteSpace)
  683. F = CanonicalizeInputFile(F);
  684. SM.AddNewSourceBuffer(F, SMLoc());
  685. /// VariableTable - This holds all the current filecheck variables.
  686. StringMap<StringRef> VariableTable;
  687. // Check that we have all of the expected strings, in order, in the input
  688. // file.
  689. StringRef Buffer = F->getBuffer();
  690. const char *LastMatch = Buffer.data();
  691. for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
  692. const CheckString &CheckStr = CheckStrings[StrNo];
  693. StringRef SearchFrom = Buffer;
  694. // Find StrNo in the file.
  695. size_t MatchLen = 0;
  696. size_t MatchPos = CheckStr.Pat.Match(Buffer, MatchLen, VariableTable);
  697. Buffer = Buffer.substr(MatchPos);
  698. // If we didn't find a match, reject the input.
  699. if (MatchPos == StringRef::npos) {
  700. PrintCheckFailed(SM, CheckStr, SearchFrom, VariableTable);
  701. return 1;
  702. }
  703. StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
  704. // If this check is a "CHECK-NEXT", verify that the previous match was on
  705. // the previous line (i.e. that there is one newline between them).
  706. if (CheckStr.IsCheckNext) {
  707. // Count the number of newlines between the previous match and this one.
  708. assert(LastMatch != F->getBufferStart() &&
  709. "CHECK-NEXT can't be the first check in a file");
  710. unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
  711. if (NumNewLines == 0) {
  712. SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
  713. CheckPrefix+"-NEXT: is on the same line as previous match");
  714. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
  715. SourceMgr::DK_Note, "'next' match was here");
  716. SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
  717. "previous match was here");
  718. return 1;
  719. }
  720. if (NumNewLines != 1) {
  721. SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+
  722. "-NEXT: is not on the line after the previous match");
  723. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
  724. SourceMgr::DK_Note, "'next' match was here");
  725. SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
  726. "previous match was here");
  727. return 1;
  728. }
  729. }
  730. // If this match had "not strings", verify that they don't exist in the
  731. // skipped region.
  732. for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size();
  733. ChunkNo != e; ++ChunkNo) {
  734. size_t MatchLen = 0;
  735. size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion,
  736. MatchLen,
  737. VariableTable);
  738. if (Pos == StringRef::npos) continue;
  739. SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos), SourceMgr::DK_Error,
  740. CheckPrefix+"-NOT: string occurred!");
  741. SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first, SourceMgr::DK_Note,
  742. CheckPrefix+"-NOT: pattern specified here");
  743. return 1;
  744. }
  745. // Otherwise, everything is good. Step over the matched text and remember
  746. // the position after the match as the end of the last match.
  747. Buffer = Buffer.substr(MatchLen);
  748. LastMatch = Buffer.data();
  749. }
  750. return 0;
  751. }