FileCheck.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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 exit 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/InitLLVM.h"
  20. #include "llvm/Support/Process.h"
  21. #include "llvm/Support/WithColor.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. #include "llvm/Support/FileCheck.h"
  24. using namespace llvm;
  25. static cl::opt<std::string>
  26. CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Optional);
  27. static cl::opt<std::string>
  28. InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
  29. cl::init("-"), cl::value_desc("filename"));
  30. static cl::list<std::string> CheckPrefixes(
  31. "check-prefix",
  32. cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
  33. static cl::alias CheckPrefixesAlias(
  34. "check-prefixes", cl::aliasopt(CheckPrefixes), cl::CommaSeparated,
  35. cl::NotHidden,
  36. cl::desc(
  37. "Alias for -check-prefix permitting multiple comma separated values"));
  38. static cl::opt<bool> NoCanonicalizeWhiteSpace(
  39. "strict-whitespace",
  40. cl::desc("Do not treat all horizontal whitespace as equivalent"));
  41. static cl::list<std::string> ImplicitCheckNot(
  42. "implicit-check-not",
  43. cl::desc("Add an implicit negative check with this pattern to every\n"
  44. "positive check. This can be used to ensure that no instances of\n"
  45. "this pattern occur which are not matched by a positive pattern"),
  46. cl::value_desc("pattern"));
  47. static cl::list<std::string> GlobalDefines("D", cl::Prefix,
  48. cl::desc("Define a variable to be used in capture patterns."),
  49. cl::value_desc("VAR=VALUE"));
  50. static cl::opt<bool> AllowEmptyInput(
  51. "allow-empty", cl::init(false),
  52. cl::desc("Allow the input file to be empty. This is useful when making\n"
  53. "checks that some error message does not occur, for example."));
  54. static cl::opt<bool> MatchFullLines(
  55. "match-full-lines", cl::init(false),
  56. cl::desc("Require all positive matches to cover an entire input line.\n"
  57. "Allows leading and trailing whitespace if --strict-whitespace\n"
  58. "is not also passed."));
  59. static cl::opt<bool> EnableVarScope(
  60. "enable-var-scope", cl::init(false),
  61. cl::desc("Enables scope for regex variables. Variables with names that\n"
  62. "do not start with '$' will be reset at the beginning of\n"
  63. "each CHECK-LABEL block."));
  64. static cl::opt<bool> AllowDeprecatedDagOverlap(
  65. "allow-deprecated-dag-overlap", cl::init(false),
  66. cl::desc("Enable overlapping among matches in a group of consecutive\n"
  67. "CHECK-DAG directives. This option is deprecated and is only\n"
  68. "provided for convenience as old tests are migrated to the new\n"
  69. "non-overlapping CHECK-DAG implementation.\n"));
  70. static cl::opt<bool> Verbose("v", cl::init(false),
  71. cl::desc("Print directive pattern matches.\n"));
  72. static cl::opt<bool> VerboseVerbose(
  73. "vv", cl::init(false),
  74. cl::desc("Print information helpful in diagnosing internal FileCheck\n"
  75. "issues. Implies -v.\n"));
  76. static const char * DumpInputEnv = "FILECHECK_DUMP_INPUT_ON_FAILURE";
  77. static cl::opt<bool> DumpInputOnFailure(
  78. "dump-input-on-failure", cl::init(std::getenv(DumpInputEnv)),
  79. cl::desc("Dump original input to stderr before failing.\n"
  80. "The value can be also controlled using\n"
  81. "FILECHECK_DUMP_INPUT_ON_FAILURE environment variable.\n"
  82. "This option is deprecated in favor of -dump-input=fail.\n"));
  83. enum DumpInputValue {
  84. DumpInputDefault,
  85. DumpInputHelp,
  86. DumpInputNever,
  87. DumpInputFail,
  88. DumpInputAlways
  89. };
  90. static cl::opt<DumpInputValue> DumpInput(
  91. "dump-input", cl::init(DumpInputDefault),
  92. cl::desc("Dump input to stderr, adding annotations representing\n"
  93. " currently enabled diagnostics\n"),
  94. cl::value_desc("mode"),
  95. cl::values(clEnumValN(DumpInputHelp, "help",
  96. "Explain dump format and quit"),
  97. clEnumValN(DumpInputNever, "never", "Never dump input"),
  98. clEnumValN(DumpInputFail, "fail", "Dump input on failure"),
  99. clEnumValN(DumpInputAlways, "always", "Always dump input")));
  100. typedef cl::list<std::string>::const_iterator prefix_iterator;
  101. static void DumpCommandLine(int argc, char **argv) {
  102. errs() << "FileCheck command line: ";
  103. for (int I = 0; I < argc; I++)
  104. errs() << " " << argv[I];
  105. errs() << "\n";
  106. }
  107. struct MarkerStyle {
  108. /// The starting char (before tildes) for marking the line.
  109. char Lead;
  110. /// What color to use for this annotation.
  111. raw_ostream::Colors Color;
  112. /// A note to follow the marker, or empty string if none.
  113. std::string Note;
  114. MarkerStyle() {}
  115. MarkerStyle(char Lead, raw_ostream::Colors Color,
  116. const std::string &Note = "")
  117. : Lead(Lead), Color(Color), Note(Note) {}
  118. };
  119. static MarkerStyle GetMarker(FileCheckDiag::MatchType MatchTy) {
  120. switch (MatchTy) {
  121. case FileCheckDiag::MatchFoundAndExpected:
  122. return MarkerStyle('^', raw_ostream::GREEN);
  123. case FileCheckDiag::MatchFoundButExcluded:
  124. return MarkerStyle('!', raw_ostream::RED, "error: no match expected");
  125. case FileCheckDiag::MatchFoundButWrongLine:
  126. return MarkerStyle('!', raw_ostream::RED, "error: match on wrong line");
  127. case FileCheckDiag::MatchFoundButDiscarded:
  128. return MarkerStyle('!', raw_ostream::CYAN,
  129. "discard: overlaps earlier match");
  130. case FileCheckDiag::MatchNoneAndExcluded:
  131. return MarkerStyle('X', raw_ostream::GREEN);
  132. case FileCheckDiag::MatchNoneButExpected:
  133. return MarkerStyle('X', raw_ostream::RED, "error: no match found");
  134. case FileCheckDiag::MatchFuzzy:
  135. return MarkerStyle('?', raw_ostream::MAGENTA, "possible intended match");
  136. }
  137. llvm_unreachable_internal("unexpected match type");
  138. }
  139. static void DumpInputAnnotationHelp(raw_ostream &OS) {
  140. OS << "The following description was requested by -dump-input=help to\n"
  141. << "explain the input annotations printed by -dump-input=always and\n"
  142. << "-dump-input=fail:\n\n";
  143. // Labels for input lines.
  144. OS << " - ";
  145. WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "L:";
  146. OS << " labels line number L of the input file\n";
  147. // Labels for annotation lines.
  148. OS << " - ";
  149. WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L";
  150. OS << " labels the only match result for a pattern of type T from "
  151. << "line L of\n"
  152. << " the check file\n";
  153. OS << " - ";
  154. WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L'N";
  155. OS << " labels the Nth match result for a pattern of type T from line "
  156. << "L of\n"
  157. << " the check file\n";
  158. // Markers on annotation lines.
  159. OS << " - ";
  160. WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "^~~";
  161. OS << " marks good match (reported if -v)\n"
  162. << " - ";
  163. WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "!~~";
  164. OS << " marks bad match, such as:\n"
  165. << " - CHECK-NEXT on same line as previous match (error)\n"
  166. << " - CHECK-NOT found (error)\n"
  167. << " - CHECK-DAG overlapping match (discarded, reported if "
  168. << "-vv)\n"
  169. << " - ";
  170. WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "X~~";
  171. OS << " marks search range when no match is found, such as:\n"
  172. << " - CHECK-NEXT not found (error)\n"
  173. << " - CHECK-NOT not found (success, reported if -vv)\n"
  174. << " - CHECK-DAG not found after discarded matches (error)\n"
  175. << " - ";
  176. WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "?";
  177. OS << " marks fuzzy match when no match is found\n";
  178. // Colors.
  179. OS << " - colors ";
  180. WithColor(OS, raw_ostream::GREEN, true) << "success";
  181. OS << ", ";
  182. WithColor(OS, raw_ostream::RED, true) << "error";
  183. OS << ", ";
  184. WithColor(OS, raw_ostream::MAGENTA, true) << "fuzzy match";
  185. OS << ", ";
  186. WithColor(OS, raw_ostream::CYAN, true, false) << "discarded match";
  187. OS << ", ";
  188. WithColor(OS, raw_ostream::CYAN, true, true) << "unmatched input";
  189. OS << "\n\n"
  190. << "If you are not seeing color above or in input dumps, try: -color\n";
  191. }
  192. /// An annotation for a single input line.
  193. struct InputAnnotation {
  194. /// The check file line (one-origin indexing) where the directive that
  195. /// produced this annotation is located.
  196. unsigned CheckLine;
  197. /// The index of the match result for this check.
  198. unsigned CheckDiagIndex;
  199. /// The label for this annotation.
  200. std::string Label;
  201. /// What input line (one-origin indexing) this annotation marks. This might
  202. /// be different from the starting line of the original diagnostic if this is
  203. /// a non-initial fragment of a diagnostic that has been broken across
  204. /// multiple lines.
  205. unsigned InputLine;
  206. /// The column range (one-origin indexing, open end) in which to to mark the
  207. /// input line. If InputEndCol is UINT_MAX, treat it as the last column
  208. /// before the newline.
  209. unsigned InputStartCol, InputEndCol;
  210. /// The marker to use.
  211. MarkerStyle Marker;
  212. /// Whether this annotation represents a good match for an expected pattern.
  213. bool FoundAndExpectedMatch;
  214. };
  215. /// Get an abbreviation for the check type.
  216. std::string GetCheckTypeAbbreviation(Check::FileCheckType Ty) {
  217. switch (Ty) {
  218. case Check::CheckPlain:
  219. if (Ty.getCount() > 1)
  220. return "count";
  221. return "check";
  222. case Check::CheckNext:
  223. return "next";
  224. case Check::CheckSame:
  225. return "same";
  226. case Check::CheckNot:
  227. return "not";
  228. case Check::CheckDAG:
  229. return "dag";
  230. case Check::CheckLabel:
  231. return "label";
  232. case Check::CheckEmpty:
  233. return "empty";
  234. case Check::CheckEOF:
  235. return "eof";
  236. case Check::CheckBadNot:
  237. return "bad-not";
  238. case Check::CheckBadCount:
  239. return "bad-count";
  240. case Check::CheckNone:
  241. llvm_unreachable("invalid FileCheckType");
  242. }
  243. llvm_unreachable("unknown FileCheckType");
  244. }
  245. static void BuildInputAnnotations(const std::vector<FileCheckDiag> &Diags,
  246. std::vector<InputAnnotation> &Annotations,
  247. unsigned &LabelWidth) {
  248. // How many diagnostics has the current check seen so far?
  249. unsigned CheckDiagCount = 0;
  250. // What's the widest label?
  251. LabelWidth = 0;
  252. for (auto DiagItr = Diags.begin(), DiagEnd = Diags.end(); DiagItr != DiagEnd;
  253. ++DiagItr) {
  254. InputAnnotation A;
  255. // Build label, which uniquely identifies this check result.
  256. A.CheckLine = DiagItr->CheckLine;
  257. llvm::raw_string_ostream Label(A.Label);
  258. Label << GetCheckTypeAbbreviation(DiagItr->CheckTy) << ":"
  259. << DiagItr->CheckLine;
  260. A.CheckDiagIndex = UINT_MAX;
  261. auto DiagNext = std::next(DiagItr);
  262. if (DiagNext != DiagEnd && DiagItr->CheckTy == DiagNext->CheckTy &&
  263. DiagItr->CheckLine == DiagNext->CheckLine)
  264. A.CheckDiagIndex = CheckDiagCount++;
  265. else if (CheckDiagCount) {
  266. A.CheckDiagIndex = CheckDiagCount;
  267. CheckDiagCount = 0;
  268. }
  269. if (A.CheckDiagIndex != UINT_MAX)
  270. Label << "'" << A.CheckDiagIndex;
  271. else
  272. A.CheckDiagIndex = 0;
  273. Label.flush();
  274. LabelWidth = std::max((std::string::size_type)LabelWidth, A.Label.size());
  275. MarkerStyle Marker = GetMarker(DiagItr->MatchTy);
  276. A.Marker = Marker;
  277. A.FoundAndExpectedMatch =
  278. DiagItr->MatchTy == FileCheckDiag::MatchFoundAndExpected;
  279. // Compute the mark location, and break annotation into multiple
  280. // annotations if it spans multiple lines.
  281. A.InputLine = DiagItr->InputStartLine;
  282. A.InputStartCol = DiagItr->InputStartCol;
  283. if (DiagItr->InputStartLine == DiagItr->InputEndLine) {
  284. // Sometimes ranges are empty in order to indicate a specific point, but
  285. // that would mean nothing would be marked, so adjust the range to
  286. // include the following character.
  287. A.InputEndCol =
  288. std::max(DiagItr->InputStartCol + 1, DiagItr->InputEndCol);
  289. Annotations.push_back(A);
  290. } else {
  291. assert(DiagItr->InputStartLine < DiagItr->InputEndLine &&
  292. "expected input range not to be inverted");
  293. A.InputEndCol = UINT_MAX;
  294. A.Marker.Note = "";
  295. Annotations.push_back(A);
  296. for (unsigned L = DiagItr->InputStartLine + 1, E = DiagItr->InputEndLine;
  297. L <= E; ++L) {
  298. // If a range ends before the first column on a line, then it has no
  299. // characters on that line, so there's nothing to render.
  300. if (DiagItr->InputEndCol == 1 && L == E) {
  301. Annotations.back().Marker.Note = Marker.Note;
  302. break;
  303. }
  304. InputAnnotation B;
  305. B.CheckLine = A.CheckLine;
  306. B.CheckDiagIndex = A.CheckDiagIndex;
  307. B.Label = A.Label;
  308. B.InputLine = L;
  309. B.Marker = Marker;
  310. B.Marker.Lead = '~';
  311. B.InputStartCol = 1;
  312. if (L != E) {
  313. B.InputEndCol = UINT_MAX;
  314. B.Marker.Note = "";
  315. } else
  316. B.InputEndCol = DiagItr->InputEndCol;
  317. B.FoundAndExpectedMatch = A.FoundAndExpectedMatch;
  318. Annotations.push_back(B);
  319. }
  320. }
  321. }
  322. }
  323. static void DumpAnnotatedInput(raw_ostream &OS, const FileCheckRequest &Req,
  324. StringRef InputFileText,
  325. std::vector<InputAnnotation> &Annotations,
  326. unsigned LabelWidth) {
  327. OS << "Full input was:\n<<<<<<\n";
  328. // Sort annotations.
  329. //
  330. // First, sort in the order of input lines to make it easier to find relevant
  331. // annotations while iterating input lines in the implementation below.
  332. // FileCheck diagnostics are not always reported and recorded in the order of
  333. // input lines due to, for example, CHECK-DAG and CHECK-NOT.
  334. //
  335. // Second, for annotations for the same input line, sort in the order of the
  336. // FileCheck directive's line in the check file (where there's at most one
  337. // directive per line) and then by the index of the match result for that
  338. // directive. The rationale of this choice is that, for any input line, this
  339. // sort establishes a total order of annotations that, with respect to match
  340. // results, is consistent across multiple lines, thus making match results
  341. // easier to track from one line to the next when they span multiple lines.
  342. std::sort(Annotations.begin(), Annotations.end(),
  343. [](const InputAnnotation &A, const InputAnnotation &B) {
  344. if (A.InputLine != B.InputLine)
  345. return A.InputLine < B.InputLine;
  346. if (A.CheckLine != B.CheckLine)
  347. return A.CheckLine < B.CheckLine;
  348. // FIXME: Sometimes CHECK-LABEL reports its match twice with
  349. // other diagnostics in between, and then diag index incrementing
  350. // fails to work properly, and then this assert fails. We should
  351. // suppress one of those diagnostics or do a better job of
  352. // computing this index. For now, we just produce a redundant
  353. // CHECK-LABEL annotation.
  354. // assert(A.CheckDiagIndex != B.CheckDiagIndex &&
  355. // "expected diagnostic indices to be unique within a "
  356. // " check line");
  357. return A.CheckDiagIndex < B.CheckDiagIndex;
  358. });
  359. // Compute the width of the label column.
  360. const unsigned char *InputFilePtr = InputFileText.bytes_begin(),
  361. *InputFileEnd = InputFileText.bytes_end();
  362. unsigned LineCount = InputFileText.count('\n');
  363. if (InputFileEnd[-1] != '\n')
  364. ++LineCount;
  365. unsigned LineNoWidth = log10(LineCount) + 1;
  366. // +3 below adds spaces (1) to the left of the (right-aligned) line numbers
  367. // on input lines and (2) to the right of the (left-aligned) labels on
  368. // annotation lines so that input lines and annotation lines are more
  369. // visually distinct. For example, the spaces on the annotation lines ensure
  370. // that input line numbers and check directive line numbers never align
  371. // horizontally. Those line numbers might not even be for the same file.
  372. // One space would be enough to achieve that, but more makes it even easier
  373. // to see.
  374. LabelWidth = std::max(LabelWidth, LineNoWidth) + 3;
  375. // Print annotated input lines.
  376. auto AnnotationItr = Annotations.begin(), AnnotationEnd = Annotations.end();
  377. for (unsigned Line = 1;
  378. InputFilePtr != InputFileEnd || AnnotationItr != AnnotationEnd;
  379. ++Line) {
  380. const unsigned char *InputFileLine = InputFilePtr;
  381. // Print right-aligned line number.
  382. WithColor(OS, raw_ostream::BLACK, true)
  383. << format_decimal(Line, LabelWidth) << ": ";
  384. // For the case where -v and colors are enabled, find the annotations for
  385. // good matches for expected patterns in order to highlight everything
  386. // else in the line. There are no such annotations if -v is disabled.
  387. std::vector<InputAnnotation> FoundAndExpectedMatches;
  388. if (Req.Verbose && WithColor(OS).colorsEnabled()) {
  389. for (auto I = AnnotationItr; I != AnnotationEnd && I->InputLine == Line;
  390. ++I) {
  391. if (I->FoundAndExpectedMatch)
  392. FoundAndExpectedMatches.push_back(*I);
  393. }
  394. }
  395. // Print numbered line with highlighting where there are no matches for
  396. // expected patterns.
  397. bool Newline = false;
  398. {
  399. WithColor COS(OS);
  400. bool InMatch = false;
  401. if (Req.Verbose)
  402. COS.changeColor(raw_ostream::CYAN, true, true);
  403. for (unsigned Col = 1; InputFilePtr != InputFileEnd && !Newline; ++Col) {
  404. bool WasInMatch = InMatch;
  405. InMatch = false;
  406. for (auto M : FoundAndExpectedMatches) {
  407. if (M.InputStartCol <= Col && Col < M.InputEndCol) {
  408. InMatch = true;
  409. break;
  410. }
  411. }
  412. if (!WasInMatch && InMatch)
  413. COS.resetColor();
  414. else if (WasInMatch && !InMatch)
  415. COS.changeColor(raw_ostream::CYAN, true, true);
  416. if (*InputFilePtr == '\n')
  417. Newline = true;
  418. else
  419. COS << *InputFilePtr;
  420. ++InputFilePtr;
  421. }
  422. }
  423. OS << '\n';
  424. unsigned InputLineWidth = InputFilePtr - InputFileLine - Newline;
  425. // Print any annotations.
  426. while (AnnotationItr != AnnotationEnd &&
  427. AnnotationItr->InputLine == Line) {
  428. WithColor COS(OS, AnnotationItr->Marker.Color, true);
  429. // The two spaces below are where the ": " appears on input lines.
  430. COS << left_justify(AnnotationItr->Label, LabelWidth) << " ";
  431. unsigned Col;
  432. for (Col = 1; Col < AnnotationItr->InputStartCol; ++Col)
  433. COS << ' ';
  434. COS << AnnotationItr->Marker.Lead;
  435. // If InputEndCol=UINT_MAX, stop at InputLineWidth.
  436. for (++Col; Col < AnnotationItr->InputEndCol && Col <= InputLineWidth;
  437. ++Col)
  438. COS << '~';
  439. const std::string &Note = AnnotationItr->Marker.Note;
  440. if (!Note.empty()) {
  441. // Put the note at the end of the input line. If we were to instead
  442. // put the note right after the marker, subsequent annotations for the
  443. // same input line might appear to mark this note instead of the input
  444. // line.
  445. for (; Col <= InputLineWidth; ++Col)
  446. COS << ' ';
  447. COS << ' ' << Note;
  448. }
  449. COS << '\n';
  450. ++AnnotationItr;
  451. }
  452. }
  453. OS << ">>>>>>\n";
  454. }
  455. int main(int argc, char **argv) {
  456. // Enable use of ANSI color codes because FileCheck is using them to
  457. // highlight text.
  458. llvm::sys::Process::UseANSIEscapeCodes(true);
  459. InitLLVM X(argc, argv);
  460. cl::ParseCommandLineOptions(argc, argv, /*Overview*/ "", /*Errs*/ nullptr,
  461. "FILECHECK_OPTS");
  462. if (DumpInput == DumpInputHelp) {
  463. DumpInputAnnotationHelp(outs());
  464. return 0;
  465. }
  466. if (CheckFilename.empty()) {
  467. errs() << "<check-file> not specified\n";
  468. return 2;
  469. }
  470. FileCheckRequest Req;
  471. for (auto Prefix : CheckPrefixes)
  472. Req.CheckPrefixes.push_back(Prefix);
  473. for (auto CheckNot : ImplicitCheckNot)
  474. Req.ImplicitCheckNot.push_back(CheckNot);
  475. for (auto G : GlobalDefines)
  476. Req.GlobalDefines.push_back(G);
  477. Req.AllowEmptyInput = AllowEmptyInput;
  478. Req.EnableVarScope = EnableVarScope;
  479. Req.AllowDeprecatedDagOverlap = AllowDeprecatedDagOverlap;
  480. Req.Verbose = Verbose;
  481. Req.VerboseVerbose = VerboseVerbose;
  482. Req.NoCanonicalizeWhiteSpace = NoCanonicalizeWhiteSpace;
  483. Req.MatchFullLines = MatchFullLines;
  484. if (VerboseVerbose)
  485. Req.Verbose = true;
  486. FileCheck FC(Req);
  487. if (!FC.ValidateCheckPrefixes()) {
  488. errs() << "Supplied check-prefix is invalid! Prefixes must be unique and "
  489. "start with a letter and contain only alphanumeric characters, "
  490. "hyphens and underscores\n";
  491. return 2;
  492. }
  493. Regex PrefixRE = FC.buildCheckPrefixRegex();
  494. std::string REError;
  495. if (!PrefixRE.isValid(REError)) {
  496. errs() << "Unable to combine check-prefix strings into a prefix regular "
  497. "expression! This is likely a bug in FileCheck's verification of "
  498. "the check-prefix strings. Regular expression parsing failed "
  499. "with the following error: "
  500. << REError << "\n";
  501. return 2;
  502. }
  503. SourceMgr SM;
  504. // Read the expected strings from the check file.
  505. ErrorOr<std::unique_ptr<MemoryBuffer>> CheckFileOrErr =
  506. MemoryBuffer::getFileOrSTDIN(CheckFilename);
  507. if (std::error_code EC = CheckFileOrErr.getError()) {
  508. errs() << "Could not open check file '" << CheckFilename
  509. << "': " << EC.message() << '\n';
  510. return 2;
  511. }
  512. MemoryBuffer &CheckFile = *CheckFileOrErr.get();
  513. SmallString<4096> CheckFileBuffer;
  514. StringRef CheckFileText = FC.CanonicalizeFile(CheckFile, CheckFileBuffer);
  515. SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
  516. CheckFileText, CheckFile.getBufferIdentifier()),
  517. SMLoc());
  518. std::vector<FileCheckString> CheckStrings;
  519. if (FC.ReadCheckFile(SM, CheckFileText, PrefixRE, CheckStrings))
  520. return 2;
  521. // Open the file to check and add it to SourceMgr.
  522. ErrorOr<std::unique_ptr<MemoryBuffer>> InputFileOrErr =
  523. MemoryBuffer::getFileOrSTDIN(InputFilename);
  524. if (std::error_code EC = InputFileOrErr.getError()) {
  525. errs() << "Could not open input file '" << InputFilename
  526. << "': " << EC.message() << '\n';
  527. return 2;
  528. }
  529. MemoryBuffer &InputFile = *InputFileOrErr.get();
  530. if (InputFile.getBufferSize() == 0 && !AllowEmptyInput) {
  531. errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
  532. DumpCommandLine(argc, argv);
  533. return 2;
  534. }
  535. SmallString<4096> InputFileBuffer;
  536. StringRef InputFileText = FC.CanonicalizeFile(InputFile, InputFileBuffer);
  537. SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
  538. InputFileText, InputFile.getBufferIdentifier()),
  539. SMLoc());
  540. if (DumpInput == DumpInputDefault)
  541. DumpInput = DumpInputOnFailure ? DumpInputFail : DumpInputNever;
  542. std::vector<FileCheckDiag> Diags;
  543. int ExitCode = FC.CheckInput(SM, InputFileText, CheckStrings,
  544. DumpInput == DumpInputNever ? nullptr : &Diags)
  545. ? EXIT_SUCCESS
  546. : 1;
  547. if (DumpInput == DumpInputAlways ||
  548. (ExitCode == 1 && DumpInput == DumpInputFail)) {
  549. errs() << "\n"
  550. << "Input file: "
  551. << (InputFilename == "-" ? "<stdin>" : InputFilename.getValue())
  552. << "\n"
  553. << "Check file: " << CheckFilename << "\n"
  554. << "\n"
  555. << "-dump-input=help describes the format of the following dump.\n"
  556. << "\n";
  557. std::vector<InputAnnotation> Annotations;
  558. unsigned LabelWidth;
  559. BuildInputAnnotations(Diags, Annotations, LabelWidth);
  560. DumpAnnotatedInput(errs(), Req, InputFileText, Annotations, LabelWidth);
  561. }
  562. return ExitCode;
  563. }