1ee3c74fbSChris Lattner //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2ee3c74fbSChris Lattner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ee3c74fbSChris Lattner //
7ee3c74fbSChris Lattner //===----------------------------------------------------------------------===//
8ee3c74fbSChris Lattner //
9ee3c74fbSChris Lattner // FileCheck does a line-by line check of a file that validates whether it
10ee3c74fbSChris Lattner // contains the expected content.  This is useful for regression tests etc.
11ee3c74fbSChris Lattner //
12b5ecceffSJames Henderson // This program exits with an exit status of 2 on error, exit status of 0 if
13ee3c74fbSChris Lattner // the file matched the expected contents, and exit status of 1 if it did not
14ee3c74fbSChris Lattner // contain the expected contents.
15ee3c74fbSChris Lattner //
16ee3c74fbSChris Lattner //===----------------------------------------------------------------------===//
17ee3c74fbSChris Lattner 
185ffd940aSRaphael Isemann #include "llvm/FileCheck/FileCheck.h"
19ee3c74fbSChris Lattner #include "llvm/Support/CommandLine.h"
20197194b6SRui Ueyama #include "llvm/Support/InitLLVM.h"
213e66509fSJoel E. Denny #include "llvm/Support/Process.h"
223c5d267eSJoel E. Denny #include "llvm/Support/WithColor.h"
23ee3c74fbSChris Lattner #include "llvm/Support/raw_ostream.h"
24010982f7SRainer Orth #include <cmath>
25ee3c74fbSChris Lattner using namespace llvm;
26ee3c74fbSChris Lattner 
27dbb757f4SJoel E. Denny static cl::extrahelp FileCheckOptsEnv(
28dbb757f4SJoel E. Denny     "\nOptions are parsed from the environment variable FILECHECK_OPTS and\n"
29dbb757f4SJoel E. Denny     "from the command line.\n");
30dbb757f4SJoel E. Denny 
31ee3c74fbSChris Lattner static cl::opt<std::string>
323c5d267eSJoel E. Denny     CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Optional);
33ee3c74fbSChris Lattner 
34ee3c74fbSChris Lattner static cl::opt<std::string>
35ee3c74fbSChris Lattner     InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
36ee3c74fbSChris Lattner                   cl::init("-"), cl::value_desc("filename"));
37ee3c74fbSChris Lattner 
38e8f2fb20SChandler Carruth static cl::list<std::string> CheckPrefixes(
39e8f2fb20SChandler Carruth     "check-prefix",
40ee3c74fbSChris Lattner     cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
41fd557cb0SDaniel Sanders static cl::alias CheckPrefixesAlias(
42fd557cb0SDaniel Sanders     "check-prefixes", cl::aliasopt(CheckPrefixes), cl::CommaSeparated,
43fd557cb0SDaniel Sanders     cl::NotHidden,
44fd557cb0SDaniel Sanders     cl::desc(
45fd557cb0SDaniel Sanders         "Alias for -check-prefix permitting multiple comma separated values"));
46ee3c74fbSChris Lattner 
47a1fd1882SJoel E. Denny static cl::list<std::string> CommentPrefixes(
48a1fd1882SJoel E. Denny     "comment-prefixes", cl::CommaSeparated, cl::Hidden,
49a1fd1882SJoel E. Denny     cl::desc("Comma-separated list of comment prefixes to use from check file\n"
50a1fd1882SJoel E. Denny              "(defaults to 'COM,RUN'). Please avoid using this feature in\n"
51a1fd1882SJoel E. Denny              "LLVM's LIT-based test suites, which should be easier to\n"
52a1fd1882SJoel E. Denny              "maintain if they all follow a consistent comment style. This\n"
53a1fd1882SJoel E. Denny              "feature is meant for non-LIT test suites using FileCheck."));
54a1fd1882SJoel E. Denny 
55e8f2fb20SChandler Carruth static cl::opt<bool> NoCanonicalizeWhiteSpace(
56e8f2fb20SChandler Carruth     "strict-whitespace",
572c3e5cdfSChris Lattner     cl::desc("Do not treat all horizontal whitespace as equivalent"));
582c3e5cdfSChris Lattner 
595b5b2fd2SKai Nacke static cl::opt<bool> IgnoreCase(
605b5b2fd2SKai Nacke     "ignore-case",
615b5b2fd2SKai Nacke     cl::desc("Use case-insensitive matching"));
625b5b2fd2SKai Nacke 
6356ccdbbdSAlexander Kornienko static cl::list<std::string> ImplicitCheckNot(
6456ccdbbdSAlexander Kornienko     "implicit-check-not",
6556ccdbbdSAlexander Kornienko     cl::desc("Add an implicit negative check with this pattern to every\n"
6656ccdbbdSAlexander Kornienko              "positive check. This can be used to ensure that no instances of\n"
6756ccdbbdSAlexander Kornienko              "this pattern occur which are not matched by a positive pattern"),
6856ccdbbdSAlexander Kornienko     cl::value_desc("pattern"));
6956ccdbbdSAlexander Kornienko 
70a5e233bfSThomas Preud'homme static cl::list<std::string>
71a5e233bfSThomas Preud'homme     GlobalDefines("D", cl::AlwaysPrefix,
7246e1fd61SAlexander Richardson                   cl::desc("Define a variable to be used in capture patterns."),
7346e1fd61SAlexander Richardson                   cl::value_desc("VAR=VALUE"));
7446e1fd61SAlexander Richardson 
751b9f936fSJustin Bogner static cl::opt<bool> AllowEmptyInput(
761b9f936fSJustin Bogner     "allow-empty", cl::init(false),
771b9f936fSJustin Bogner     cl::desc("Allow the input file to be empty. This is useful when making\n"
781b9f936fSJustin Bogner              "checks that some error message does not occur, for example."));
791b9f936fSJustin Bogner 
80871d658cSMircea Trofin static cl::opt<bool> AllowUnusedPrefixes(
81*87dbdd2eSFangrui Song     "allow-unused-prefixes", cl::init(false), cl::ZeroOrMore,
82871d658cSMircea Trofin     cl::desc("Allow prefixes to be specified but not appear in the test."));
83871d658cSMircea Trofin 
8485913ccaSJames Y Knight static cl::opt<bool> MatchFullLines(
8585913ccaSJames Y Knight     "match-full-lines", cl::init(false),
8685913ccaSJames Y Knight     cl::desc("Require all positive matches to cover an entire input line.\n"
8785913ccaSJames Y Knight              "Allows leading and trailing whitespace if --strict-whitespace\n"
8885913ccaSJames Y Knight              "is not also passed."));
8985913ccaSJames Y Knight 
90f55e72a5SArtem Belevich static cl::opt<bool> EnableVarScope(
91f55e72a5SArtem Belevich     "enable-var-scope", cl::init(false),
92f55e72a5SArtem Belevich     cl::desc("Enables scope for regex variables. Variables with names that\n"
93f55e72a5SArtem Belevich              "do not start with '$' will be reset at the beginning of\n"
94f55e72a5SArtem Belevich              "each CHECK-LABEL block."));
95f55e72a5SArtem Belevich 
96bcf5b441SJoel E. Denny static cl::opt<bool> AllowDeprecatedDagOverlap(
97bcf5b441SJoel E. Denny     "allow-deprecated-dag-overlap", cl::init(false),
98bcf5b441SJoel E. Denny     cl::desc("Enable overlapping among matches in a group of consecutive\n"
99bcf5b441SJoel E. Denny              "CHECK-DAG directives.  This option is deprecated and is only\n"
100bcf5b441SJoel E. Denny              "provided for convenience as old tests are migrated to the new\n"
101bcf5b441SJoel E. Denny              "non-overlapping CHECK-DAG implementation.\n"));
102bcf5b441SJoel E. Denny 
103352695c3SJoel E. Denny static cl::opt<bool> Verbose(
104782585a2SJoel E. Denny     "v", cl::init(false), cl::ZeroOrMore,
105352695c3SJoel E. Denny     cl::desc("Print directive pattern matches, or add them to the input dump\n"
106352695c3SJoel E. Denny              "if enabled.\n"));
107dc5ba317SJoel E. Denny 
108dc5ba317SJoel E. Denny static cl::opt<bool> VerboseVerbose(
109782585a2SJoel E. Denny     "vv", cl::init(false), cl::ZeroOrMore,
110dc5ba317SJoel E. Denny     cl::desc("Print information helpful in diagnosing internal FileCheck\n"
111352695c3SJoel E. Denny              "issues, or add it to the input dump if enabled.  Implies\n"
112352695c3SJoel E. Denny              "-v.\n"));
1133c5d267eSJoel E. Denny 
114fdde18a7SJoel E. Denny // The order of DumpInputValue members affects their precedence, as documented
115fdde18a7SJoel E. Denny // for -dump-input below.
1163c5d267eSJoel E. Denny enum DumpInputValue {
1173c5d267eSJoel E. Denny   DumpInputNever,
1183c5d267eSJoel E. Denny   DumpInputFail,
119fdde18a7SJoel E. Denny   DumpInputAlways,
120fdde18a7SJoel E. Denny   DumpInputHelp
1213c5d267eSJoel E. Denny };
1223c5d267eSJoel E. Denny 
123fdde18a7SJoel E. Denny static cl::list<DumpInputValue> DumpInputs(
124fdde18a7SJoel E. Denny     "dump-input",
1253c5d267eSJoel E. Denny     cl::desc("Dump input to stderr, adding annotations representing\n"
126fdde18a7SJoel E. Denny              "currently enabled diagnostics.  When there are multiple\n"
127fdde18a7SJoel E. Denny              "occurrences of this option, the <value> that appears earliest\n"
128839f8e4fSJoel E. Denny              "in the list below has precedence.  The default is 'fail'.\n"),
1293c5d267eSJoel E. Denny     cl::value_desc("mode"),
130839f8e4fSJoel E. Denny     cl::values(clEnumValN(DumpInputHelp, "help", "Explain input dump and quit"),
131fdde18a7SJoel E. Denny                clEnumValN(DumpInputAlways, "always", "Always dump input"),
1323c5d267eSJoel E. Denny                clEnumValN(DumpInputFail, "fail", "Dump input on failure"),
133fdde18a7SJoel E. Denny                clEnumValN(DumpInputNever, "never", "Never dump input")));
134dc5ba317SJoel E. Denny 
1359fd4b5faSJoel E. Denny // The order of DumpInputFilterValue members affects their precedence, as
1369fd4b5faSJoel E. Denny // documented for -dump-input-filter below.
1379fd4b5faSJoel E. Denny enum DumpInputFilterValue {
1389fd4b5faSJoel E. Denny   DumpInputFilterError,
1399fd4b5faSJoel E. Denny   DumpInputFilterAnnotation,
1409fd4b5faSJoel E. Denny   DumpInputFilterAnnotationFull,
1419fd4b5faSJoel E. Denny   DumpInputFilterAll
1429fd4b5faSJoel E. Denny };
1439fd4b5faSJoel E. Denny 
1449fd4b5faSJoel E. Denny static cl::list<DumpInputFilterValue> DumpInputFilters(
1459fd4b5faSJoel E. Denny     "dump-input-filter",
1469fd4b5faSJoel E. Denny     cl::desc("In the dump requested by -dump-input, print only input lines of\n"
1476dda6ff0SJoel E. Denny              "kind <value> plus any context specified by -dump-input-context.\n"
1486dda6ff0SJoel E. Denny              "When there are multiple occurrences of this option, the <value>\n"
1499fd4b5faSJoel E. Denny              "that appears earliest in the list below has precedence.  The\n"
1509fd4b5faSJoel E. Denny              "default is 'error' when -dump-input=fail, and it's 'all' when\n"
1519fd4b5faSJoel E. Denny              "-dump-input=always.\n"),
1529fd4b5faSJoel E. Denny     cl::values(clEnumValN(DumpInputFilterAll, "all", "All input lines"),
1539fd4b5faSJoel E. Denny                clEnumValN(DumpInputFilterAnnotationFull, "annotation-full",
1549fd4b5faSJoel E. Denny                           "Input lines with annotations"),
1559fd4b5faSJoel E. Denny                clEnumValN(DumpInputFilterAnnotation, "annotation",
1569fd4b5faSJoel E. Denny                           "Input lines with starting points of annotations"),
1579fd4b5faSJoel E. Denny                clEnumValN(DumpInputFilterError, "error",
1589fd4b5faSJoel E. Denny                           "Input lines with starting points of error "
1599fd4b5faSJoel E. Denny                           "annotations")));
1609fd4b5faSJoel E. Denny 
161bce8fcedSJoel E. Denny static cl::list<unsigned> DumpInputContexts(
162bce8fcedSJoel E. Denny     "dump-input-context", cl::value_desc("N"),
1639fd4b5faSJoel E. Denny     cl::desc("In the dump requested by -dump-input, print <N> input lines\n"
1649fd4b5faSJoel E. Denny              "before and <N> input lines after any lines specified by\n"
1659fd4b5faSJoel E. Denny              "-dump-input-filter.  When there are multiple occurrences of\n"
166bce8fcedSJoel E. Denny              "this option, the largest specified <N> has precedence.  The\n"
167bce8fcedSJoel E. Denny              "default is 5.\n"));
168bce8fcedSJoel E. Denny 
16913df4626SMatt Arsenault typedef cl::list<std::string>::const_iterator prefix_iterator;
17013df4626SMatt Arsenault 
17113df4626SMatt Arsenault 
17213df4626SMatt Arsenault 
173726774cbSChandler Carruth 
174726774cbSChandler Carruth 
175726774cbSChandler Carruth 
176c2735158SRui Ueyama 
1772bd4f8b6SXinliang David Li static void DumpCommandLine(int argc, char **argv) {
1782bd4f8b6SXinliang David Li   errs() << "FileCheck command line: ";
1792bd4f8b6SXinliang David Li   for (int I = 0; I < argc; I++)
1802bd4f8b6SXinliang David Li     errs() << " " << argv[I];
1812bd4f8b6SXinliang David Li   errs() << "\n";
1822bd4f8b6SXinliang David Li }
1832bd4f8b6SXinliang David Li 
1843c5d267eSJoel E. Denny struct MarkerStyle {
1853c5d267eSJoel E. Denny   /// The starting char (before tildes) for marking the line.
1863c5d267eSJoel E. Denny   char Lead;
1873c5d267eSJoel E. Denny   /// What color to use for this annotation.
1884d41c332SRui Ueyama   raw_ostream::Colors Color;
1893c5d267eSJoel E. Denny   /// A note to follow the marker, or empty string if none.
1903c5d267eSJoel E. Denny   std::string Note;
1919fd4b5faSJoel E. Denny   /// Does this marker indicate inclusion by -dump-input-filter=error?
192bce8fcedSJoel E. Denny   bool FiltersAsError;
1933c5d267eSJoel E. Denny   MarkerStyle() {}
1944d41c332SRui Ueyama   MarkerStyle(char Lead, raw_ostream::Colors Color,
195bce8fcedSJoel E. Denny               const std::string &Note = "", bool FiltersAsError = false)
196bce8fcedSJoel E. Denny       : Lead(Lead), Color(Color), Note(Note), FiltersAsError(FiltersAsError) {
197bce8fcedSJoel E. Denny     assert((!FiltersAsError || !Note.empty()) &&
198bce8fcedSJoel E. Denny            "expected error diagnostic to have note");
199bce8fcedSJoel E. Denny   }
2003c5d267eSJoel E. Denny };
2013c5d267eSJoel E. Denny 
2023c5d267eSJoel E. Denny static MarkerStyle GetMarker(FileCheckDiag::MatchType MatchTy) {
2033c5d267eSJoel E. Denny   switch (MatchTy) {
204e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundAndExpected:
2057df86967SJoel E. Denny     return MarkerStyle('^', raw_ostream::GREEN);
206e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundButExcluded:
207bce8fcedSJoel E. Denny     return MarkerStyle('!', raw_ostream::RED, "error: no match expected",
208bce8fcedSJoel E. Denny                        /*FiltersAsError=*/true);
209e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundButWrongLine:
210bce8fcedSJoel E. Denny     return MarkerStyle('!', raw_ostream::RED, "error: match on wrong line",
211bce8fcedSJoel E. Denny                        /*FiltersAsError=*/true);
212e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundButDiscarded:
213f7c1c4d8SJoel E. Denny     return MarkerStyle('!', raw_ostream::CYAN,
214f7c1c4d8SJoel E. Denny                        "discard: overlaps earlier match");
21596f0e84cSJoel E. Denny   case FileCheckDiag::MatchNoneAndExcluded:
21696f0e84cSJoel E. Denny     return MarkerStyle('X', raw_ostream::GREEN);
2173c5d267eSJoel E. Denny   case FileCheckDiag::MatchNoneButExpected:
218bce8fcedSJoel E. Denny     return MarkerStyle('X', raw_ostream::RED, "error: no match found",
219bce8fcedSJoel E. Denny                        /*FiltersAsError=*/true);
2202c007c80SJoel E. Denny   case FileCheckDiag::MatchFuzzy:
221bce8fcedSJoel E. Denny     return MarkerStyle('?', raw_ostream::MAGENTA, "possible intended match",
222bce8fcedSJoel E. Denny                        /*FiltersAsError=*/true);
2233c5d267eSJoel E. Denny   }
2243c5d267eSJoel E. Denny   llvm_unreachable_internal("unexpected match type");
2253c5d267eSJoel E. Denny }
2263c5d267eSJoel E. Denny 
2273c5d267eSJoel E. Denny static void DumpInputAnnotationHelp(raw_ostream &OS) {
2283c5d267eSJoel E. Denny   OS << "The following description was requested by -dump-input=help to\n"
229839f8e4fSJoel E. Denny      << "explain the input dump printed by FileCheck.\n"
230839f8e4fSJoel E. Denny      << "\n"
231839f8e4fSJoel E. Denny      << "Related command-line options:\n"
2326dda6ff0SJoel E. Denny      << "\n"
233839f8e4fSJoel E. Denny      << "  - -dump-input=<value> enables or disables the input dump\n"
2346dda6ff0SJoel E. Denny      << "  - -dump-input-filter=<value> filters the input lines\n"
2359fd4b5faSJoel E. Denny      << "  - -dump-input-context=<N> adjusts the context of filtered lines\n"
236839f8e4fSJoel E. Denny      << "  - -v and -vv add more annotations\n"
237839f8e4fSJoel E. Denny      << "  - -color forces colors to be enabled both in the dump and below\n"
238839f8e4fSJoel E. Denny      << "  - -help documents the above options in more detail\n"
239839f8e4fSJoel E. Denny      << "\n"
2406dda6ff0SJoel E. Denny      << "These options can also be set via FILECHECK_OPTS.  For example, for\n"
2416dda6ff0SJoel E. Denny      << "maximum debugging output on failures:\n"
2426dda6ff0SJoel E. Denny      << "\n"
2436dda6ff0SJoel E. Denny      << "  $ FILECHECK_OPTS='-dump-input-filter=all -vv -color' ninja check\n"
2446dda6ff0SJoel E. Denny      << "\n"
2456dda6ff0SJoel E. Denny      << "Input dump annotation format:\n"
2466dda6ff0SJoel E. Denny      << "\n";
2473c5d267eSJoel E. Denny 
2483c5d267eSJoel E. Denny   // Labels for input lines.
2493c5d267eSJoel E. Denny   OS << "  - ";
2503c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "L:";
2513c5d267eSJoel E. Denny   OS << "     labels line number L of the input file\n";
2523c5d267eSJoel E. Denny 
2533c5d267eSJoel E. Denny   // Labels for annotation lines.
2543c5d267eSJoel E. Denny   OS << "  - ";
2553c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L";
256b5a24610SJoel E. Denny   OS << "    labels the only match result for either (1) a pattern of type T"
257b5a24610SJoel E. Denny      << " from\n"
258b5a24610SJoel E. Denny      << "           line L of the check file if L is an integer or (2) the"
259b5a24610SJoel E. Denny      << " I-th implicit\n"
260b5a24610SJoel E. Denny      << "           pattern if L is \"imp\" followed by an integer "
261b5a24610SJoel E. Denny      << "I (index origin one)\n";
2622c007c80SJoel E. Denny   OS << "  - ";
2632c007c80SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L'N";
264b5a24610SJoel E. Denny   OS << "  labels the Nth match result for such a pattern\n";
2653c5d267eSJoel E. Denny 
2663c5d267eSJoel E. Denny   // Markers on annotation lines.
2673c5d267eSJoel E. Denny   OS << "  - ";
2687df86967SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "^~~";
2697df86967SJoel E. Denny   OS << "    marks good match (reported if -v)\n"
2707df86967SJoel E. Denny      << "  - ";
271cadfcef4SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "!~~";
272cadfcef4SJoel E. Denny   OS << "    marks bad match, such as:\n"
273cadfcef4SJoel E. Denny      << "           - CHECK-NEXT on same line as previous match (error)\n"
2740e7e3fa0SJoel E. Denny      << "           - CHECK-NOT found (error)\n"
275f7c1c4d8SJoel E. Denny      << "           - CHECK-DAG overlapping match (discarded, reported if "
276f7c1c4d8SJoel E. Denny      << "-vv)\n"
277cadfcef4SJoel E. Denny      << "  - ";
2783c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "X~~";
279cadfcef4SJoel E. Denny   OS << "    marks search range when no match is found, such as:\n"
280cadfcef4SJoel E. Denny      << "           - CHECK-NEXT not found (error)\n"
28196f0e84cSJoel E. Denny      << "           - CHECK-NOT not found (success, reported if -vv)\n"
282f7c1c4d8SJoel E. Denny      << "           - CHECK-DAG not found after discarded matches (error)\n"
2832c007c80SJoel E. Denny      << "  - ";
2842c007c80SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "?";
2852c007c80SJoel E. Denny   OS << "      marks fuzzy match when no match is found\n";
2863c5d267eSJoel E. Denny 
287bce8fcedSJoel E. Denny   // Elided lines.
288bce8fcedSJoel E. Denny   OS << "  - ";
289bce8fcedSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "...";
290bce8fcedSJoel E. Denny   OS << "    indicates elided input lines and annotations, as specified by\n"
2919fd4b5faSJoel E. Denny      << "           -dump-input-filter and -dump-input-context\n";
292bce8fcedSJoel E. Denny 
2933c5d267eSJoel E. Denny   // Colors.
2943c5d267eSJoel E. Denny   OS << "  - colors ";
2957df86967SJoel E. Denny   WithColor(OS, raw_ostream::GREEN, true) << "success";
2967df86967SJoel E. Denny   OS << ", ";
2973c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::RED, true) << "error";
2982c007c80SJoel E. Denny   OS << ", ";
2992c007c80SJoel E. Denny   WithColor(OS, raw_ostream::MAGENTA, true) << "fuzzy match";
3007df86967SJoel E. Denny   OS << ", ";
301f7c1c4d8SJoel E. Denny   WithColor(OS, raw_ostream::CYAN, true, false) << "discarded match";
302f7c1c4d8SJoel E. Denny   OS << ", ";
3037df86967SJoel E. Denny   WithColor(OS, raw_ostream::CYAN, true, true) << "unmatched input";
304839f8e4fSJoel E. Denny   OS << "\n";
3053c5d267eSJoel E. Denny }
3063c5d267eSJoel E. Denny 
3073c5d267eSJoel E. Denny /// An annotation for a single input line.
3083c5d267eSJoel E. Denny struct InputAnnotation {
309ce685455SJoel E. Denny   /// The index of the match result across all checks
310ce685455SJoel E. Denny   unsigned DiagIndex;
3113c5d267eSJoel E. Denny   /// The label for this annotation.
3123c5d267eSJoel E. Denny   std::string Label;
313bce8fcedSJoel E. Denny   /// Is this the initial fragment of a diagnostic that has been broken across
314bce8fcedSJoel E. Denny   /// multiple lines?
315bce8fcedSJoel E. Denny   bool IsFirstLine;
3163c5d267eSJoel E. Denny   /// What input line (one-origin indexing) this annotation marks.  This might
317bce8fcedSJoel E. Denny   /// be different from the starting line of the original diagnostic if
318bce8fcedSJoel E. Denny   /// !IsFirstLine.
3193c5d267eSJoel E. Denny   unsigned InputLine;
320ce685455SJoel E. Denny   /// The column range (one-origin indexing, open end) in which to mark the
3213c5d267eSJoel E. Denny   /// input line.  If InputEndCol is UINT_MAX, treat it as the last column
3223c5d267eSJoel E. Denny   /// before the newline.
3233c5d267eSJoel E. Denny   unsigned InputStartCol, InputEndCol;
3243c5d267eSJoel E. Denny   /// The marker to use.
3253c5d267eSJoel E. Denny   MarkerStyle Marker;
326e2afb614SJoel E. Denny   /// Whether this annotation represents a good match for an expected pattern.
327e2afb614SJoel E. Denny   bool FoundAndExpectedMatch;
3283c5d267eSJoel E. Denny };
3293c5d267eSJoel E. Denny 
3303c5d267eSJoel E. Denny /// Get an abbreviation for the check type.
33120e9c36cSFangrui Song static std::string GetCheckTypeAbbreviation(Check::FileCheckType Ty) {
3323c5d267eSJoel E. Denny   switch (Ty) {
3333c5d267eSJoel E. Denny   case Check::CheckPlain:
3343c5d267eSJoel E. Denny     if (Ty.getCount() > 1)
3353c5d267eSJoel E. Denny       return "count";
3363c5d267eSJoel E. Denny     return "check";
3373c5d267eSJoel E. Denny   case Check::CheckNext:
3383c5d267eSJoel E. Denny     return "next";
3393c5d267eSJoel E. Denny   case Check::CheckSame:
3403c5d267eSJoel E. Denny     return "same";
3413c5d267eSJoel E. Denny   case Check::CheckNot:
3423c5d267eSJoel E. Denny     return "not";
3433c5d267eSJoel E. Denny   case Check::CheckDAG:
3443c5d267eSJoel E. Denny     return "dag";
3453c5d267eSJoel E. Denny   case Check::CheckLabel:
3463c5d267eSJoel E. Denny     return "label";
3473c5d267eSJoel E. Denny   case Check::CheckEmpty:
3483c5d267eSJoel E. Denny     return "empty";
349a1fd1882SJoel E. Denny   case Check::CheckComment:
350a1fd1882SJoel E. Denny     return "com";
3513c5d267eSJoel E. Denny   case Check::CheckEOF:
3523c5d267eSJoel E. Denny     return "eof";
3533c5d267eSJoel E. Denny   case Check::CheckBadNot:
3543c5d267eSJoel E. Denny     return "bad-not";
3553c5d267eSJoel E. Denny   case Check::CheckBadCount:
3563c5d267eSJoel E. Denny     return "bad-count";
3573c5d267eSJoel E. Denny   case Check::CheckNone:
3583c5d267eSJoel E. Denny     llvm_unreachable("invalid FileCheckType");
3593c5d267eSJoel E. Denny   }
3603c5d267eSJoel E. Denny   llvm_unreachable("unknown FileCheckType");
3613c5d267eSJoel E. Denny }
3623c5d267eSJoel E. Denny 
363b5a24610SJoel E. Denny static void
364b5a24610SJoel E. Denny BuildInputAnnotations(const SourceMgr &SM, unsigned CheckFileBufferID,
365b5a24610SJoel E. Denny                       const std::pair<unsigned, unsigned> &ImpPatBufferIDRange,
366b5a24610SJoel E. Denny                       const std::vector<FileCheckDiag> &Diags,
3673c5d267eSJoel E. Denny                       std::vector<InputAnnotation> &Annotations,
3683c5d267eSJoel E. Denny                       unsigned &LabelWidth) {
369ce685455SJoel E. Denny   // How many diagnostics have we seen so far?
370ce685455SJoel E. Denny   unsigned DiagCount = 0;
3712c007c80SJoel E. Denny   // How many diagnostics has the current check seen so far?
3722c007c80SJoel E. Denny   unsigned CheckDiagCount = 0;
3733c5d267eSJoel E. Denny   // What's the widest label?
3743c5d267eSJoel E. Denny   LabelWidth = 0;
3753c5d267eSJoel E. Denny   for (auto DiagItr = Diags.begin(), DiagEnd = Diags.end(); DiagItr != DiagEnd;
3763c5d267eSJoel E. Denny        ++DiagItr) {
3773c5d267eSJoel E. Denny     InputAnnotation A;
378ce685455SJoel E. Denny     A.DiagIndex = DiagCount++;
3793c5d267eSJoel E. Denny 
3803c5d267eSJoel E. Denny     // Build label, which uniquely identifies this check result.
381b5a24610SJoel E. Denny     unsigned CheckBufferID = SM.FindBufferContainingLoc(DiagItr->CheckLoc);
382b5a24610SJoel E. Denny     auto CheckLineAndCol =
383b5a24610SJoel E. Denny         SM.getLineAndColumn(DiagItr->CheckLoc, CheckBufferID);
3843c5d267eSJoel E. Denny     llvm::raw_string_ostream Label(A.Label);
385b5a24610SJoel E. Denny     Label << GetCheckTypeAbbreviation(DiagItr->CheckTy) << ":";
386b5a24610SJoel E. Denny     if (CheckBufferID == CheckFileBufferID)
387b5a24610SJoel E. Denny       Label << CheckLineAndCol.first;
388b5a24610SJoel E. Denny     else if (ImpPatBufferIDRange.first <= CheckBufferID &&
389b5a24610SJoel E. Denny              CheckBufferID < ImpPatBufferIDRange.second)
390b5a24610SJoel E. Denny       Label << "imp" << (CheckBufferID - ImpPatBufferIDRange.first + 1);
391b5a24610SJoel E. Denny     else
392b5a24610SJoel E. Denny       llvm_unreachable("expected diagnostic's check location to be either in "
393b5a24610SJoel E. Denny                        "the check file or for an implicit pattern");
394ce685455SJoel E. Denny     unsigned CheckDiagIndex = UINT_MAX;
3952c007c80SJoel E. Denny     auto DiagNext = std::next(DiagItr);
3962c007c80SJoel E. Denny     if (DiagNext != DiagEnd && DiagItr->CheckTy == DiagNext->CheckTy &&
397b5a24610SJoel E. Denny         DiagItr->CheckLoc == DiagNext->CheckLoc)
398ce685455SJoel E. Denny       CheckDiagIndex = CheckDiagCount++;
3992c007c80SJoel E. Denny     else if (CheckDiagCount) {
400ce685455SJoel E. Denny       CheckDiagIndex = CheckDiagCount;
4012c007c80SJoel E. Denny       CheckDiagCount = 0;
4022c007c80SJoel E. Denny     }
403ce685455SJoel E. Denny     if (CheckDiagIndex != UINT_MAX)
404ce685455SJoel E. Denny       Label << "'" << CheckDiagIndex;
4053c5d267eSJoel E. Denny     Label.flush();
4063c5d267eSJoel E. Denny     LabelWidth = std::max((std::string::size_type)LabelWidth, A.Label.size());
4073c5d267eSJoel E. Denny 
408608f2bfdSJoel E. Denny     A.Marker = GetMarker(DiagItr->MatchTy);
409d680711bSJoel E. Denny     if (!DiagItr->Note.empty()) {
410d680711bSJoel E. Denny       A.Marker.Note = DiagItr->Note;
411d680711bSJoel E. Denny       // It's less confusing if notes that don't actually have ranges don't have
412d680711bSJoel E. Denny       // markers.  For example, a marker for 'with "VAR" equal to "5"' would
413d680711bSJoel E. Denny       // seem to indicate where "VAR" matches, but the location we actually have
414d680711bSJoel E. Denny       // for the marker simply points to the start of the match/search range for
415d680711bSJoel E. Denny       // the full pattern of which the substitution is potentially just one
416d680711bSJoel E. Denny       // component.
417d680711bSJoel E. Denny       if (DiagItr->InputStartLine == DiagItr->InputEndLine &&
418d680711bSJoel E. Denny           DiagItr->InputStartCol == DiagItr->InputEndCol)
419d680711bSJoel E. Denny         A.Marker.Lead = ' ';
420d680711bSJoel E. Denny     }
421e2afb614SJoel E. Denny     A.FoundAndExpectedMatch =
422e2afb614SJoel E. Denny         DiagItr->MatchTy == FileCheckDiag::MatchFoundAndExpected;
4233c5d267eSJoel E. Denny 
4243c5d267eSJoel E. Denny     // Compute the mark location, and break annotation into multiple
4253c5d267eSJoel E. Denny     // annotations if it spans multiple lines.
426bce8fcedSJoel E. Denny     A.IsFirstLine = true;
4273c5d267eSJoel E. Denny     A.InputLine = DiagItr->InputStartLine;
4283c5d267eSJoel E. Denny     A.InputStartCol = DiagItr->InputStartCol;
4293c5d267eSJoel E. Denny     if (DiagItr->InputStartLine == DiagItr->InputEndLine) {
4303c5d267eSJoel E. Denny       // Sometimes ranges are empty in order to indicate a specific point, but
4313c5d267eSJoel E. Denny       // that would mean nothing would be marked, so adjust the range to
4323c5d267eSJoel E. Denny       // include the following character.
4333c5d267eSJoel E. Denny       A.InputEndCol =
4343c5d267eSJoel E. Denny           std::max(DiagItr->InputStartCol + 1, DiagItr->InputEndCol);
4353c5d267eSJoel E. Denny       Annotations.push_back(A);
4363c5d267eSJoel E. Denny     } else {
4373c5d267eSJoel E. Denny       assert(DiagItr->InputStartLine < DiagItr->InputEndLine &&
4383c5d267eSJoel E. Denny              "expected input range not to be inverted");
4393c5d267eSJoel E. Denny       A.InputEndCol = UINT_MAX;
4403c5d267eSJoel E. Denny       Annotations.push_back(A);
4413c5d267eSJoel E. Denny       for (unsigned L = DiagItr->InputStartLine + 1, E = DiagItr->InputEndLine;
4423c5d267eSJoel E. Denny            L <= E; ++L) {
4433c5d267eSJoel E. Denny         // If a range ends before the first column on a line, then it has no
4443c5d267eSJoel E. Denny         // characters on that line, so there's nothing to render.
445608f2bfdSJoel E. Denny         if (DiagItr->InputEndCol == 1 && L == E)
4463c5d267eSJoel E. Denny           break;
4473c5d267eSJoel E. Denny         InputAnnotation B;
448ce685455SJoel E. Denny         B.DiagIndex = A.DiagIndex;
4493c5d267eSJoel E. Denny         B.Label = A.Label;
450bce8fcedSJoel E. Denny         B.IsFirstLine = false;
4513c5d267eSJoel E. Denny         B.InputLine = L;
452608f2bfdSJoel E. Denny         B.Marker = A.Marker;
4533c5d267eSJoel E. Denny         B.Marker.Lead = '~';
4543c5d267eSJoel E. Denny         B.Marker.Note = "";
455608f2bfdSJoel E. Denny         B.InputStartCol = 1;
456608f2bfdSJoel E. Denny         if (L != E)
457608f2bfdSJoel E. Denny           B.InputEndCol = UINT_MAX;
458608f2bfdSJoel E. Denny         else
4593c5d267eSJoel E. Denny           B.InputEndCol = DiagItr->InputEndCol;
460e2afb614SJoel E. Denny         B.FoundAndExpectedMatch = A.FoundAndExpectedMatch;
4613c5d267eSJoel E. Denny         Annotations.push_back(B);
4623c5d267eSJoel E. Denny       }
4633c5d267eSJoel E. Denny     }
4643c5d267eSJoel E. Denny   }
4653c5d267eSJoel E. Denny }
4663c5d267eSJoel E. Denny 
467bce8fcedSJoel E. Denny static unsigned FindInputLineInFilter(
4689fd4b5faSJoel E. Denny     DumpInputFilterValue DumpInputFilter, unsigned CurInputLine,
469bce8fcedSJoel E. Denny     const std::vector<InputAnnotation>::iterator &AnnotationBeg,
470bce8fcedSJoel E. Denny     const std::vector<InputAnnotation>::iterator &AnnotationEnd) {
4719fd4b5faSJoel E. Denny   if (DumpInputFilter == DumpInputFilterAll)
472bce8fcedSJoel E. Denny     return CurInputLine;
473bce8fcedSJoel E. Denny   for (auto AnnotationItr = AnnotationBeg; AnnotationItr != AnnotationEnd;
474bce8fcedSJoel E. Denny        ++AnnotationItr) {
4759fd4b5faSJoel E. Denny     switch (DumpInputFilter) {
4769fd4b5faSJoel E. Denny     case DumpInputFilterAll:
4779fd4b5faSJoel E. Denny       llvm_unreachable("unexpected DumpInputFilterAll");
4789fd4b5faSJoel E. Denny       break;
4799fd4b5faSJoel E. Denny     case DumpInputFilterAnnotationFull:
4809fd4b5faSJoel E. Denny       return AnnotationItr->InputLine;
4819fd4b5faSJoel E. Denny     case DumpInputFilterAnnotation:
4829fd4b5faSJoel E. Denny       if (AnnotationItr->IsFirstLine)
4839fd4b5faSJoel E. Denny         return AnnotationItr->InputLine;
4849fd4b5faSJoel E. Denny       break;
4859fd4b5faSJoel E. Denny     case DumpInputFilterError:
486bce8fcedSJoel E. Denny       if (AnnotationItr->IsFirstLine && AnnotationItr->Marker.FiltersAsError)
487bce8fcedSJoel E. Denny         return AnnotationItr->InputLine;
4889fd4b5faSJoel E. Denny       break;
4899fd4b5faSJoel E. Denny     }
490bce8fcedSJoel E. Denny   }
491bce8fcedSJoel E. Denny   return UINT_MAX;
492bce8fcedSJoel E. Denny }
493bce8fcedSJoel E. Denny 
49477b6ddf1SJoel E. Denny /// To OS, print a vertical ellipsis (right-justified at LabelWidth) if it would
49577b6ddf1SJoel E. Denny /// occupy less lines than ElidedLines, but print ElidedLines otherwise.  Either
49677b6ddf1SJoel E. Denny /// way, clear ElidedLines.  Thus, if ElidedLines is empty, do nothing.
49777b6ddf1SJoel E. Denny static void DumpEllipsisOrElidedLines(raw_ostream &OS, std::string &ElidedLines,
49877b6ddf1SJoel E. Denny                                       unsigned LabelWidth) {
49977b6ddf1SJoel E. Denny   if (ElidedLines.empty())
50077b6ddf1SJoel E. Denny     return;
50177b6ddf1SJoel E. Denny   unsigned EllipsisLines = 3;
50277b6ddf1SJoel E. Denny   if (EllipsisLines < StringRef(ElidedLines).count('\n')) {
50377b6ddf1SJoel E. Denny     for (unsigned i = 0; i < EllipsisLines; ++i) {
50477b6ddf1SJoel E. Denny       WithColor(OS, raw_ostream::BLACK, /*Bold=*/true)
50577b6ddf1SJoel E. Denny           << right_justify(".", LabelWidth);
50677b6ddf1SJoel E. Denny       OS << '\n';
50777b6ddf1SJoel E. Denny     }
50877b6ddf1SJoel E. Denny   } else
50977b6ddf1SJoel E. Denny     OS << ElidedLines;
51077b6ddf1SJoel E. Denny   ElidedLines.clear();
51177b6ddf1SJoel E. Denny }
51277b6ddf1SJoel E. Denny 
5137df86967SJoel E. Denny static void DumpAnnotatedInput(raw_ostream &OS, const FileCheckRequest &Req,
5149fd4b5faSJoel E. Denny                                DumpInputFilterValue DumpInputFilter,
515bce8fcedSJoel E. Denny                                unsigned DumpInputContext,
5167df86967SJoel E. Denny                                StringRef InputFileText,
5177df86967SJoel E. Denny                                std::vector<InputAnnotation> &Annotations,
5187df86967SJoel E. Denny                                unsigned LabelWidth) {
519bce8fcedSJoel E. Denny   OS << "Input was:\n<<<<<<\n";
5203c5d267eSJoel E. Denny 
5213c5d267eSJoel E. Denny   // Sort annotations.
522a396e2e0SKazu Hirata   llvm::sort(Annotations,
5233c5d267eSJoel E. Denny              [](const InputAnnotation &A, const InputAnnotation &B) {
524ce685455SJoel E. Denny                // 1. Sort annotations in the order of the input lines.
525ce685455SJoel E. Denny                //
526ce685455SJoel E. Denny                // This makes it easier to find relevant annotations while
527ce685455SJoel E. Denny                // iterating input lines in the implementation below.  FileCheck
528ce685455SJoel E. Denny                // does not always produce diagnostics in the order of input
529ce685455SJoel E. Denny                // lines due to, for example, CHECK-DAG and CHECK-NOT.
5303c5d267eSJoel E. Denny                if (A.InputLine != B.InputLine)
5313c5d267eSJoel E. Denny                  return A.InputLine < B.InputLine;
532ce685455SJoel E. Denny                // 2. Sort annotations in the temporal order FileCheck produced
533ce685455SJoel E. Denny                // their associated diagnostics.
534ce685455SJoel E. Denny                //
535ce685455SJoel E. Denny                // This sort offers several benefits:
536ce685455SJoel E. Denny                //
537ce685455SJoel E. Denny                // A. On a single input line, the order of annotations reflects
538ce685455SJoel E. Denny                //    the FileCheck logic for processing directives/patterns.
539ce685455SJoel E. Denny                //    This can be helpful in understanding cases in which the
540ce685455SJoel E. Denny                //    order of the associated directives/patterns in the check
541ce685455SJoel E. Denny                //    file or on the command line either (i) does not match the
542ce685455SJoel E. Denny                //    temporal order in which FileCheck looks for matches for the
543ce685455SJoel E. Denny                //    directives/patterns (due to, for example, CHECK-LABEL,
544ce685455SJoel E. Denny                //    CHECK-NOT, or `--implicit-check-not`) or (ii) does match
545ce685455SJoel E. Denny                //    that order but does not match the order of those
546ce685455SJoel E. Denny                //    diagnostics along an input line (due to, for example,
547ce685455SJoel E. Denny                //    CHECK-DAG).
548ce685455SJoel E. Denny                //
549ce685455SJoel E. Denny                //    On the other hand, because our presentation format presents
550ce685455SJoel E. Denny                //    input lines in order, there's no clear way to offer the
551ce685455SJoel E. Denny                //    same benefit across input lines.  For consistency, it might
552ce685455SJoel E. Denny                //    then seem worthwhile to have annotations on a single line
553ce685455SJoel E. Denny                //    also sorted in input order (that is, by input column).
554ce685455SJoel E. Denny                //    However, in practice, this appears to be more confusing
555ce685455SJoel E. Denny                //    than helpful.  Perhaps it's intuitive to expect annotations
556ce685455SJoel E. Denny                //    to be listed in the temporal order in which they were
557ce685455SJoel E. Denny                //    produced except in cases the presentation format obviously
558ce685455SJoel E. Denny                //    and inherently cannot support it (that is, across input
559ce685455SJoel E. Denny                //    lines).
560ce685455SJoel E. Denny                //
561ce685455SJoel E. Denny                // B. When diagnostics' annotations are split among multiple
562ce685455SJoel E. Denny                //    input lines, the user must track them from one input line
563ce685455SJoel E. Denny                //    to the next.  One property of the sort chosen here is that
564ce685455SJoel E. Denny                //    it facilitates the user in this regard by ensuring the
565ce685455SJoel E. Denny                //    following: when comparing any two input lines, a
566ce685455SJoel E. Denny                //    diagnostic's annotations are sorted in the same position
567ce685455SJoel E. Denny                //    relative to all other diagnostics' annotations.
568ce685455SJoel E. Denny                return A.DiagIndex < B.DiagIndex;
5693c5d267eSJoel E. Denny              });
5703c5d267eSJoel E. Denny 
5713c5d267eSJoel E. Denny   // Compute the width of the label column.
5723c5d267eSJoel E. Denny   const unsigned char *InputFilePtr = InputFileText.bytes_begin(),
5733c5d267eSJoel E. Denny                       *InputFileEnd = InputFileText.bytes_end();
5743c5d267eSJoel E. Denny   unsigned LineCount = InputFileText.count('\n');
5753c5d267eSJoel E. Denny   if (InputFileEnd[-1] != '\n')
5763c5d267eSJoel E. Denny     ++LineCount;
577010982f7SRainer Orth   unsigned LineNoWidth = std::log10(LineCount) + 1;
5783c5d267eSJoel E. Denny   // +3 below adds spaces (1) to the left of the (right-aligned) line numbers
5793c5d267eSJoel E. Denny   // on input lines and (2) to the right of the (left-aligned) labels on
5803c5d267eSJoel E. Denny   // annotation lines so that input lines and annotation lines are more
5813c5d267eSJoel E. Denny   // visually distinct.  For example, the spaces on the annotation lines ensure
5823c5d267eSJoel E. Denny   // that input line numbers and check directive line numbers never align
5833c5d267eSJoel E. Denny   // horizontally.  Those line numbers might not even be for the same file.
5843c5d267eSJoel E. Denny   // One space would be enough to achieve that, but more makes it even easier
5853c5d267eSJoel E. Denny   // to see.
5863c5d267eSJoel E. Denny   LabelWidth = std::max(LabelWidth, LineNoWidth) + 3;
5873c5d267eSJoel E. Denny 
5883c5d267eSJoel E. Denny   // Print annotated input lines.
589bce8fcedSJoel E. Denny   unsigned PrevLineInFilter = 0; // 0 means none so far
590bce8fcedSJoel E. Denny   unsigned NextLineInFilter = 0; // 0 means uncomputed, UINT_MAX means none
59177b6ddf1SJoel E. Denny   std::string ElidedLines;
59277b6ddf1SJoel E. Denny   raw_string_ostream ElidedLinesOS(ElidedLines);
59377b6ddf1SJoel E. Denny   ColorMode TheColorMode =
59477b6ddf1SJoel E. Denny       WithColor(OS).colorsEnabled() ? ColorMode::Enable : ColorMode::Disable;
59577b6ddf1SJoel E. Denny   if (TheColorMode == ColorMode::Enable)
59677b6ddf1SJoel E. Denny     ElidedLinesOS.enable_colors(true);
5973c5d267eSJoel E. Denny   auto AnnotationItr = Annotations.begin(), AnnotationEnd = Annotations.end();
5983c5d267eSJoel E. Denny   for (unsigned Line = 1;
5993c5d267eSJoel E. Denny        InputFilePtr != InputFileEnd || AnnotationItr != AnnotationEnd;
6003c5d267eSJoel E. Denny        ++Line) {
6013c5d267eSJoel E. Denny     const unsigned char *InputFileLine = InputFilePtr;
6023c5d267eSJoel E. Denny 
603bce8fcedSJoel E. Denny     // Compute the previous and next line included by the filter.
604bce8fcedSJoel E. Denny     if (NextLineInFilter < Line)
6059fd4b5faSJoel E. Denny       NextLineInFilter = FindInputLineInFilter(DumpInputFilter, Line,
606bce8fcedSJoel E. Denny                                                AnnotationItr, AnnotationEnd);
607bce8fcedSJoel E. Denny     assert(NextLineInFilter && "expected NextLineInFilter to be computed");
608bce8fcedSJoel E. Denny     if (NextLineInFilter == Line)
609bce8fcedSJoel E. Denny       PrevLineInFilter = Line;
610bce8fcedSJoel E. Denny 
611bce8fcedSJoel E. Denny     // Elide this input line and its annotations if it's not within the
612bce8fcedSJoel E. Denny     // context specified by -dump-input-context of an input line included by
6139fd4b5faSJoel E. Denny     // -dump-input-filter.  However, in case the resulting ellipsis would occupy
61477b6ddf1SJoel E. Denny     // more lines than the input lines and annotations it elides, buffer the
61577b6ddf1SJoel E. Denny     // elided lines and annotations so we can print them instead.
61677b6ddf1SJoel E. Denny     raw_ostream *LineOS = &OS;
617bce8fcedSJoel E. Denny     if ((!PrevLineInFilter || PrevLineInFilter + DumpInputContext < Line) &&
618bce8fcedSJoel E. Denny         (NextLineInFilter == UINT_MAX ||
61977b6ddf1SJoel E. Denny          Line + DumpInputContext < NextLineInFilter))
62077b6ddf1SJoel E. Denny       LineOS = &ElidedLinesOS;
62177b6ddf1SJoel E. Denny     else {
62277b6ddf1SJoel E. Denny       LineOS = &OS;
62377b6ddf1SJoel E. Denny       DumpEllipsisOrElidedLines(OS, ElidedLinesOS.str(), LabelWidth);
624bce8fcedSJoel E. Denny     }
625bce8fcedSJoel E. Denny 
6263c5d267eSJoel E. Denny     // Print right-aligned line number.
62777b6ddf1SJoel E. Denny     WithColor(*LineOS, raw_ostream::BLACK, /*Bold=*/true, /*BF=*/false,
62877b6ddf1SJoel E. Denny               TheColorMode)
6293c5d267eSJoel E. Denny         << format_decimal(Line, LabelWidth) << ": ";
6303c5d267eSJoel E. Denny 
631e2afb614SJoel E. Denny     // For the case where -v and colors are enabled, find the annotations for
632e2afb614SJoel E. Denny     // good matches for expected patterns in order to highlight everything
633e2afb614SJoel E. Denny     // else in the line.  There are no such annotations if -v is disabled.
634e2afb614SJoel E. Denny     std::vector<InputAnnotation> FoundAndExpectedMatches;
63577b6ddf1SJoel E. Denny     if (Req.Verbose && TheColorMode == ColorMode::Enable) {
6367df86967SJoel E. Denny       for (auto I = AnnotationItr; I != AnnotationEnd && I->InputLine == Line;
6377df86967SJoel E. Denny            ++I) {
638e2afb614SJoel E. Denny         if (I->FoundAndExpectedMatch)
639e2afb614SJoel E. Denny           FoundAndExpectedMatches.push_back(*I);
6407df86967SJoel E. Denny       }
6417df86967SJoel E. Denny     }
6427df86967SJoel E. Denny 
6437df86967SJoel E. Denny     // Print numbered line with highlighting where there are no matches for
6447df86967SJoel E. Denny     // expected patterns.
6453c5d267eSJoel E. Denny     bool Newline = false;
6467df86967SJoel E. Denny     {
64777b6ddf1SJoel E. Denny       WithColor COS(*LineOS, raw_ostream::SAVEDCOLOR, /*Bold=*/false,
64877b6ddf1SJoel E. Denny                     /*BG=*/false, TheColorMode);
6497df86967SJoel E. Denny       bool InMatch = false;
6507df86967SJoel E. Denny       if (Req.Verbose)
6517df86967SJoel E. Denny         COS.changeColor(raw_ostream::CYAN, true, true);
6527df86967SJoel E. Denny       for (unsigned Col = 1; InputFilePtr != InputFileEnd && !Newline; ++Col) {
6537df86967SJoel E. Denny         bool WasInMatch = InMatch;
6547df86967SJoel E. Denny         InMatch = false;
655e2afb614SJoel E. Denny         for (auto M : FoundAndExpectedMatches) {
6567df86967SJoel E. Denny           if (M.InputStartCol <= Col && Col < M.InputEndCol) {
6577df86967SJoel E. Denny             InMatch = true;
6587df86967SJoel E. Denny             break;
6597df86967SJoel E. Denny           }
6607df86967SJoel E. Denny         }
6617df86967SJoel E. Denny         if (!WasInMatch && InMatch)
6627df86967SJoel E. Denny           COS.resetColor();
6637df86967SJoel E. Denny         else if (WasInMatch && !InMatch)
6647df86967SJoel E. Denny           COS.changeColor(raw_ostream::CYAN, true, true);
6653c5d267eSJoel E. Denny         if (*InputFilePtr == '\n')
6663c5d267eSJoel E. Denny           Newline = true;
6673c5d267eSJoel E. Denny         else
6687df86967SJoel E. Denny           COS << *InputFilePtr;
6693c5d267eSJoel E. Denny         ++InputFilePtr;
6703c5d267eSJoel E. Denny       }
6717df86967SJoel E. Denny     }
67277b6ddf1SJoel E. Denny     *LineOS << '\n';
6733c5d267eSJoel E. Denny     unsigned InputLineWidth = InputFilePtr - InputFileLine - Newline;
6743c5d267eSJoel E. Denny 
6753c5d267eSJoel E. Denny     // Print any annotations.
6763c5d267eSJoel E. Denny     while (AnnotationItr != AnnotationEnd &&
6773c5d267eSJoel E. Denny            AnnotationItr->InputLine == Line) {
67877b6ddf1SJoel E. Denny       WithColor COS(*LineOS, AnnotationItr->Marker.Color, /*Bold=*/true,
67977b6ddf1SJoel E. Denny                     /*BG=*/false, TheColorMode);
6803c5d267eSJoel E. Denny       // The two spaces below are where the ": " appears on input lines.
6813c5d267eSJoel E. Denny       COS << left_justify(AnnotationItr->Label, LabelWidth) << "  ";
6823c5d267eSJoel E. Denny       unsigned Col;
6833c5d267eSJoel E. Denny       for (Col = 1; Col < AnnotationItr->InputStartCol; ++Col)
6843c5d267eSJoel E. Denny         COS << ' ';
6853c5d267eSJoel E. Denny       COS << AnnotationItr->Marker.Lead;
6863c5d267eSJoel E. Denny       // If InputEndCol=UINT_MAX, stop at InputLineWidth.
6873c5d267eSJoel E. Denny       for (++Col; Col < AnnotationItr->InputEndCol && Col <= InputLineWidth;
6883c5d267eSJoel E. Denny            ++Col)
6893c5d267eSJoel E. Denny         COS << '~';
6903c5d267eSJoel E. Denny       const std::string &Note = AnnotationItr->Marker.Note;
6913c5d267eSJoel E. Denny       if (!Note.empty()) {
6923c5d267eSJoel E. Denny         // Put the note at the end of the input line.  If we were to instead
6933c5d267eSJoel E. Denny         // put the note right after the marker, subsequent annotations for the
6943c5d267eSJoel E. Denny         // same input line might appear to mark this note instead of the input
6953c5d267eSJoel E. Denny         // line.
6963c5d267eSJoel E. Denny         for (; Col <= InputLineWidth; ++Col)
6973c5d267eSJoel E. Denny           COS << ' ';
6983c5d267eSJoel E. Denny         COS << ' ' << Note;
6993c5d267eSJoel E. Denny       }
7003c5d267eSJoel E. Denny       COS << '\n';
7013c5d267eSJoel E. Denny       ++AnnotationItr;
7023c5d267eSJoel E. Denny     }
7033c5d267eSJoel E. Denny   }
70477b6ddf1SJoel E. Denny   DumpEllipsisOrElidedLines(OS, ElidedLinesOS.str(), LabelWidth);
7053c5d267eSJoel E. Denny 
7063c5d267eSJoel E. Denny   OS << ">>>>>>\n";
7073c5d267eSJoel E. Denny }
7083c5d267eSJoel E. Denny 
709ee3c74fbSChris Lattner int main(int argc, char **argv) {
7103e66509fSJoel E. Denny   // Enable use of ANSI color codes because FileCheck is using them to
7113e66509fSJoel E. Denny   // highlight text.
7123e66509fSJoel E. Denny   llvm::sys::Process::UseANSIEscapeCodes(true);
7133e66509fSJoel E. Denny 
714197194b6SRui Ueyama   InitLLVM X(argc, argv);
71524994d77SJoel E. Denny   cl::ParseCommandLineOptions(argc, argv, /*Overview*/ "", /*Errs*/ nullptr,
71624994d77SJoel E. Denny                               "FILECHECK_OPTS");
717bce8fcedSJoel E. Denny 
718bce8fcedSJoel E. Denny   // Select -dump-input* values.  The -help documentation specifies the default
719bce8fcedSJoel E. Denny   // value and which value to choose if an option is specified multiple times.
720bce8fcedSJoel E. Denny   // In the latter case, the general rule of thumb is to choose the value that
721bce8fcedSJoel E. Denny   // provides the most information.
722fdde18a7SJoel E. Denny   DumpInputValue DumpInput =
723fdde18a7SJoel E. Denny       DumpInputs.empty()
7243b83501cSJoel E. Denny           ? DumpInputFail
725fdde18a7SJoel E. Denny           : *std::max_element(DumpInputs.begin(), DumpInputs.end());
7269fd4b5faSJoel E. Denny   DumpInputFilterValue DumpInputFilter;
7279fd4b5faSJoel E. Denny   if (DumpInputFilters.empty())
7289fd4b5faSJoel E. Denny     DumpInputFilter = DumpInput == DumpInputAlways ? DumpInputFilterAll
7299fd4b5faSJoel E. Denny                                                    : DumpInputFilterError;
7309fd4b5faSJoel E. Denny   else
7319fd4b5faSJoel E. Denny     DumpInputFilter =
7329fd4b5faSJoel E. Denny         *std::max_element(DumpInputFilters.begin(), DumpInputFilters.end());
733bce8fcedSJoel E. Denny   unsigned DumpInputContext = DumpInputContexts.empty()
734bce8fcedSJoel E. Denny                                   ? 5
735bce8fcedSJoel E. Denny                                   : *std::max_element(DumpInputContexts.begin(),
736bce8fcedSJoel E. Denny                                                       DumpInputContexts.end());
737bce8fcedSJoel E. Denny 
7383c5d267eSJoel E. Denny   if (DumpInput == DumpInputHelp) {
7393c5d267eSJoel E. Denny     DumpInputAnnotationHelp(outs());
7403c5d267eSJoel E. Denny     return 0;
7413c5d267eSJoel E. Denny   }
7423c5d267eSJoel E. Denny   if (CheckFilename.empty()) {
7433c5d267eSJoel E. Denny     errs() << "<check-file> not specified\n";
7443c5d267eSJoel E. Denny     return 2;
7453c5d267eSJoel E. Denny   }
746ee3c74fbSChris Lattner 
747ffa9d2e4SAditya Nandakumar   FileCheckRequest Req;
7487728cc00SKazu Hirata   append_range(Req.CheckPrefixes, CheckPrefixes);
749ffa9d2e4SAditya Nandakumar 
7507728cc00SKazu Hirata   append_range(Req.CommentPrefixes, CommentPrefixes);
751a1fd1882SJoel E. Denny 
7527728cc00SKazu Hirata   append_range(Req.ImplicitCheckNot, ImplicitCheckNot);
753ffa9d2e4SAditya Nandakumar 
754a5e233bfSThomas Preud'homme   bool GlobalDefineError = false;
75576e0ab23SGeorgii Rymar   for (StringRef G : GlobalDefines) {
756a5e233bfSThomas Preud'homme     size_t EqIdx = G.find('=');
757a5e233bfSThomas Preud'homme     if (EqIdx == std::string::npos) {
758a5e233bfSThomas Preud'homme       errs() << "Missing equal sign in command-line definition '-D" << G
759a5e233bfSThomas Preud'homme              << "'\n";
760a5e233bfSThomas Preud'homme       GlobalDefineError = true;
761a5e233bfSThomas Preud'homme       continue;
762a5e233bfSThomas Preud'homme     }
763a5e233bfSThomas Preud'homme     if (EqIdx == 0) {
7641a944d27SThomas Preud'homme       errs() << "Missing variable name in command-line definition '-D" << G
7651a944d27SThomas Preud'homme              << "'\n";
766a5e233bfSThomas Preud'homme       GlobalDefineError = true;
767a5e233bfSThomas Preud'homme       continue;
768a5e233bfSThomas Preud'homme     }
769ffa9d2e4SAditya Nandakumar     Req.GlobalDefines.push_back(G);
770a5e233bfSThomas Preud'homme   }
771a5e233bfSThomas Preud'homme   if (GlobalDefineError)
772a5e233bfSThomas Preud'homme     return 2;
773ffa9d2e4SAditya Nandakumar 
774ffa9d2e4SAditya Nandakumar   Req.AllowEmptyInput = AllowEmptyInput;
775871d658cSMircea Trofin   Req.AllowUnusedPrefixes = AllowUnusedPrefixes;
776ffa9d2e4SAditya Nandakumar   Req.EnableVarScope = EnableVarScope;
777ffa9d2e4SAditya Nandakumar   Req.AllowDeprecatedDagOverlap = AllowDeprecatedDagOverlap;
778ffa9d2e4SAditya Nandakumar   Req.Verbose = Verbose;
779ffa9d2e4SAditya Nandakumar   Req.VerboseVerbose = VerboseVerbose;
780ffa9d2e4SAditya Nandakumar   Req.NoCanonicalizeWhiteSpace = NoCanonicalizeWhiteSpace;
781ffa9d2e4SAditya Nandakumar   Req.MatchFullLines = MatchFullLines;
7825b5b2fd2SKai Nacke   Req.IgnoreCase = IgnoreCase;
783ffa9d2e4SAditya Nandakumar 
784ffa9d2e4SAditya Nandakumar   if (VerboseVerbose)
785ffa9d2e4SAditya Nandakumar     Req.Verbose = true;
786ffa9d2e4SAditya Nandakumar 
787ffa9d2e4SAditya Nandakumar   FileCheck FC(Req);
7882aa0217aSJoel E. Denny   if (!FC.ValidateCheckPrefixes())
789c2735158SRui Ueyama     return 2;
790c2735158SRui Ueyama 
791ffa9d2e4SAditya Nandakumar   Regex PrefixRE = FC.buildCheckPrefixRegex();
792726774cbSChandler Carruth   std::string REError;
793726774cbSChandler Carruth   if (!PrefixRE.isValid(REError)) {
794726774cbSChandler Carruth     errs() << "Unable to combine check-prefix strings into a prefix regular "
795726774cbSChandler Carruth               "expression! This is likely a bug in FileCheck's verification of "
796726774cbSChandler Carruth               "the check-prefix strings. Regular expression parsing failed "
797726774cbSChandler Carruth               "with the following error: "
798726774cbSChandler Carruth            << REError << "\n";
799726774cbSChandler Carruth     return 2;
800726774cbSChandler Carruth   }
80113df4626SMatt Arsenault 
802ee3c74fbSChris Lattner   SourceMgr SM;
803ee3c74fbSChris Lattner 
804ee3c74fbSChris Lattner   // Read the expected strings from the check file.
80520247900SChandler Carruth   ErrorOr<std::unique_ptr<MemoryBuffer>> CheckFileOrErr =
80620247900SChandler Carruth       MemoryBuffer::getFileOrSTDIN(CheckFilename);
80720247900SChandler Carruth   if (std::error_code EC = CheckFileOrErr.getError()) {
80820247900SChandler Carruth     errs() << "Could not open check file '" << CheckFilename
80920247900SChandler Carruth            << "': " << EC.message() << '\n';
81020247900SChandler Carruth     return 2;
81120247900SChandler Carruth   }
81220247900SChandler Carruth   MemoryBuffer &CheckFile = *CheckFileOrErr.get();
81320247900SChandler Carruth 
81420247900SChandler Carruth   SmallString<4096> CheckFileBuffer;
815ffa9d2e4SAditya Nandakumar   StringRef CheckFileText = FC.CanonicalizeFile(CheckFile, CheckFileBuffer);
81620247900SChandler Carruth 
817b5a24610SJoel E. Denny   unsigned CheckFileBufferID =
81820247900SChandler Carruth       SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
81920247900SChandler Carruth                                 CheckFileText, CheckFile.getBufferIdentifier()),
82020247900SChandler Carruth                             SMLoc());
82120247900SChandler Carruth 
822b5a24610SJoel E. Denny   std::pair<unsigned, unsigned> ImpPatBufferIDRange;
823b5a24610SJoel E. Denny   if (FC.readCheckFile(SM, CheckFileText, PrefixRE, &ImpPatBufferIDRange))
824ee3c74fbSChris Lattner     return 2;
825ee3c74fbSChris Lattner 
826ee3c74fbSChris Lattner   // Open the file to check and add it to SourceMgr.
82720247900SChandler Carruth   ErrorOr<std::unique_ptr<MemoryBuffer>> InputFileOrErr =
828adf21f2aSRafael Espindola       MemoryBuffer::getFileOrSTDIN(InputFilename);
8296e01cd67SDavid Bozier   if (InputFilename == "-")
8306e01cd67SDavid Bozier     InputFilename = "<stdin>"; // Overwrite for improved diagnostic messages
83120247900SChandler Carruth   if (std::error_code EC = InputFileOrErr.getError()) {
832adf21f2aSRafael Espindola     errs() << "Could not open input file '" << InputFilename
833adf21f2aSRafael Espindola            << "': " << EC.message() << '\n';
8348e1c6477SEli Bendersky     return 2;
835ee3c74fbSChris Lattner   }
83620247900SChandler Carruth   MemoryBuffer &InputFile = *InputFileOrErr.get();
8372c3e5cdfSChris Lattner 
83820247900SChandler Carruth   if (InputFile.getBufferSize() == 0 && !AllowEmptyInput) {
839b692bed7SChris Lattner     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
8402bd4f8b6SXinliang David Li     DumpCommandLine(argc, argv);
8418e1c6477SEli Bendersky     return 2;
842b692bed7SChris Lattner   }
843b692bed7SChris Lattner 
84420247900SChandler Carruth   SmallString<4096> InputFileBuffer;
845ffa9d2e4SAditya Nandakumar   StringRef InputFileText = FC.CanonicalizeFile(InputFile, InputFileBuffer);
8462c3e5cdfSChris Lattner 
847e8f2fb20SChandler Carruth   SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
848e8f2fb20SChandler Carruth                             InputFileText, InputFile.getBufferIdentifier()),
849e8f2fb20SChandler Carruth                         SMLoc());
850ee3c74fbSChris Lattner 
8513c5d267eSJoel E. Denny   std::vector<FileCheckDiag> Diags;
85202ada9bdSThomas Preud'homme   int ExitCode = FC.checkInput(SM, InputFileText,
8533c5d267eSJoel E. Denny                                DumpInput == DumpInputNever ? nullptr : &Diags)
8543c5d267eSJoel E. Denny                      ? EXIT_SUCCESS
8553c5d267eSJoel E. Denny                      : 1;
8563c5d267eSJoel E. Denny   if (DumpInput == DumpInputAlways ||
8573c5d267eSJoel E. Denny       (ExitCode == 1 && DumpInput == DumpInputFail)) {
8583c5d267eSJoel E. Denny     errs() << "\n"
859839f8e4fSJoel E. Denny            << "Input file: " << InputFilename << "\n"
8603c5d267eSJoel E. Denny            << "Check file: " << CheckFilename << "\n"
8613c5d267eSJoel E. Denny            << "\n"
862839f8e4fSJoel E. Denny            << "-dump-input=help explains the following input dump.\n"
8633c5d267eSJoel E. Denny            << "\n";
8643c5d267eSJoel E. Denny     std::vector<InputAnnotation> Annotations;
8653c5d267eSJoel E. Denny     unsigned LabelWidth;
866b5a24610SJoel E. Denny     BuildInputAnnotations(SM, CheckFileBufferID, ImpPatBufferIDRange, Diags,
867b5a24610SJoel E. Denny                           Annotations, LabelWidth);
8689fd4b5faSJoel E. Denny     DumpAnnotatedInput(errs(), Req, DumpInputFilter, DumpInputContext,
869bce8fcedSJoel E. Denny                        InputFileText, Annotations, LabelWidth);
8703c5d267eSJoel E. Denny   }
871346dfbe2SGeorge Karpenkov 
872346dfbe2SGeorge Karpenkov   return ExitCode;
873ee3c74fbSChris Lattner }
874