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/FileCheck/FileCheck.h"
19#include "llvm/Support/CommandLine.h"
20#include "llvm/Support/InitLLVM.h"
21#include "llvm/Support/MemoryBuffer.h"
22#include "llvm/Support/Process.h"
23#include "llvm/Support/SourceMgr.h"
24#include "llvm/Support/WithColor.h"
25#include "llvm/Support/raw_ostream.h"
26using namespace llvm;
27
28static cl::extrahelp FileCheckOptsEnv(
29 "\nOptions are parsed from the environment variable FILECHECK_OPTS and\n"
30 "from the command line.\n");
31
32static cl::opt<std::string>
33 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Optional);
34
35static cl::opt<std::string>
36 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
37 cl::init(Val: "-"), cl::value_desc("filename"));
38
39static cl::list<std::string>
40 CheckPrefixes("check-prefixes", cl::CommaSeparated,
41 cl::desc("Comma separated list of prefixes to use from check "
42 "file\n(defaults to 'CHECK')"));
43static cl::alias CheckPrefixesAlias("check-prefix", cl::aliasopt(CheckPrefixes),
44 cl::CommaSeparated, cl::NotHidden,
45 cl::desc("Alias for -check-prefixes"));
46
47static 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
55static cl::opt<bool> NoCanonicalizeWhiteSpace(
56 "strict-whitespace",
57 cl::desc("Do not treat all horizontal whitespace as equivalent"));
58
59static cl::opt<bool> IgnoreCase(
60 "ignore-case",
61 cl::desc("Use case-insensitive matching"));
62
63static 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
70static 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
75static cl::opt<bool> AllowEmptyInput(
76 "allow-empty", cl::init(Val: 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
80static cl::opt<bool> AllowUnusedPrefixes(
81 "allow-unused-prefixes",
82 cl::desc("Allow prefixes to be specified but not appear in the test."));
83
84static cl::opt<bool> MatchFullLines(
85 "match-full-lines", cl::init(Val: false),
86 cl::desc("Require all positive matches to cover an entire input line.\n"
87 "Allows leading and trailing whitespace if --strict-whitespace\n"
88 "is not also passed."));
89
90static cl::opt<bool> EnableVarScope(
91 "enable-var-scope", cl::init(Val: false),
92 cl::desc("Enables scope for regex variables. Variables with names that\n"
93 "do not start with '$' will be reset at the beginning of\n"
94 "each CHECK-LABEL block."));
95
96static cl::opt<bool> AllowDeprecatedDagOverlap(
97 "allow-deprecated-dag-overlap", cl::init(Val: false),
98 cl::desc("Enable overlapping among matches in a group of consecutive\n"
99 "CHECK-DAG directives. This option is deprecated and is only\n"
100 "provided for convenience as old tests are migrated to the new\n"
101 "non-overlapping CHECK-DAG implementation.\n"));
102
103static cl::opt<bool> Verbose(
104 "v",
105 cl::desc("Print directive pattern matches, or add them to the input dump\n"
106 "if enabled.\n"));
107
108static cl::opt<bool> VerboseVerbose(
109 "vv",
110 cl::desc("Print information helpful in diagnosing internal FileCheck\n"
111 "issues, or add it to the input dump if enabled. Implies\n"
112 "-v.\n"));
113
114// The order of DumpInputValue members affects their precedence, as documented
115// for -dump-input below.
116enum DumpInputValue {
117 DumpInputNever,
118 DumpInputFail,
119 DumpInputAlways,
120 DumpInputHelp
121};
122
123static cl::list<DumpInputValue> DumpInputs(
124 "dump-input",
125 cl::desc("Dump input to stderr, adding annotations representing\n"
126 "currently enabled diagnostics. When there are multiple\n"
127 "occurrences of this option, the <value> that appears earliest\n"
128 "in the list below has precedence. The default is 'fail'.\n"),
129 cl::value_desc("mode"),
130 cl::values(clEnumValN(DumpInputHelp, "help", "Explain input dump and quit"),
131 clEnumValN(DumpInputAlways, "always", "Always dump input"),
132 clEnumValN(DumpInputFail, "fail", "Dump input on failure"),
133 clEnumValN(DumpInputNever, "never", "Never dump input")));
134
135// The order of DumpInputFilterValue members affects their precedence, as
136// documented for -dump-input-filter below.
137enum DumpInputFilterValue {
138 DumpInputFilterError,
139 DumpInputFilterAnnotation,
140 DumpInputFilterAnnotationFull,
141 DumpInputFilterAll
142};
143
144static cl::list<DumpInputFilterValue> DumpInputFilters(
145 "dump-input-filter",
146 cl::desc("In the dump requested by -dump-input, print only input lines of\n"
147 "kind <value> plus any context specified by -dump-input-context.\n"
148 "When there are multiple occurrences of this option, the <value>\n"
149 "that appears earliest in the list below has precedence. The\n"
150 "default is 'error' when -dump-input=fail, and it's 'all' when\n"
151 "-dump-input=always.\n"),
152 cl::values(clEnumValN(DumpInputFilterAll, "all", "All input lines"),
153 clEnumValN(DumpInputFilterAnnotationFull, "annotation-full",
154 "Input lines with annotations"),
155 clEnumValN(DumpInputFilterAnnotation, "annotation",
156 "Input lines with starting points of annotations"),
157 clEnumValN(DumpInputFilterError, "error",
158 "Input lines with starting points of error "
159 "annotations")));
160
161static cl::list<unsigned> DumpInputContexts(
162 "dump-input-context", cl::value_desc("N"),
163 cl::desc("In the dump requested by -dump-input, print <N> input lines\n"
164 "before and <N> input lines after any lines specified by\n"
165 "-dump-input-filter. When there are multiple occurrences of\n"
166 "this option, the largest specified <N> has precedence. The\n"
167 "default is 5.\n"));
168
169static cl::opt<unsigned> DumpInputLabelWidth(
170 "dump-input-label-width", cl::value_desc("N"), cl::init(Val: 0), cl::Hidden,
171 cl::desc("In the dump requested by -dump-input, set <N> as the minimum\n"
172 "width for the initial label column. When there are multiple\n"
173 "occurrences of this option, the last specified has precedence.\n"
174 "The default is 0, meaning that the actual labels fully\n"
175 "determine the width. FileCheck's own test suite uses this\n"
176 "option to avoid a fluctuating column width when checking input\n"
177 "dumps. This option is not expected to be useful elsewhere.\n"));
178
179static void DumpCommandLine(int argc, char **argv) {
180 errs() << "FileCheck command line: ";
181 for (int I = 0; I < argc; I++)
182 errs() << " " << argv[I];
183 errs() << "\n";
184}
185
186struct MarkerStyle {
187 /// The first char for marking the input line.
188 char Head;
189 /// Every character for marking the input line between \c Head and \c Tail.
190 /// Normally it is a tilde.
191 char Mid;
192 /// The final char for marking the input line. Normally it is a tilde.
193 char Tail;
194 /// What color to use for this annotation.
195 raw_ostream::Colors Color;
196 /// A note to follow the marker, or empty string if none.
197 std::string Note;
198 /// Does this marker indicate inclusion by -dump-input-filter=error?
199 bool FiltersAsError;
200};
201
202static MarkerStyle getMarker(const FileCheckDiag &Diag) {
203 // By default, the marker is based on whether the diagnostic is an error or is
204 // a MatchNoteDiag on a MatchResultDiag that is an error.
205 //
206 // It's less confusing if diagnostics that don't actually have match ranges
207 // don't have markers. For example, a marker for the MatchNoteDiag
208 // 'with "VAR" equal to "5"' would seem to indicate where "VAR" matches, but
209 // we don't actually have that location. Instead, we just place the note
210 // after the start of the associated MatchResultDiag. Search ranges are
211 // indicated separately.
212 MarkerStyle Res;
213 bool IsError = Diag.isError() || Diag.getMatchResultDiag().isError();
214 if (Diag.getMatchRange()) {
215 Res.Head = IsError ? '!' : '^';
216 Res.Mid = Res.Tail = '~';
217 } else {
218 Res.Head = Res.Mid = Res.Tail = ' ';
219 }
220 Res.Color = IsError ? raw_ostream::RED : raw_ostream::GREEN;
221 Res.FiltersAsError = IsError;
222
223 // Add Note. Override the default Head and Color for some diagnostic kinds.
224 switch (Diag.getKind()) {
225 case FileCheckDiag::MatchFoundDiag:
226 switch (cast<MatchFoundDiag>(Val: Diag).getStatus()) {
227 case MatchFoundDiag::Success:
228 break;
229 case MatchFoundDiag::Excluded:
230 Res.Note = "no match expected";
231 break;
232 case MatchFoundDiag::WrongLine:
233 Res.Note = "match on wrong line";
234 break;
235 case MatchFoundDiag::Discarded:
236 Res.Head = '!'; // Not an error, but not a successful match either.
237 Res.Color = raw_ostream::CYAN;
238 Res.Note = "discard: overlaps earlier match";
239 break;
240 }
241 break;
242 case FileCheckDiag::MatchNoneDiag:
243 switch (cast<MatchNoneDiag>(Val: Diag).getStatus()) {
244 case MatchNoneDiag::Success:
245 break;
246 case MatchNoneDiag::InvalidPattern:
247 Res.Note = "match failed for invalid pattern";
248 break;
249 case MatchNoneDiag::Expected:
250 Res.Note = "no match found in search range";
251 break;
252 }
253 break;
254 case FileCheckDiag::MatchFuzzyDiag:
255 Res.Head = '?';
256 Res.Color = raw_ostream::MAGENTA;
257 Res.Note = "possible intended match";
258 break;
259 case FileCheckDiag::MatchCustomNoteDiag:
260 Res.Note = cast<MatchCustomNoteDiag>(Val: Diag).getNote();
261 break;
262 }
263 if (Diag.isError()) {
264 assert(!Res.Note.empty() && "expected error diagnostic to have note");
265 Res.Note = "error: " + Res.Note;
266 }
267 return Res;
268}
269
270static void DumpInputAnnotationHelp(raw_ostream &OS) {
271 OS << "The following description was requested by -dump-input=help to\n"
272 << "explain the input dump printed by FileCheck.\n"
273 << "\n"
274 << "Related command-line options:\n"
275 << "\n"
276 << " - -dump-input=<value> enables or disables the input dump\n"
277 << " - -dump-input-filter=<value> filters the input lines\n"
278 << " - -dump-input-context=<N> adjusts the context of filtered lines\n"
279 << " - -v and -vv add more annotations\n"
280 << " - -color forces colors to be enabled both in the dump and below\n"
281 << " - -help documents the above options in more detail\n"
282 << "\n"
283 << "These options can also be set via FILECHECK_OPTS. For example, for\n"
284 << "maximum debugging output on failures:\n"
285 << "\n"
286 << " $ FILECHECK_OPTS='-dump-input-filter=all -vv -color' ninja check\n"
287 << "\n"
288 << "Input dump annotation format:\n"
289 << "\n";
290
291 // Labels for input lines.
292 OS << " - ";
293 WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "L:";
294 OS << " labels line number L of the input file\n"
295 << " An extra space is added after each input line to represent"
296 << " the\n"
297 << " newline character\n";
298
299 // Labels for annotation lines.
300 OS << " - ";
301 WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L";
302 OS << " labels the only match result for either (1) a pattern of type T"
303 << " from\n"
304 << " line L of the check file if L is an integer or (2) the"
305 << " I-th implicit\n"
306 << " pattern if L is \"imp\" followed by an integer "
307 << "I (index origin one)\n";
308 OS << " - ";
309 WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L'N";
310 OS << " labels the Nth match result for such a pattern\n";
311
312 // Markers on annotation lines.
313 OS << " - ";
314 WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "^~~";
315 OS << " marks good match (reported if -v)\n"
316 << " - ";
317 WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "!~~";
318 OS << " marks bad match, such as:\n"
319 << " - CHECK-NEXT on same line as previous match (error)\n"
320 << " - CHECK-NOT found (error)\n"
321 << " - CHECK-DAG overlapping match (discarded, reported if "
322 << "-vv)\n"
323 << " - ";
324 WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "{ }";
325 OS << " encloses search range (exclusive bounds) when no match is found "
326 << "or\n"
327 << " there is an error, such as:\n"
328 << " - the errors mentioned above\n"
329 << " - CHECK-NEXT not found (error)\n"
330 << " - CHECK-NOT not found (success, reported if -vv)\n"
331 << " - CHECK-DAG not found after discarded matches (error)\n"
332 << " - ";
333 WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "?";
334 OS << " marks fuzzy match when no match is found\n";
335
336 // Elided lines.
337 OS << " - ";
338 WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "...";
339 OS << " indicates elided input lines and annotations, as specified by\n"
340 << " -dump-input-filter and -dump-input-context\n";
341
342 // Colors.
343 OS << " - colors ";
344 WithColor(OS, raw_ostream::GREEN, true) << "success";
345 OS << ", ";
346 WithColor(OS, raw_ostream::RED, true) << "error";
347 OS << ", ";
348 WithColor(OS, raw_ostream::MAGENTA, true) << "fuzzy match";
349 OS << ", ";
350 WithColor(OS, raw_ostream::CYAN, true, false) << "discarded match";
351 OS << ", ";
352 WithColor(OS, raw_ostream::CYAN, true, true) << "unmatched input";
353 OS << "\n";
354}
355
356/// An annotation for a single input line.
357struct InputAnnotation {
358 /// A globally unique index for this annotation before it was broken into
359 /// multiple lines.
360 unsigned LabelIndexGlobal;
361 /// The globally unique label for this annotation before it was broken into
362 /// multiple lines. There is one \c Label per \c LabelIndexGlobal and
363 /// vice-versa.
364 std::string Label;
365 /// Is this the initial (possibly only) fragment of an annotation, which has
366 /// been broken across multiple lines if necessary?
367 bool IsFirstLine;
368 /// What input line (one-origin indexing) this annotation marks. This might
369 /// be different from the starting line of the original diagnostic if
370 /// !IsFirstLine.
371 unsigned InputLine;
372 /// The column range (inclusive boundaries) in which to mark the input line.
373 /// A value of one indicates the first column of the actual input, and a
374 /// value of zero indicates the left margin. If \c InputLastCol is
375 /// \c UINT_MAX, the rest of the input line should be marked, and another
376 /// \c InputAnnotation will continue it on the next line.
377 unsigned InputFirstCol, InputLastCol;
378 /// The marker to use.
379 MarkerStyle Marker;
380 /// Whether this annotation represents a good match for an expected pattern.
381 bool FoundAndExpectedMatch;
382};
383
384/// Get an abbreviation for the check type.
385static std::string GetCheckTypeAbbreviation(Check::FileCheckType Ty) {
386 switch (Ty) {
387 case Check::CheckPlain:
388 if (Ty.getCount() > 1)
389 return "count";
390 return "check";
391 case Check::CheckNext:
392 return "next";
393 case Check::CheckSame:
394 return "same";
395 case Check::CheckNot:
396 return "not";
397 case Check::CheckDAG:
398 return "dag";
399 case Check::CheckLabel:
400 return "label";
401 case Check::CheckEmpty:
402 return "empty";
403 case Check::CheckComment:
404 return "com";
405 case Check::CheckEOF:
406 return "eof";
407 case Check::CheckBadNot:
408 return "bad-not";
409 case Check::CheckBadCount:
410 return "bad-count";
411 case Check::CheckMisspelled:
412 return "misspelled";
413 case Check::CheckNone:
414 llvm_unreachable("invalid FileCheckType");
415 }
416 llvm_unreachable("unknown FileCheckType");
417}
418
419template <> struct llvm::DenseMapInfo<SMLoc> {
420 static unsigned getHashValue(const SMLoc &Loc) {
421 return DenseMapInfo<const char *>::getHashValue(PtrVal: Loc.getPointer());
422 }
423 static bool isEqual(const SMLoc &LHS, SMLoc &RHS) { return LHS == RHS; }
424};
425
426namespace {
427/// Stores all information needed to generate \c InputAnnotation labels.
428class InputAnnotationLabeler {
429private:
430 const SourceMgr &SM;
431 const unsigned CheckFileBufferID;
432 const std::pair<unsigned, unsigned> ImpPatBufferIDRange;
433
434 /// How many unique input annotation labels does each check pattern need?
435 /// Each check pattern can have multiple \c MatchResultDiag's, each followed
436 /// by a series of zero or more \c MatchNoteDiag's. Each such
437 /// \c MatchResultDiag and its \c MatchNoteDiag series can require multiple
438 /// labels.
439 DenseMap<SMLoc, unsigned> LabelCountPerPattern;
440 /// For each check pattern, how many labels have we generated so far?
441 DenseMap<SMLoc, unsigned> LabelIndexPerPattern;
442 /// For each check pattern, what is the common prefix for all its labels?
443 DenseMap<SMLoc, std::string> LabelPrefixPerPattern;
444 /// How many total labels have we generated so far over all check patterns?
445 unsigned LabelIndexGlobal;
446 /// The widest label generated so far over all check patterns.
447 unsigned LabelWidthGlobal;
448
449public:
450 /// - \p CheckFileBufferID is the buffer ID for the check file.
451 /// - \p ImpPatBufferIDRange is the buffer ID range for all implicit patterns.
452 InputAnnotationLabeler(const SourceMgr &SM, unsigned CheckFileBufferID,
453 std::pair<unsigned, unsigned> ImpPatBufferIDRange)
454 : SM(SM), CheckFileBufferID(CheckFileBufferID),
455 ImpPatBufferIDRange(ImpPatBufferIDRange), LabelIndexGlobal(0),
456 LabelWidthGlobal(0) {}
457 /// Add \c C to the number of expected \c makeLabel calls for \c Diag.
458 /// \c expect must not be called after the first \c makeLabel call.
459 void expect(const FileCheckDiag &Diag, unsigned C) {
460 LabelCountPerPattern[Diag.getMatchResultDiag().getCheckLoc()] += C;
461 }
462 /// Write a new globally unique label for \c Diag into \p Label, and write its
463 /// globally unique index into LabelIndexGlobal. All \c makeLabel calls must
464 /// have already been predicted by \c expect calls.
465 void makeLabel(const FileCheckDiag &Diag, std::string &Label,
466 unsigned &LabelIndexGlobal) {
467 const MatchResultDiag &MRD = Diag.getMatchResultDiag();
468 SMLoc CheckLoc = MRD.getCheckLoc();
469 std::string &LabelPrefix = LabelPrefixPerPattern[CheckLoc];
470 if (LabelPrefix.empty()) {
471 llvm::raw_string_ostream LabelStrm(LabelPrefix);
472 LabelStrm << GetCheckTypeAbbreviation(Ty: MRD.getCheckTy()) << ":";
473 unsigned CheckBufferID = SM.FindBufferContainingLoc(Loc: CheckLoc);
474 if (CheckBufferID == CheckFileBufferID)
475 LabelStrm << SM.getLineAndColumn(Loc: CheckLoc, BufferID: CheckBufferID).first;
476 else if (ImpPatBufferIDRange.first <= CheckBufferID &&
477 CheckBufferID < ImpPatBufferIDRange.second)
478 LabelStrm << "imp" << (CheckBufferID - ImpPatBufferIDRange.first + 1);
479 else
480 llvm_unreachable(
481 "expected check location to be either in the check file or for an "
482 "implicit pattern");
483 }
484 assert(Label.empty() && "expected empty string for writing label");
485 llvm::raw_string_ostream LabelStrm(Label);
486 LabelStrm << LabelPrefix;
487 unsigned LabelCount = LabelCountPerPattern[CheckLoc];
488 unsigned LabelIndex = LabelIndexPerPattern[CheckLoc]++;
489 assert(LabelIndex < LabelCount &&
490 "expected all makeLabel calls to be predicted by expect calls");
491 if (LabelCount > 1)
492 LabelStrm << "'" << LabelIndex;
493 LabelWidthGlobal =
494 std::max(a: (std::string::size_type)LabelWidthGlobal, b: Label.size());
495 LabelIndexGlobal = this->LabelIndexGlobal++;
496 }
497 /// Get the widest label generated.
498 unsigned getLabelWidthGlobal() const { return LabelWidthGlobal; }
499};
500
501/// A range specifying where annotation markers are physically \a drawn in the
502/// input dump.
503struct MarkerRange {
504public:
505 /// An inclusive \c MarkerRange boundary. Both line and column use a 1-based
506 /// index origin.
507 struct Loc {
508 unsigned Line;
509 unsigned Col;
510 /// Make an invalid location to be overwritten before being used.
511 Loc() : Line(0), Col(0) {}
512 /// Make a valid location.
513 Loc(const std::pair<unsigned, unsigned> &LineAndCol)
514 : Line(LineAndCol.first), Col(LineAndCol.second) {}
515 };
516
517private:
518 /// Location of the first marked character.
519 Loc First;
520 /// Location of the last marked character.
521 Loc Last;
522
523public:
524 /// Make an invalid range to be overwritten before being used.
525 MarkerRange() = default;
526 /// \p Range specifies the \a logical input range to be depicted by annotation
527 /// markers \a drawn at the resulting \c MarkerRange.
528 ///
529 /// \a how that drawing depicts that logical input range is determined by
530 /// \p ShowExclusive. The drawing specifies either:
531 /// - The \a inclusive start and end bounds of the logical input range if
532 /// \p !ShowExclusive. In this case:
533 /// - If the logical input range is empty, then the resulting \c MarkerRange
534 /// is expanded to a single character. This avoids a missing marker, but
535 /// it means the markers for a single-character range are
536 /// indistinguishable from markers for an empty range.
537 /// - The first and last location of the \c MarkerRange are always real
538 /// locations in the input (never, for example, column 0).
539 /// - The \a exclusive start and end bounds of the logical input range if
540 /// \p ShowExclusive. In this case:
541 /// - The \c MarkerRange length is then always at least two because
542 /// exclusive boundaries never occupy the same location.
543 /// - If a \p Range boundary is an input line boundary, the corresponding
544 /// \c MarkerRange column might be in the line's margin (e.g., column 0)
545 /// to avoid placing a marker on an adjacent line. That decision can make
546 /// input annotations more concise (more line-liners) and easier to read.
547 /// It also avoids non-existent adjacent lines (e.g., line 0) that are not
548 /// depicted in the input dump.
549 MarkerRange(const SourceMgr &SM, SMRange Range, bool ShowExclusive = false) {
550 // Given an SMRange representing the range of text "range of text", the
551 // following example compares how it and the resulting MarkerRange encode
552 // the same start (s) and end (e) bounds:
553 //
554 // ....range of text....
555 // s e SMRange
556 // s e MarkerRange with ShowExclusive=false
557 // s e MarkerRange with ShowExclusive=true
558 if (ShowExclusive) {
559 // Range has inclusive start, but ShowExclusive requires exclusive start.
560 First = SM.getLineAndColumn(Loc: Range.Start);
561 --First.Col;
562 // Range has an exclusive end as ShowExclusive requires. If it is at a
563 // line boundary, it is at the start of the next line, so normally move it
564 // to the end of the previous line. For an empty range, do not do that as
565 // we do not want an end marker on the line before the start marker.
566 if (Range.Start == Range.End) {
567 Last = SM.getLineAndColumn(Loc: Range.End);
568 } else {
569 SMLoc EndLoc = SMLoc::getFromPointer(Ptr: Range.End.getPointer() - 1);
570 Last = SM.getLineAndColumn(Loc: EndLoc);
571 ++Last.Col;
572 }
573 return;
574 }
575 // Range has an inclusive start as !ShowExclusive requires.
576 First = SM.getLineAndColumn(Loc: Range.Start);
577 // Range has an exclusive end, but !ShowExclusive requires an inclusive end.
578 if (Range.Start == Range.End) {
579 // Convert the empty range to a one-character range.
580 Last = First;
581 } else {
582 // We cannot simply subtract one from the end column number because that
583 // might result in column 0, which does not exist and is thus incorrect
584 // for an inclusive boundary.
585 SMLoc EndLoc = SMLoc::getFromPointer(Ptr: Range.End.getPointer() - 1);
586 Last = SM.getLineAndColumn(Loc: EndLoc);
587 }
588 }
589 /// \p Loc specifies a single input character to be marked by a single
590 /// annotation marker character.
591 MarkerRange(Loc OneChar) : First(OneChar), Last(OneChar) {}
592 /// Is the marker range contained on a single line?
593 bool isSingleLine() const { return First.Line == Last.Line; }
594 /// Get the location of the first marked character.
595 Loc getFirstLoc() const { return First; }
596 /// Get the location of the last marked character.
597 Loc getLastLoc() const { return Last; }
598};
599
600/// Emits search range annotations for each \c MatchResultDiag as it is
601/// encountered.
602///
603/// In some cases, it emits a single, one-line annotation. Otherwise, it emits
604/// separate annotations for the start and end of the search range. The logic
605/// for making this determination is encapsulated in static member functions.
606class SearchRangeAnnotator {
607private:
608 const SourceMgr &SM;
609 InputAnnotationLabeler &Labeler;
610 std::vector<InputAnnotation> &Annotations;
611
612 /// The most recent \c MatchResultDiag, or \c nullptr if all search range
613 /// annotations have been added already for the most recent
614 /// \c MatchResultDiag.
615 const MatchResultDiag *MRD;
616 /// Assuming \c makesAnnotationsFor(MRD), would a \c SearchRangeAnnotator make
617 /// a one-line search range annotation for \p MRD? Either way, the search
618 /// range computed for \p MRD is stored in \p SearchRange.
619 static bool makesOneLinerFor(const SourceMgr &SM, const MatchResultDiag &MRD,
620 MarkerRange &SearchRange) {
621 assert(makesAnnotationsFor(MRD) &&
622 "expected makesAnnotationsFor to be checked first");
623 SearchRange = {SM, MRD.getSearchRange(), /*ShowExclusive=*/true};
624 return SearchRange.isSingleLine();
625 }
626 /// Make the next annotation for the current \c MatchResultDiag.
627 void makeAnnotation(bool Start) {
628 InputAnnotation &A = Annotations.emplace_back();
629 Labeler.makeLabel(Diag: *MRD, Label&: A.Label, LabelIndexGlobal&: A.LabelIndexGlobal);
630 A.IsFirstLine = true;
631 A.FoundAndExpectedMatch = false;
632 MarkerRange SearchRange;
633 if (makesOneLinerFor(SM, MRD: *MRD, SearchRange)) {
634 assert(Start && "expected no search range end annotation for one-liner");
635 A.InputLine = SearchRange.getFirstLoc().Line;
636 A.InputFirstCol = SearchRange.getFirstLoc().Col;
637 A.InputLastCol = SearchRange.getLastLoc().Col;
638 MatchCustomNoteDiag NoteDiag("search range (exclusive bounds)");
639 NoteDiag.setMatchResultDiag(MRD);
640 A.Marker = getMarker(Diag: NoteDiag);
641 A.Marker.Head = '{';
642 A.Marker.Mid = ' ';
643 A.Marker.Tail = '}';
644 MRD = nullptr;
645 return;
646 }
647 // We have separate annotations for start and end.
648 MarkerRange::Loc Loc =
649 Start ? SearchRange.getFirstLoc() : SearchRange.getLastLoc();
650 A.InputLine = Loc.Line;
651 A.InputFirstCol = A.InputLastCol = Loc.Col;
652 MatchCustomNoteDiag NoteDiag(std::string("search range ") +
653 (Start ? "start" : "end") + " (exclusive)");
654 NoteDiag.setMatchResultDiag(MRD);
655 A.Marker = getMarker(Diag: NoteDiag);
656 A.Marker.Head = Start ? '{' : '}';
657 }
658
659public:
660 /// Would a \c SearchRangeAnnotator make any search range annotations for
661 /// \p MRD?
662 static bool makesAnnotationsFor(const MatchResultDiag &MRD) {
663 return !MRD.getMatchRange() || MRD.isError();
664 }
665 /// Tell the labeler how many times this will call
666 /// \c InputAnnotationLabeler::makeLabel for \c MRD.
667 void predictLabelsFor(const MatchResultDiag &MRD) {
668 if (!makesAnnotationsFor(MRD))
669 return;
670 MarkerRange SearchRange;
671 Labeler.expect(Diag: MRD, C: makesOneLinerFor(SM, MRD, SearchRange) ? 1 : 2);
672 }
673 /// \p Annotations is where this annotator should append search range
674 /// annotations.
675 SearchRangeAnnotator(const SourceMgr &SM, InputAnnotationLabeler &Labeler,
676 std::vector<InputAnnotation> &Annotations)
677 : SM(SM), Labeler(Labeler), Annotations(Annotations), MRD(nullptr) {}
678 /// Emit any search range start annotation or one-line search range annotation
679 /// for \p MRDNew. Emit any search range end annotation for \p MRDNew at the
680 /// next call to \c newMatchResultDiag or \c endDiags.
681 void newMatchResultDiag(const MatchResultDiag &MRDNew) {
682 if (MRD) {
683 makeAnnotation(/*Start=*/false);
684 MRD = nullptr;
685 }
686 if (makesAnnotationsFor(MRD: MRDNew)) {
687 MRD = &MRDNew;
688 makeAnnotation(/*Start=*/true);
689 }
690 }
691 /// Emit any search range end annotation for the final \c MatchResultDiag
692 /// passed to \c newMatchResultDiag.
693 void endDiags() {
694 if (MRD)
695 makeAnnotation(/*Start=*/false);
696 }
697};
698
699/// Emits the main annotations for each \c FileCheckDiag as it is encountered.
700class FileCheckDiagAnnotator {
701private:
702 const SourceMgr &SM;
703 InputAnnotationLabeler &Labeler;
704 std::vector<InputAnnotation> &Annotations;
705 /// Would a \c FileCheckDiagAnnotator make any annotations for \p Diag?
706 static bool makesAnnotationsFor(const FileCheckDiag &Diag) {
707 const MatchResultDiag *MRD = dyn_cast<MatchResultDiag>(Val: &Diag);
708 if (!MRD)
709 return true;
710 if (SearchRangeAnnotator::makesAnnotationsFor(MRD: *MRD) &&
711 getMarker(Diag: *MRD).Note.empty())
712 return false;
713 return true;
714 }
715
716public:
717 /// Tell the labeler how many times this will call
718 /// \c InputAnnotationLabeler::makeLabel for \c Diag.
719 void predictLabelsFor(const FileCheckDiag &Diag) {
720 Labeler.expect(Diag, C: makesAnnotationsFor(Diag) ? 1 : 0);
721 }
722 /// \p Annotations is where this annotator should append annotations.
723 FileCheckDiagAnnotator(const SourceMgr &SM, InputAnnotationLabeler &Labeler,
724 std::vector<InputAnnotation> &Annotations)
725 : SM(SM), Labeler(Labeler), Annotations(Annotations) {}
726 /// Emit any annotations for \c Diag.
727 void makeAnnotations(const FileCheckDiag &Diag) {
728 if (!makesAnnotationsFor(Diag))
729 return;
730
731 // Build label that is unique for this input annotation before it is
732 // potentially broken across multiple lines.
733 InputAnnotation A;
734 Labeler.makeLabel(Diag, Label&: A.Label, LabelIndexGlobal&: A.LabelIndexGlobal);
735
736 // Build the input marker.
737 A.Marker = getMarker(Diag);
738
739 // Does this diagnostic mark text that has been successfully matched?
740 A.FoundAndExpectedMatch = false;
741 if (const MatchFoundDiag *Found = dyn_cast<MatchFoundDiag>(Val: &Diag)) {
742 if (Found->getStatus() == MatchFoundDiag::Success)
743 A.FoundAndExpectedMatch = true;
744 }
745
746 // If Diag has a match range, position the marker there. Otherwise,
747 // position the marker at the start of the most recent MatchResultDiag, with
748 // which it is associated.
749 MarkerRange InputRange;
750 if (Diag.getMatchRange()) {
751 InputRange = MarkerRange(SM, *Diag.getMatchRange());
752 } else {
753 const MatchResultDiag &MRD = Diag.getMatchResultDiag();
754 InputRange = MRD.getMatchRange() ? MarkerRange(SM, *MRD.getMatchRange())
755 : MarkerRange(SM, MRD.getSearchRange());
756 InputRange = MarkerRange(InputRange.getFirstLoc());
757 assert(A.Marker.Head == ' ' && "expected no marker for no match range");
758 }
759
760 // Compute the marker location, and break annotation into multiple
761 // annotations if it spans multiple lines.
762 A.IsFirstLine = true;
763 A.InputLine = InputRange.getFirstLoc().Line;
764 A.InputFirstCol = InputRange.getFirstLoc().Col;
765 if (InputRange.isSingleLine()) {
766 A.InputLastCol = InputRange.getLastLoc().Col;
767 Annotations.push_back(x: A);
768 } else {
769 A.InputLastCol = UINT_MAX;
770 char MarkerTail = A.Marker.Tail;
771 A.Marker.Tail = A.Marker.Mid;
772 Annotations.push_back(x: A);
773 for (unsigned L = InputRange.getFirstLoc().Line + 1,
774 E = InputRange.getLastLoc().Line;
775 L <= E; ++L) {
776 InputAnnotation B;
777 B.LabelIndexGlobal = A.LabelIndexGlobal;
778 B.Label = A.Label;
779 B.IsFirstLine = false;
780 B.InputLine = L;
781 B.Marker = A.Marker;
782 B.Marker.Head = B.Marker.Mid = A.Marker.Mid;
783 B.Marker.Tail = L != E ? A.Marker.Mid : MarkerTail;
784 B.Marker.Note = "";
785 B.InputFirstCol = 1;
786 B.InputLastCol = L != E ? UINT_MAX : InputRange.getLastLoc().Col;
787 B.FoundAndExpectedMatch = A.FoundAndExpectedMatch;
788 Annotations.push_back(x: B);
789 }
790 }
791 }
792};
793} // namespace
794
795static void
796buildInputAnnotations(const SourceMgr &SM, unsigned CheckFileBufferID,
797 const std::pair<unsigned, unsigned> &ImpPatBufferIDRange,
798 const FileCheckDiagList &Diags,
799 std::vector<InputAnnotation> &Annotations,
800 unsigned &LabelWidthGlobal) {
801 InputAnnotationLabeler Labeler(SM, CheckFileBufferID, ImpPatBufferIDRange);
802 SearchRangeAnnotator TheSearchRangeAnnotator(SM, Labeler, Annotations);
803 FileCheckDiagAnnotator TheFileCheckDiagAnnotator(SM, Labeler, Annotations);
804 for (const FileCheckDiag &Diag : Diags) {
805 if (const MatchResultDiag *MRD = dyn_cast<MatchResultDiag>(Val: &Diag))
806 TheSearchRangeAnnotator.predictLabelsFor(MRD: *MRD);
807 TheFileCheckDiagAnnotator.predictLabelsFor(Diag);
808 }
809 for (const FileCheckDiag &Diag : Diags) {
810 if (const MatchResultDiag *MRD = dyn_cast<MatchResultDiag>(Val: &Diag))
811 TheSearchRangeAnnotator.newMatchResultDiag(MRDNew: *MRD);
812 TheFileCheckDiagAnnotator.makeAnnotations(Diag);
813 }
814 TheSearchRangeAnnotator.endDiags();
815 LabelWidthGlobal = Labeler.getLabelWidthGlobal();
816}
817
818static unsigned FindInputLineInFilter(
819 DumpInputFilterValue DumpInputFilter, unsigned CurInputLine,
820 const std::vector<InputAnnotation>::iterator &AnnotationBeg,
821 const std::vector<InputAnnotation>::iterator &AnnotationEnd) {
822 if (DumpInputFilter == DumpInputFilterAll)
823 return CurInputLine;
824 for (auto AnnotationItr = AnnotationBeg; AnnotationItr != AnnotationEnd;
825 ++AnnotationItr) {
826 switch (DumpInputFilter) {
827 case DumpInputFilterAll:
828 llvm_unreachable("unexpected DumpInputFilterAll");
829 break;
830 case DumpInputFilterAnnotationFull:
831 return AnnotationItr->InputLine;
832 case DumpInputFilterAnnotation:
833 if (AnnotationItr->IsFirstLine)
834 return AnnotationItr->InputLine;
835 break;
836 case DumpInputFilterError:
837 if (AnnotationItr->IsFirstLine && AnnotationItr->Marker.FiltersAsError)
838 return AnnotationItr->InputLine;
839 break;
840 }
841 }
842 return UINT_MAX;
843}
844
845/// To OS, print a vertical ellipsis (right-justified at LabelWidthGlobal) if it
846/// would occupy less lines than ElidedLines, but print ElidedLines otherwise.
847/// Either way, clear ElidedLines. Thus, if ElidedLines is empty, do nothing.
848static void DumpEllipsisOrElidedLines(raw_ostream &OS, std::string &ElidedLines,
849 unsigned LabelWidthGlobal) {
850 if (ElidedLines.empty())
851 return;
852 unsigned EllipsisLines = 3;
853 if (EllipsisLines < StringRef(ElidedLines).count(C: '\n')) {
854 for (unsigned i = 0; i < EllipsisLines; ++i) {
855 WithColor(OS, raw_ostream::BRIGHT_BLACK, /*Bold=*/true)
856 << right_justify(Str: ".", Width: LabelWidthGlobal);
857 OS << '\n';
858 }
859 } else
860 OS << ElidedLines;
861 ElidedLines.clear();
862}
863
864static void DumpAnnotatedInput(raw_ostream &OS, const FileCheckRequest &Req,
865 DumpInputFilterValue DumpInputFilter,
866 unsigned DumpInputContext,
867 StringRef InputFileText,
868 std::vector<InputAnnotation> &Annotations,
869 unsigned LabelWidthGlobal) {
870 OS << "Input was:\n<<<<<<\n";
871
872 // Sort annotations.
873 llvm::sort(C&: Annotations,
874 Comp: [](const InputAnnotation &A, const InputAnnotation &B) {
875 // 1. Sort annotations in the order of the input lines.
876 //
877 // This makes it easier to find relevant annotations while
878 // iterating input lines in the implementation below. FileCheck
879 // does not always produce diagnostics in the order of input
880 // lines due to, for example, CHECK-DAG and CHECK-NOT.
881 if (A.InputLine != B.InputLine)
882 return A.InputLine < B.InputLine;
883 // 2. Sort annotations in the temporal order FileCheck produced
884 // their associated diagnostics.
885 //
886 // This sort offers several benefits:
887 //
888 // A. On a single input line, the order of annotations reflects
889 // the FileCheck logic for processing directives/patterns.
890 // This can be helpful in understanding cases in which the
891 // order of the associated directives/patterns in the check
892 // file or on the command line either (i) does not match the
893 // temporal order in which FileCheck looks for matches for the
894 // directives/patterns (due to, for example, CHECK-LABEL,
895 // CHECK-NOT, or `--implicit-check-not`) or (ii) does match
896 // that order but does not match the order of those
897 // diagnostics along an input line (due to, for example,
898 // CHECK-DAG).
899 //
900 // On the other hand, because our presentation format presents
901 // input lines in order, there's no clear way to offer the
902 // same benefit across input lines. For consistency, it might
903 // then seem worthwhile to have annotations on a single line
904 // also sorted in input order (that is, by input column).
905 // However, in practice, this appears to be more confusing
906 // than helpful. Perhaps it's intuitive to expect annotations
907 // to be listed in the temporal order in which they were
908 // produced except in cases the presentation format obviously
909 // and inherently cannot support it (that is, across input
910 // lines).
911 //
912 // B. When diagnostics' annotations are split among multiple
913 // input lines, the user must track them from one input line
914 // to the next. One property of the sort chosen here is that
915 // it facilitates the user in this regard by ensuring the
916 // following: when comparing any two input lines, a
917 // diagnostic's annotations are sorted in the same position
918 // relative to all other diagnostics' annotations.
919 return A.LabelIndexGlobal < B.LabelIndexGlobal;
920 });
921
922 // Compute the width of the label column.
923 const unsigned char *InputFilePtr = InputFileText.bytes_begin(),
924 *InputFileEnd = InputFileText.bytes_end();
925 unsigned LineCount = InputFileText.count(C: '\n');
926 if (InputFileEnd[-1] != '\n')
927 ++LineCount;
928 unsigned LineNoWidth = NumDigitsBase10(X: LineCount);
929 // +3 below adds spaces (1) to the left of the (right-aligned) line numbers
930 // on input lines and (2) to the right of the (left-aligned) labels on
931 // annotation lines so that input lines and annotation lines are more
932 // visually distinct. For example, the spaces on the annotation lines ensure
933 // that input line numbers and check directive line numbers never align
934 // horizontally. Those line numbers might not even be for the same file.
935 // One space would be enough to achieve that, but more makes it even easier
936 // to see.
937 LabelWidthGlobal = std::max(a: LabelWidthGlobal, b: LineNoWidth) + 3;
938 LabelWidthGlobal = std::max(a: LabelWidthGlobal, b: DumpInputLabelWidth.getValue());
939
940 // Print annotated input lines.
941 unsigned PrevLineInFilter = 0; // 0 means none so far
942 unsigned NextLineInFilter = 0; // 0 means uncomputed, UINT_MAX means none
943 std::string ElidedLines;
944 raw_string_ostream ElidedLinesOS(ElidedLines);
945 ColorMode TheColorMode =
946 WithColor(OS).colorsEnabled() ? ColorMode::Enable : ColorMode::Disable;
947 if (TheColorMode == ColorMode::Enable)
948 ElidedLinesOS.enable_colors(enable: true);
949 auto AnnotationItr = Annotations.begin(), AnnotationEnd = Annotations.end();
950 for (unsigned Line = 1;
951 InputFilePtr != InputFileEnd || AnnotationItr != AnnotationEnd;
952 ++Line) {
953 const unsigned char *InputFileLine = InputFilePtr;
954
955 // Compute the previous and next line included by the filter.
956 if (NextLineInFilter < Line)
957 NextLineInFilter = FindInputLineInFilter(DumpInputFilter, CurInputLine: Line,
958 AnnotationBeg: AnnotationItr, AnnotationEnd);
959 assert(NextLineInFilter && "expected NextLineInFilter to be computed");
960 if (NextLineInFilter == Line)
961 PrevLineInFilter = Line;
962
963 // Elide this input line and its annotations if it's not within the
964 // context specified by -dump-input-context of an input line included by
965 // -dump-input-filter. However, in case the resulting ellipsis would occupy
966 // more lines than the input lines and annotations it elides, buffer the
967 // elided lines and annotations so we can print them instead.
968 raw_ostream *LineOS;
969 if ((!PrevLineInFilter || PrevLineInFilter + DumpInputContext < Line) &&
970 (NextLineInFilter == UINT_MAX ||
971 Line + DumpInputContext < NextLineInFilter))
972 LineOS = &ElidedLinesOS;
973 else {
974 LineOS = &OS;
975 DumpEllipsisOrElidedLines(OS, ElidedLines, LabelWidthGlobal);
976 }
977
978 // Print right-aligned line number.
979 WithColor(*LineOS, raw_ostream::BRIGHT_BLACK, /*Bold=*/true, /*BG=*/false,
980 TheColorMode)
981 << format_decimal(N: Line, Width: LabelWidthGlobal) << ": ";
982
983 // For the case where -v and colors are enabled, find the annotations for
984 // good matches for expected patterns in order to highlight everything
985 // else in the line. There are no such annotations if -v is disabled.
986 std::vector<InputAnnotation> FoundAndExpectedMatches;
987 if (Req.Verbose && TheColorMode == ColorMode::Enable) {
988 for (auto I = AnnotationItr; I != AnnotationEnd && I->InputLine == Line;
989 ++I) {
990 if (I->FoundAndExpectedMatch)
991 FoundAndExpectedMatches.push_back(x: *I);
992 }
993 }
994
995 // Print numbered line with highlighting where there are no matches for
996 // expected patterns.
997 bool Newline = false;
998 {
999 WithColor COS(*LineOS, raw_ostream::SAVEDCOLOR, /*Bold=*/false,
1000 /*BG=*/false, TheColorMode);
1001 bool InMatch = false;
1002 if (Req.Verbose) {
1003 COS.changeColor(Color: raw_ostream::CYAN, /*Bold=*/true, /*BG=*/true);
1004 } else {
1005 // Our goal is to use the output streams's default color so that input
1006 // text is legibile in both light and dark themes. SAVEDCOLOR above
1007 // currently ignores the Bold=false there, so we override it with
1008 // resetColor here, which ensures consistent colors with the resetColor
1009 // below anyway.
1010 COS.resetColor();
1011 }
1012 for (unsigned Col = 1; InputFilePtr != InputFileEnd && !Newline; ++Col) {
1013 bool WasInMatch = InMatch;
1014 InMatch = false;
1015 for (const InputAnnotation &M : FoundAndExpectedMatches) {
1016 if (M.InputFirstCol <= Col && Col <= M.InputLastCol) {
1017 InMatch = true;
1018 break;
1019 }
1020 }
1021 // If !Req.Verbose, FoundAndExpectedMatches is empty, so InMatch and
1022 // WasInMatch remain false, so these color transitions never happen.
1023 if (!WasInMatch && InMatch)
1024 COS.resetColor();
1025 else if (WasInMatch && !InMatch)
1026 COS.changeColor(Color: raw_ostream::CYAN, Bold: true, BG: true);
1027 if (*InputFilePtr == '\n') {
1028 Newline = true;
1029 COS << ' ';
1030 } else
1031 COS << *InputFilePtr;
1032 ++InputFilePtr;
1033 }
1034 }
1035 *LineOS << '\n';
1036 unsigned InputLineWidth = InputFilePtr - InputFileLine;
1037
1038 // Print any annotations.
1039 while (AnnotationItr != AnnotationEnd &&
1040 AnnotationItr->InputLine == Line) {
1041 WithColor COS(*LineOS, AnnotationItr->Marker.Color, /*Bold=*/true,
1042 /*BG=*/false, TheColorMode);
1043 // The space below aligns with the ":" on the input line.
1044 COS << left_justify(Str: AnnotationItr->Label, Width: LabelWidthGlobal) << " ";
1045 unsigned Col;
1046 // A search range annotation at the beginning of the line starts at column
1047 // 0 because it is an exclusive boundary.
1048 for (Col = 0; Col < AnnotationItr->InputFirstCol; ++Col)
1049 COS << ' ';
1050 COS << AnnotationItr->Marker.Head;
1051 // If InputLastCol==UINT_MAX, stop at InputLineWidth.
1052 for (++Col; Col < AnnotationItr->InputLastCol && Col <= InputLineWidth;
1053 ++Col)
1054 COS << AnnotationItr->Marker.Mid;
1055 if (Col <= AnnotationItr->InputLastCol &&
1056 AnnotationItr->InputLastCol != UINT_MAX) {
1057 COS << AnnotationItr->Marker.Tail;
1058 ++Col;
1059 }
1060 const std::string &Note = AnnotationItr->Marker.Note;
1061 if (!Note.empty()) {
1062 // Put the note at the end of the input line. If we were to instead
1063 // put the note right after the marker, subsequent annotations for the
1064 // same input line might appear to mark this note instead of the input
1065 // line.
1066 for (; Col <= InputLineWidth + 1; ++Col)
1067 COS << ' ';
1068 COS << ' ' << Note;
1069 }
1070 COS << '\n';
1071 ++AnnotationItr;
1072 }
1073 }
1074 DumpEllipsisOrElidedLines(OS, ElidedLines, LabelWidthGlobal);
1075
1076 OS << ">>>>>>\n";
1077}
1078
1079int main(int argc, char **argv) {
1080 // Enable use of ANSI color codes because FileCheck is using them to
1081 // highlight text.
1082 llvm::sys::Process::UseANSIEscapeCodes(enable: true);
1083
1084 InitLLVM X(argc, argv);
1085 cl::ParseCommandLineOptions(argc, argv, /*Overview*/ "", /*Errs*/ nullptr,
1086 /*VFS*/ nullptr, EnvVar: "FILECHECK_OPTS");
1087
1088 // Select -dump-input* values. The -help documentation specifies the default
1089 // value and which value to choose if an option is specified multiple times.
1090 // In the latter case, the general rule of thumb is to choose the value that
1091 // provides the most information.
1092 DumpInputValue DumpInput =
1093 DumpInputs.empty() ? DumpInputFail : *llvm::max_element(Range&: DumpInputs);
1094 DumpInputFilterValue DumpInputFilter;
1095 if (DumpInputFilters.empty())
1096 DumpInputFilter = DumpInput == DumpInputAlways ? DumpInputFilterAll
1097 : DumpInputFilterError;
1098 else
1099 DumpInputFilter = *llvm::max_element(Range&: DumpInputFilters);
1100 unsigned DumpInputContext =
1101 DumpInputContexts.empty() ? 5 : *llvm::max_element(Range&: DumpInputContexts);
1102
1103 if (DumpInput == DumpInputHelp) {
1104 DumpInputAnnotationHelp(OS&: outs());
1105 return 0;
1106 }
1107 if (CheckFilename.empty()) {
1108 errs() << "<check-file> not specified\n";
1109 return 2;
1110 }
1111
1112 FileCheckRequest Req;
1113 append_range(C&: Req.CheckPrefixes, R&: CheckPrefixes);
1114
1115 append_range(C&: Req.CommentPrefixes, R&: CommentPrefixes);
1116
1117 append_range(C&: Req.ImplicitCheckNot, R&: ImplicitCheckNot);
1118
1119 bool GlobalDefineError = false;
1120 for (StringRef G : GlobalDefines) {
1121 size_t EqIdx = G.find(C: '=');
1122 if (EqIdx == std::string::npos) {
1123 errs() << "Missing equal sign in command-line definition '-D" << G
1124 << "'\n";
1125 GlobalDefineError = true;
1126 continue;
1127 }
1128 if (EqIdx == 0) {
1129 errs() << "Missing variable name in command-line definition '-D" << G
1130 << "'\n";
1131 GlobalDefineError = true;
1132 continue;
1133 }
1134 Req.GlobalDefines.push_back(x: G);
1135 }
1136 if (GlobalDefineError)
1137 return 2;
1138
1139 Req.AllowEmptyInput = AllowEmptyInput;
1140 Req.AllowUnusedPrefixes = AllowUnusedPrefixes;
1141 Req.EnableVarScope = EnableVarScope;
1142 Req.AllowDeprecatedDagOverlap = AllowDeprecatedDagOverlap;
1143 Req.Verbose = Verbose;
1144 Req.VerboseVerbose = VerboseVerbose;
1145 Req.NoCanonicalizeWhiteSpace = NoCanonicalizeWhiteSpace;
1146 Req.MatchFullLines = MatchFullLines;
1147 Req.IgnoreCase = IgnoreCase;
1148
1149 if (VerboseVerbose)
1150 Req.Verbose = true;
1151
1152 FileCheck FC(Req);
1153 if (!FC.ValidateCheckPrefixes())
1154 return 2;
1155
1156 SourceMgr SM;
1157
1158 // Read the expected strings from the check file.
1159 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckFileOrErr =
1160 MemoryBuffer::getFileOrSTDIN(Filename: CheckFilename, /*IsText=*/true);
1161 if (std::error_code EC = CheckFileOrErr.getError()) {
1162 errs() << "Could not open check file '" << CheckFilename
1163 << "': " << EC.message() << '\n';
1164 return 2;
1165 }
1166 MemoryBuffer &CheckFile = *CheckFileOrErr.get();
1167
1168 SmallString<4096> CheckFileBuffer;
1169 StringRef CheckFileText = FC.CanonicalizeFile(MB&: CheckFile, OutputBuffer&: CheckFileBuffer);
1170
1171 unsigned CheckFileBufferID =
1172 SM.AddNewSourceBuffer(F: MemoryBuffer::getMemBuffer(
1173 InputData: CheckFileText, BufferName: CheckFile.getBufferIdentifier()),
1174 IncludeLoc: SMLoc());
1175
1176 std::pair<unsigned, unsigned> ImpPatBufferIDRange;
1177 if (FC.readCheckFile(SM, Buffer: CheckFileText, ImpPatBufferIDRange: &ImpPatBufferIDRange))
1178 return 2;
1179
1180 // Open the file to check and add it to SourceMgr.
1181 ErrorOr<std::unique_ptr<MemoryBuffer>> InputFileOrErr =
1182 MemoryBuffer::getFileOrSTDIN(Filename: InputFilename, /*IsText=*/true);
1183 if (InputFilename == "-")
1184 InputFilename = "<stdin>"; // Overwrite for improved diagnostic messages
1185 if (std::error_code EC = InputFileOrErr.getError()) {
1186 errs() << "Could not open input file '" << InputFilename
1187 << "': " << EC.message() << '\n';
1188 return 2;
1189 }
1190 MemoryBuffer &InputFile = *InputFileOrErr.get();
1191
1192 if (InputFile.getBufferSize() == 0 && !AllowEmptyInput) {
1193 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
1194 DumpCommandLine(argc, argv);
1195 return 2;
1196 }
1197
1198 SmallString<4096> InputFileBuffer;
1199 StringRef InputFileText = FC.CanonicalizeFile(MB&: InputFile, OutputBuffer&: InputFileBuffer);
1200
1201 SM.AddNewSourceBuffer(F: MemoryBuffer::getMemBuffer(
1202 InputData: InputFileText, BufferName: InputFile.getBufferIdentifier()),
1203 IncludeLoc: SMLoc());
1204
1205 FileCheckDiagList Diags;
1206 int ExitCode = FC.checkInput(SM, Buffer: InputFileText,
1207 Diags: DumpInput == DumpInputNever ? nullptr : &Diags)
1208 ? EXIT_SUCCESS
1209 : 1;
1210 if (DumpInput == DumpInputAlways ||
1211 (ExitCode == 1 && DumpInput == DumpInputFail)) {
1212 errs() << "\n"
1213 << "Input file: " << InputFilename << "\n"
1214 << "Check file: " << CheckFilename << "\n"
1215 << "\n"
1216 << "-dump-input=help explains the following input dump.\n"
1217 << "\n";
1218 std::vector<InputAnnotation> Annotations;
1219 unsigned LabelWidthGlobal;
1220 buildInputAnnotations(SM, CheckFileBufferID, ImpPatBufferIDRange, Diags,
1221 Annotations, LabelWidthGlobal);
1222 DumpAnnotatedInput(OS&: errs(), Req, DumpInputFilter, DumpInputContext,
1223 InputFileText, Annotations, LabelWidthGlobal);
1224 }
1225
1226 return ExitCode;
1227}
1228