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