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 
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 #include <cmath>
25 using namespace llvm;
26 
27 static cl::extrahelp FileCheckOptsEnv(
28     "\nOptions are parsed from the environment variable FILECHECK_OPTS and\n"
29     "from the command line.\n");
30 
31 static cl::opt<std::string>
32     CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Optional);
33 
34 static cl::opt<std::string>
35     InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
36                   cl::init("-"), cl::value_desc("filename"));
37 
38 static cl::list<std::string> CheckPrefixes(
39     "check-prefix",
40     cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
41 static cl::alias CheckPrefixesAlias(
42     "check-prefixes", cl::aliasopt(CheckPrefixes), cl::CommaSeparated,
43     cl::NotHidden,
44     cl::desc(
45         "Alias for -check-prefix permitting multiple comma separated values"));
46 
47 static cl::list<std::string> CommentPrefixes(
48     "comment-prefixes", cl::CommaSeparated, cl::Hidden,
49     cl::desc("Comma-separated list of comment prefixes to use from check file\n"
50              "(defaults to 'COM,RUN'). Please avoid using this feature in\n"
51              "LLVM's LIT-based test suites, which should be easier to\n"
52              "maintain if they all follow a consistent comment style. This\n"
53              "feature is meant for non-LIT test suites using FileCheck."));
54 
55 static cl::opt<bool> NoCanonicalizeWhiteSpace(
56     "strict-whitespace",
57     cl::desc("Do not treat all horizontal whitespace as equivalent"));
58 
59 static cl::opt<bool> IgnoreCase(
60     "ignore-case",
61     cl::desc("Use case-insensitive matching"));
62 
63 static cl::list<std::string> ImplicitCheckNot(
64     "implicit-check-not",
65     cl::desc("Add an implicit negative check with this pattern to every\n"
66              "positive check. This can be used to ensure that no instances of\n"
67              "this pattern occur which are not matched by a positive pattern"),
68     cl::value_desc("pattern"));
69 
70 static cl::list<std::string>
71     GlobalDefines("D", cl::AlwaysPrefix,
72                   cl::desc("Define a variable to be used in capture patterns."),
73                   cl::value_desc("VAR=VALUE"));
74 
75 static cl::opt<bool> AllowEmptyInput(
76     "allow-empty", cl::init(false),
77     cl::desc("Allow the input file to be empty. This is useful when making\n"
78              "checks that some error message does not occur, for example."));
79 
80 static cl::opt<bool> MatchFullLines(
81     "match-full-lines", cl::init(false),
82     cl::desc("Require all positive matches to cover an entire input line.\n"
83              "Allows leading and trailing whitespace if --strict-whitespace\n"
84              "is not also passed."));
85 
86 static cl::opt<bool> EnableVarScope(
87     "enable-var-scope", cl::init(false),
88     cl::desc("Enables scope for regex variables. Variables with names that\n"
89              "do not start with '$' will be reset at the beginning of\n"
90              "each CHECK-LABEL block."));
91 
92 static cl::opt<bool> AllowDeprecatedDagOverlap(
93     "allow-deprecated-dag-overlap", cl::init(false),
94     cl::desc("Enable overlapping among matches in a group of consecutive\n"
95              "CHECK-DAG directives.  This option is deprecated and is only\n"
96              "provided for convenience as old tests are migrated to the new\n"
97              "non-overlapping CHECK-DAG implementation.\n"));
98 
99 static cl::opt<bool> Verbose(
100     "v", cl::init(false), cl::ZeroOrMore,
101     cl::desc("Print directive pattern matches, or add them to the input dump\n"
102              "if enabled.\n"));
103 
104 static cl::opt<bool> VerboseVerbose(
105     "vv", cl::init(false), cl::ZeroOrMore,
106     cl::desc("Print information helpful in diagnosing internal FileCheck\n"
107              "issues, or add it to the input dump if enabled.  Implies\n"
108              "-v.\n"));
109 
110 // The order of DumpInputValue members affects their precedence, as documented
111 // for -dump-input below.
112 enum DumpInputValue {
113   DumpInputNever,
114   DumpInputFail,
115   DumpInputAlways,
116   DumpInputHelp
117 };
118 
119 static cl::list<DumpInputValue> DumpInputs(
120     "dump-input",
121     cl::desc("Dump input to stderr, adding annotations representing\n"
122              "currently enabled diagnostics.  When there are multiple\n"
123              "occurrences of this option, the <value> that appears earliest\n"
124              "in the list below has precedence.  The default is 'fail'.\n"),
125     cl::value_desc("mode"),
126     cl::values(clEnumValN(DumpInputHelp, "help", "Explain input dump and quit"),
127                clEnumValN(DumpInputAlways, "always", "Always dump input"),
128                clEnumValN(DumpInputFail, "fail", "Dump input on failure"),
129                clEnumValN(DumpInputNever, "never", "Never dump input")));
130 
131 static cl::list<unsigned> DumpInputContexts(
132     "dump-input-context", cl::value_desc("N"),
133     cl::desc("In the dump requested by -dump-input=fail, print <N> input\n"
134              "lines before and <N> input lines after the starting line of\n"
135              "any error diagnostic.  When there are multiple occurrences of\n"
136              "this option, the largest specified <N> has precedence.  The\n"
137              "default is 5.\n"));
138 
139 typedef cl::list<std::string>::const_iterator prefix_iterator;
140 
141 
142 
143 
144 
145 
146 
147 static void DumpCommandLine(int argc, char **argv) {
148   errs() << "FileCheck command line: ";
149   for (int I = 0; I < argc; I++)
150     errs() << " " << argv[I];
151   errs() << "\n";
152 }
153 
154 struct MarkerStyle {
155   /// The starting char (before tildes) for marking the line.
156   char Lead;
157   /// What color to use for this annotation.
158   raw_ostream::Colors Color;
159   /// A note to follow the marker, or empty string if none.
160   std::string Note;
161   /// Does this marker indicate inclusion by the input filter implied by
162   /// -dump-input=fail?
163   bool FiltersAsError;
164   MarkerStyle() {}
165   MarkerStyle(char Lead, raw_ostream::Colors Color,
166               const std::string &Note = "", bool FiltersAsError = false)
167       : Lead(Lead), Color(Color), Note(Note), FiltersAsError(FiltersAsError) {
168     assert((!FiltersAsError || !Note.empty()) &&
169            "expected error diagnostic to have note");
170   }
171 };
172 
173 static MarkerStyle GetMarker(FileCheckDiag::MatchType MatchTy) {
174   switch (MatchTy) {
175   case FileCheckDiag::MatchFoundAndExpected:
176     return MarkerStyle('^', raw_ostream::GREEN);
177   case FileCheckDiag::MatchFoundButExcluded:
178     return MarkerStyle('!', raw_ostream::RED, "error: no match expected",
179                        /*FiltersAsError=*/true);
180   case FileCheckDiag::MatchFoundButWrongLine:
181     return MarkerStyle('!', raw_ostream::RED, "error: match on wrong line",
182                        /*FiltersAsError=*/true);
183   case FileCheckDiag::MatchFoundButDiscarded:
184     return MarkerStyle('!', raw_ostream::CYAN,
185                        "discard: overlaps earlier match");
186   case FileCheckDiag::MatchNoneAndExcluded:
187     return MarkerStyle('X', raw_ostream::GREEN);
188   case FileCheckDiag::MatchNoneButExpected:
189     return MarkerStyle('X', raw_ostream::RED, "error: no match found",
190                        /*FiltersAsError=*/true);
191   case FileCheckDiag::MatchFuzzy:
192     return MarkerStyle('?', raw_ostream::MAGENTA, "possible intended match",
193                        /*FiltersAsError=*/true);
194   }
195   llvm_unreachable_internal("unexpected match type");
196 }
197 
198 static void DumpInputAnnotationHelp(raw_ostream &OS) {
199   OS << "The following description was requested by -dump-input=help to\n"
200      << "explain the input dump printed by FileCheck.\n"
201      << "\n"
202      << "Related command-line options:\n"
203      << "  - -dump-input=<value> enables or disables the input dump\n"
204      << "  - -dump-input-context=<N> adjusts the context of errors\n"
205      << "  - -v and -vv add more annotations\n"
206      << "  - -color forces colors to be enabled both in the dump and below\n"
207      << "  - -help documents the above options in more detail\n"
208      << "\n"
209      << "Input dump annotation format:\n";
210 
211   // Labels for input lines.
212   OS << "  - ";
213   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "L:";
214   OS << "     labels line number L of the input file\n";
215 
216   // Labels for annotation lines.
217   OS << "  - ";
218   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L";
219   OS << "    labels the only match result for either (1) a pattern of type T"
220      << " from\n"
221      << "           line L of the check file if L is an integer or (2) the"
222      << " I-th implicit\n"
223      << "           pattern if L is \"imp\" followed by an integer "
224      << "I (index origin one)\n";
225   OS << "  - ";
226   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L'N";
227   OS << "  labels the Nth match result for such a pattern\n";
228 
229   // Markers on annotation lines.
230   OS << "  - ";
231   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "^~~";
232   OS << "    marks good match (reported if -v)\n"
233      << "  - ";
234   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "!~~";
235   OS << "    marks bad match, such as:\n"
236      << "           - CHECK-NEXT on same line as previous match (error)\n"
237      << "           - CHECK-NOT found (error)\n"
238      << "           - CHECK-DAG overlapping match (discarded, reported if "
239      << "-vv)\n"
240      << "  - ";
241   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "X~~";
242   OS << "    marks search range when no match is found, such as:\n"
243      << "           - CHECK-NEXT not found (error)\n"
244      << "           - CHECK-NOT not found (success, reported if -vv)\n"
245      << "           - CHECK-DAG not found after discarded matches (error)\n"
246      << "  - ";
247   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "?";
248   OS << "      marks fuzzy match when no match is found\n";
249 
250   // Elided lines.
251   OS << "  - ";
252   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "...";
253   OS << "    indicates elided input lines and annotations, as specified by\n"
254      << "           -dump-input=fail and -dump-input-context\n";
255 
256   // Colors.
257   OS << "  - colors ";
258   WithColor(OS, raw_ostream::GREEN, true) << "success";
259   OS << ", ";
260   WithColor(OS, raw_ostream::RED, true) << "error";
261   OS << ", ";
262   WithColor(OS, raw_ostream::MAGENTA, true) << "fuzzy match";
263   OS << ", ";
264   WithColor(OS, raw_ostream::CYAN, true, false) << "discarded match";
265   OS << ", ";
266   WithColor(OS, raw_ostream::CYAN, true, true) << "unmatched input";
267   OS << "\n";
268 }
269 
270 /// An annotation for a single input line.
271 struct InputAnnotation {
272   /// The index of the match result across all checks
273   unsigned DiagIndex;
274   /// The label for this annotation.
275   std::string Label;
276   /// Is this the initial fragment of a diagnostic that has been broken across
277   /// multiple lines?
278   bool IsFirstLine;
279   /// What input line (one-origin indexing) this annotation marks.  This might
280   /// be different from the starting line of the original diagnostic if
281   /// !IsFirstLine.
282   unsigned InputLine;
283   /// The column range (one-origin indexing, open end) in which to mark the
284   /// input line.  If InputEndCol is UINT_MAX, treat it as the last column
285   /// before the newline.
286   unsigned InputStartCol, InputEndCol;
287   /// The marker to use.
288   MarkerStyle Marker;
289   /// Whether this annotation represents a good match for an expected pattern.
290   bool FoundAndExpectedMatch;
291 };
292 
293 /// Get an abbreviation for the check type.
294 std::string GetCheckTypeAbbreviation(Check::FileCheckType Ty) {
295   switch (Ty) {
296   case Check::CheckPlain:
297     if (Ty.getCount() > 1)
298       return "count";
299     return "check";
300   case Check::CheckNext:
301     return "next";
302   case Check::CheckSame:
303     return "same";
304   case Check::CheckNot:
305     return "not";
306   case Check::CheckDAG:
307     return "dag";
308   case Check::CheckLabel:
309     return "label";
310   case Check::CheckEmpty:
311     return "empty";
312   case Check::CheckComment:
313     return "com";
314   case Check::CheckEOF:
315     return "eof";
316   case Check::CheckBadNot:
317     return "bad-not";
318   case Check::CheckBadCount:
319     return "bad-count";
320   case Check::CheckNone:
321     llvm_unreachable("invalid FileCheckType");
322   }
323   llvm_unreachable("unknown FileCheckType");
324 }
325 
326 static void
327 BuildInputAnnotations(const SourceMgr &SM, unsigned CheckFileBufferID,
328                       const std::pair<unsigned, unsigned> &ImpPatBufferIDRange,
329                       const std::vector<FileCheckDiag> &Diags,
330                       std::vector<InputAnnotation> &Annotations,
331                       unsigned &LabelWidth) {
332   // How many diagnostics have we seen so far?
333   unsigned DiagCount = 0;
334   // How many diagnostics has the current check seen so far?
335   unsigned CheckDiagCount = 0;
336   // What's the widest label?
337   LabelWidth = 0;
338   for (auto DiagItr = Diags.begin(), DiagEnd = Diags.end(); DiagItr != DiagEnd;
339        ++DiagItr) {
340     InputAnnotation A;
341     A.DiagIndex = DiagCount++;
342 
343     // Build label, which uniquely identifies this check result.
344     unsigned CheckBufferID = SM.FindBufferContainingLoc(DiagItr->CheckLoc);
345     auto CheckLineAndCol =
346         SM.getLineAndColumn(DiagItr->CheckLoc, CheckBufferID);
347     llvm::raw_string_ostream Label(A.Label);
348     Label << GetCheckTypeAbbreviation(DiagItr->CheckTy) << ":";
349     if (CheckBufferID == CheckFileBufferID)
350       Label << CheckLineAndCol.first;
351     else if (ImpPatBufferIDRange.first <= CheckBufferID &&
352              CheckBufferID < ImpPatBufferIDRange.second)
353       Label << "imp" << (CheckBufferID - ImpPatBufferIDRange.first + 1);
354     else
355       llvm_unreachable("expected diagnostic's check location to be either in "
356                        "the check file or for an implicit pattern");
357     unsigned CheckDiagIndex = UINT_MAX;
358     auto DiagNext = std::next(DiagItr);
359     if (DiagNext != DiagEnd && DiagItr->CheckTy == DiagNext->CheckTy &&
360         DiagItr->CheckLoc == DiagNext->CheckLoc)
361       CheckDiagIndex = CheckDiagCount++;
362     else if (CheckDiagCount) {
363       CheckDiagIndex = CheckDiagCount;
364       CheckDiagCount = 0;
365     }
366     if (CheckDiagIndex != UINT_MAX)
367       Label << "'" << CheckDiagIndex;
368     Label.flush();
369     LabelWidth = std::max((std::string::size_type)LabelWidth, A.Label.size());
370 
371     A.Marker = GetMarker(DiagItr->MatchTy);
372     A.FoundAndExpectedMatch =
373         DiagItr->MatchTy == FileCheckDiag::MatchFoundAndExpected;
374 
375     // Compute the mark location, and break annotation into multiple
376     // annotations if it spans multiple lines.
377     A.IsFirstLine = true;
378     A.InputLine = DiagItr->InputStartLine;
379     A.InputStartCol = DiagItr->InputStartCol;
380     if (DiagItr->InputStartLine == DiagItr->InputEndLine) {
381       // Sometimes ranges are empty in order to indicate a specific point, but
382       // that would mean nothing would be marked, so adjust the range to
383       // include the following character.
384       A.InputEndCol =
385           std::max(DiagItr->InputStartCol + 1, DiagItr->InputEndCol);
386       Annotations.push_back(A);
387     } else {
388       assert(DiagItr->InputStartLine < DiagItr->InputEndLine &&
389              "expected input range not to be inverted");
390       A.InputEndCol = UINT_MAX;
391       Annotations.push_back(A);
392       for (unsigned L = DiagItr->InputStartLine + 1, E = DiagItr->InputEndLine;
393            L <= E; ++L) {
394         // If a range ends before the first column on a line, then it has no
395         // characters on that line, so there's nothing to render.
396         if (DiagItr->InputEndCol == 1 && L == E)
397           break;
398         InputAnnotation B;
399         B.DiagIndex = A.DiagIndex;
400         B.Label = A.Label;
401         B.IsFirstLine = false;
402         B.InputLine = L;
403         B.Marker = A.Marker;
404         B.Marker.Lead = '~';
405         B.Marker.Note = "";
406         B.InputStartCol = 1;
407         if (L != E)
408           B.InputEndCol = UINT_MAX;
409         else
410           B.InputEndCol = DiagItr->InputEndCol;
411         B.FoundAndExpectedMatch = A.FoundAndExpectedMatch;
412         Annotations.push_back(B);
413       }
414     }
415   }
416 }
417 
418 static unsigned FindInputLineInFilter(
419     bool FilterOnError, unsigned CurInputLine,
420     const std::vector<InputAnnotation>::iterator &AnnotationBeg,
421     const std::vector<InputAnnotation>::iterator &AnnotationEnd) {
422   if (!FilterOnError)
423     return CurInputLine;
424   for (auto AnnotationItr = AnnotationBeg; AnnotationItr != AnnotationEnd;
425        ++AnnotationItr) {
426     if (AnnotationItr->IsFirstLine && AnnotationItr->Marker.FiltersAsError)
427       return AnnotationItr->InputLine;
428   }
429   return UINT_MAX;
430 }
431 
432 /// To OS, print a vertical ellipsis (right-justified at LabelWidth) if it would
433 /// occupy less lines than ElidedLines, but print ElidedLines otherwise.  Either
434 /// way, clear ElidedLines.  Thus, if ElidedLines is empty, do nothing.
435 static void DumpEllipsisOrElidedLines(raw_ostream &OS, std::string &ElidedLines,
436                                       unsigned LabelWidth) {
437   if (ElidedLines.empty())
438     return;
439   unsigned EllipsisLines = 3;
440   if (EllipsisLines < StringRef(ElidedLines).count('\n')) {
441     for (unsigned i = 0; i < EllipsisLines; ++i) {
442       WithColor(OS, raw_ostream::BLACK, /*Bold=*/true)
443           << right_justify(".", LabelWidth);
444       OS << '\n';
445     }
446   } else
447     OS << ElidedLines;
448   ElidedLines.clear();
449 }
450 
451 static void DumpAnnotatedInput(raw_ostream &OS, const FileCheckRequest &Req,
452                                bool DumpInputFilterOnError,
453                                unsigned DumpInputContext,
454                                StringRef InputFileText,
455                                std::vector<InputAnnotation> &Annotations,
456                                unsigned LabelWidth) {
457   OS << "Input was:\n<<<<<<\n";
458 
459   // Sort annotations.
460   std::sort(Annotations.begin(), Annotations.end(),
461             [](const InputAnnotation &A, const InputAnnotation &B) {
462               // 1. Sort annotations in the order of the input lines.
463               //
464               // This makes it easier to find relevant annotations while
465               // iterating input lines in the implementation below.  FileCheck
466               // does not always produce diagnostics in the order of input
467               // lines due to, for example, CHECK-DAG and CHECK-NOT.
468               if (A.InputLine != B.InputLine)
469                 return A.InputLine < B.InputLine;
470               // 2. Sort annotations in the temporal order FileCheck produced
471               // their associated diagnostics.
472               //
473               // This sort offers several benefits:
474               //
475               // A. On a single input line, the order of annotations reflects
476               //    the FileCheck logic for processing directives/patterns.
477               //    This can be helpful in understanding cases in which the
478               //    order of the associated directives/patterns in the check
479               //    file or on the command line either (i) does not match the
480               //    temporal order in which FileCheck looks for matches for the
481               //    directives/patterns (due to, for example, CHECK-LABEL,
482               //    CHECK-NOT, or `--implicit-check-not`) or (ii) does match
483               //    that order but does not match the order of those
484               //    diagnostics along an input line (due to, for example,
485               //    CHECK-DAG).
486               //
487               //    On the other hand, because our presentation format presents
488               //    input lines in order, there's no clear way to offer the
489               //    same benefit across input lines.  For consistency, it might
490               //    then seem worthwhile to have annotations on a single line
491               //    also sorted in input order (that is, by input column).
492               //    However, in practice, this appears to be more confusing
493               //    than helpful.  Perhaps it's intuitive to expect annotations
494               //    to be listed in the temporal order in which they were
495               //    produced except in cases the presentation format obviously
496               //    and inherently cannot support it (that is, across input
497               //    lines).
498               //
499               // B. When diagnostics' annotations are split among multiple
500               //    input lines, the user must track them from one input line
501               //    to the next.  One property of the sort chosen here is that
502               //    it facilitates the user in this regard by ensuring the
503               //    following: when comparing any two input lines, a
504               //    diagnostic's annotations are sorted in the same position
505               //    relative to all other diagnostics' annotations.
506               return A.DiagIndex < B.DiagIndex;
507             });
508 
509   // Compute the width of the label column.
510   const unsigned char *InputFilePtr = InputFileText.bytes_begin(),
511                       *InputFileEnd = InputFileText.bytes_end();
512   unsigned LineCount = InputFileText.count('\n');
513   if (InputFileEnd[-1] != '\n')
514     ++LineCount;
515   unsigned LineNoWidth = std::log10(LineCount) + 1;
516   // +3 below adds spaces (1) to the left of the (right-aligned) line numbers
517   // on input lines and (2) to the right of the (left-aligned) labels on
518   // annotation lines so that input lines and annotation lines are more
519   // visually distinct.  For example, the spaces on the annotation lines ensure
520   // that input line numbers and check directive line numbers never align
521   // horizontally.  Those line numbers might not even be for the same file.
522   // One space would be enough to achieve that, but more makes it even easier
523   // to see.
524   LabelWidth = std::max(LabelWidth, LineNoWidth) + 3;
525 
526   // Print annotated input lines.
527   unsigned PrevLineInFilter = 0; // 0 means none so far
528   unsigned NextLineInFilter = 0; // 0 means uncomputed, UINT_MAX means none
529   std::string ElidedLines;
530   raw_string_ostream ElidedLinesOS(ElidedLines);
531   ColorMode TheColorMode =
532       WithColor(OS).colorsEnabled() ? ColorMode::Enable : ColorMode::Disable;
533   if (TheColorMode == ColorMode::Enable)
534     ElidedLinesOS.enable_colors(true);
535   auto AnnotationItr = Annotations.begin(), AnnotationEnd = Annotations.end();
536   for (unsigned Line = 1;
537        InputFilePtr != InputFileEnd || AnnotationItr != AnnotationEnd;
538        ++Line) {
539     const unsigned char *InputFileLine = InputFilePtr;
540 
541     // Compute the previous and next line included by the filter.
542     if (NextLineInFilter < Line)
543       NextLineInFilter = FindInputLineInFilter(DumpInputFilterOnError, Line,
544                                                AnnotationItr, AnnotationEnd);
545     assert(NextLineInFilter && "expected NextLineInFilter to be computed");
546     if (NextLineInFilter == Line)
547       PrevLineInFilter = Line;
548 
549     // Elide this input line and its annotations if it's not within the
550     // context specified by -dump-input-context of an input line included by
551     // the dump filter.  However, in case the resulting ellipsis would occupy
552     // more lines than the input lines and annotations it elides, buffer the
553     // elided lines and annotations so we can print them instead.
554     raw_ostream *LineOS = &OS;
555     if ((!PrevLineInFilter || PrevLineInFilter + DumpInputContext < Line) &&
556         (NextLineInFilter == UINT_MAX ||
557          Line + DumpInputContext < NextLineInFilter))
558       LineOS = &ElidedLinesOS;
559     else {
560       LineOS = &OS;
561       DumpEllipsisOrElidedLines(OS, ElidedLinesOS.str(), LabelWidth);
562     }
563 
564     // Print right-aligned line number.
565     WithColor(*LineOS, raw_ostream::BLACK, /*Bold=*/true, /*BF=*/false,
566               TheColorMode)
567         << format_decimal(Line, LabelWidth) << ": ";
568 
569     // For the case where -v and colors are enabled, find the annotations for
570     // good matches for expected patterns in order to highlight everything
571     // else in the line.  There are no such annotations if -v is disabled.
572     std::vector<InputAnnotation> FoundAndExpectedMatches;
573     if (Req.Verbose && TheColorMode == ColorMode::Enable) {
574       for (auto I = AnnotationItr; I != AnnotationEnd && I->InputLine == Line;
575            ++I) {
576         if (I->FoundAndExpectedMatch)
577           FoundAndExpectedMatches.push_back(*I);
578       }
579     }
580 
581     // Print numbered line with highlighting where there are no matches for
582     // expected patterns.
583     bool Newline = false;
584     {
585       WithColor COS(*LineOS, raw_ostream::SAVEDCOLOR, /*Bold=*/false,
586                     /*BG=*/false, TheColorMode);
587       bool InMatch = false;
588       if (Req.Verbose)
589         COS.changeColor(raw_ostream::CYAN, true, true);
590       for (unsigned Col = 1; InputFilePtr != InputFileEnd && !Newline; ++Col) {
591         bool WasInMatch = InMatch;
592         InMatch = false;
593         for (auto M : FoundAndExpectedMatches) {
594           if (M.InputStartCol <= Col && Col < M.InputEndCol) {
595             InMatch = true;
596             break;
597           }
598         }
599         if (!WasInMatch && InMatch)
600           COS.resetColor();
601         else if (WasInMatch && !InMatch)
602           COS.changeColor(raw_ostream::CYAN, true, true);
603         if (*InputFilePtr == '\n')
604           Newline = true;
605         else
606           COS << *InputFilePtr;
607         ++InputFilePtr;
608       }
609     }
610     *LineOS << '\n';
611     unsigned InputLineWidth = InputFilePtr - InputFileLine - Newline;
612 
613     // Print any annotations.
614     while (AnnotationItr != AnnotationEnd &&
615            AnnotationItr->InputLine == Line) {
616       WithColor COS(*LineOS, AnnotationItr->Marker.Color, /*Bold=*/true,
617                     /*BG=*/false, TheColorMode);
618       // The two spaces below are where the ": " appears on input lines.
619       COS << left_justify(AnnotationItr->Label, LabelWidth) << "  ";
620       unsigned Col;
621       for (Col = 1; Col < AnnotationItr->InputStartCol; ++Col)
622         COS << ' ';
623       COS << AnnotationItr->Marker.Lead;
624       // If InputEndCol=UINT_MAX, stop at InputLineWidth.
625       for (++Col; Col < AnnotationItr->InputEndCol && Col <= InputLineWidth;
626            ++Col)
627         COS << '~';
628       const std::string &Note = AnnotationItr->Marker.Note;
629       if (!Note.empty()) {
630         // Put the note at the end of the input line.  If we were to instead
631         // put the note right after the marker, subsequent annotations for the
632         // same input line might appear to mark this note instead of the input
633         // line.
634         for (; Col <= InputLineWidth; ++Col)
635           COS << ' ';
636         COS << ' ' << Note;
637       }
638       COS << '\n';
639       ++AnnotationItr;
640     }
641   }
642   DumpEllipsisOrElidedLines(OS, ElidedLinesOS.str(), LabelWidth);
643 
644   OS << ">>>>>>\n";
645 }
646 
647 int main(int argc, char **argv) {
648   // Enable use of ANSI color codes because FileCheck is using them to
649   // highlight text.
650   llvm::sys::Process::UseANSIEscapeCodes(true);
651 
652   InitLLVM X(argc, argv);
653   cl::ParseCommandLineOptions(argc, argv, /*Overview*/ "", /*Errs*/ nullptr,
654                               "FILECHECK_OPTS");
655 
656   // Select -dump-input* values.  The -help documentation specifies the default
657   // value and which value to choose if an option is specified multiple times.
658   // In the latter case, the general rule of thumb is to choose the value that
659   // provides the most information.
660   DumpInputValue DumpInput =
661       DumpInputs.empty()
662           ? DumpInputFail
663           : *std::max_element(DumpInputs.begin(), DumpInputs.end());
664   bool DumpInputFilterOnError = DumpInput == DumpInputFail;
665   unsigned DumpInputContext = DumpInputContexts.empty()
666                                   ? 5
667                                   : *std::max_element(DumpInputContexts.begin(),
668                                                       DumpInputContexts.end());
669 
670   if (DumpInput == DumpInputHelp) {
671     DumpInputAnnotationHelp(outs());
672     return 0;
673   }
674   if (CheckFilename.empty()) {
675     errs() << "<check-file> not specified\n";
676     return 2;
677   }
678 
679   FileCheckRequest Req;
680   for (StringRef Prefix : CheckPrefixes)
681     Req.CheckPrefixes.push_back(Prefix);
682 
683   for (StringRef Prefix : CommentPrefixes)
684     Req.CommentPrefixes.push_back(Prefix);
685 
686   for (StringRef CheckNot : ImplicitCheckNot)
687     Req.ImplicitCheckNot.push_back(CheckNot);
688 
689   bool GlobalDefineError = false;
690   for (StringRef G : GlobalDefines) {
691     size_t EqIdx = G.find('=');
692     if (EqIdx == std::string::npos) {
693       errs() << "Missing equal sign in command-line definition '-D" << G
694              << "'\n";
695       GlobalDefineError = true;
696       continue;
697     }
698     if (EqIdx == 0) {
699       errs() << "Missing variable name in command-line definition '-D" << G
700              << "'\n";
701       GlobalDefineError = true;
702       continue;
703     }
704     Req.GlobalDefines.push_back(G);
705   }
706   if (GlobalDefineError)
707     return 2;
708 
709   Req.AllowEmptyInput = AllowEmptyInput;
710   Req.EnableVarScope = EnableVarScope;
711   Req.AllowDeprecatedDagOverlap = AllowDeprecatedDagOverlap;
712   Req.Verbose = Verbose;
713   Req.VerboseVerbose = VerboseVerbose;
714   Req.NoCanonicalizeWhiteSpace = NoCanonicalizeWhiteSpace;
715   Req.MatchFullLines = MatchFullLines;
716   Req.IgnoreCase = IgnoreCase;
717 
718   if (VerboseVerbose)
719     Req.Verbose = true;
720 
721   FileCheck FC(Req);
722   if (!FC.ValidateCheckPrefixes())
723     return 2;
724 
725   Regex PrefixRE = FC.buildCheckPrefixRegex();
726   std::string REError;
727   if (!PrefixRE.isValid(REError)) {
728     errs() << "Unable to combine check-prefix strings into a prefix regular "
729               "expression! This is likely a bug in FileCheck's verification of "
730               "the check-prefix strings. Regular expression parsing failed "
731               "with the following error: "
732            << REError << "\n";
733     return 2;
734   }
735 
736   SourceMgr SM;
737 
738   // Read the expected strings from the check file.
739   ErrorOr<std::unique_ptr<MemoryBuffer>> CheckFileOrErr =
740       MemoryBuffer::getFileOrSTDIN(CheckFilename);
741   if (std::error_code EC = CheckFileOrErr.getError()) {
742     errs() << "Could not open check file '" << CheckFilename
743            << "': " << EC.message() << '\n';
744     return 2;
745   }
746   MemoryBuffer &CheckFile = *CheckFileOrErr.get();
747 
748   SmallString<4096> CheckFileBuffer;
749   StringRef CheckFileText = FC.CanonicalizeFile(CheckFile, CheckFileBuffer);
750 
751   unsigned CheckFileBufferID =
752       SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
753                                 CheckFileText, CheckFile.getBufferIdentifier()),
754                             SMLoc());
755 
756   std::pair<unsigned, unsigned> ImpPatBufferIDRange;
757   if (FC.readCheckFile(SM, CheckFileText, PrefixRE, &ImpPatBufferIDRange))
758     return 2;
759 
760   // Open the file to check and add it to SourceMgr.
761   ErrorOr<std::unique_ptr<MemoryBuffer>> InputFileOrErr =
762       MemoryBuffer::getFileOrSTDIN(InputFilename);
763   if (InputFilename == "-")
764     InputFilename = "<stdin>"; // Overwrite for improved diagnostic messages
765   if (std::error_code EC = InputFileOrErr.getError()) {
766     errs() << "Could not open input file '" << InputFilename
767            << "': " << EC.message() << '\n';
768     return 2;
769   }
770   MemoryBuffer &InputFile = *InputFileOrErr.get();
771 
772   if (InputFile.getBufferSize() == 0 && !AllowEmptyInput) {
773     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
774     DumpCommandLine(argc, argv);
775     return 2;
776   }
777 
778   SmallString<4096> InputFileBuffer;
779   StringRef InputFileText = FC.CanonicalizeFile(InputFile, InputFileBuffer);
780 
781   SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
782                             InputFileText, InputFile.getBufferIdentifier()),
783                         SMLoc());
784 
785   std::vector<FileCheckDiag> Diags;
786   int ExitCode = FC.checkInput(SM, InputFileText,
787                                DumpInput == DumpInputNever ? nullptr : &Diags)
788                      ? EXIT_SUCCESS
789                      : 1;
790   if (DumpInput == DumpInputAlways ||
791       (ExitCode == 1 && DumpInput == DumpInputFail)) {
792     errs() << "\n"
793            << "Input file: " << InputFilename << "\n"
794            << "Check file: " << CheckFilename << "\n"
795            << "\n"
796            << "-dump-input=help explains the following input dump.\n"
797            << "\n";
798     std::vector<InputAnnotation> Annotations;
799     unsigned LabelWidth;
800     BuildInputAnnotations(SM, CheckFileBufferID, ImpPatBufferIDRange, Diags,
801                           Annotations, LabelWidth);
802     DumpAnnotatedInput(errs(), Req, DumpInputFilterOnError, DumpInputContext,
803                        InputFileText, Annotations, LabelWidth);
804   }
805 
806   return ExitCode;
807 }
808