FileCheck.cpp 25 KB

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