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 static void DumpAnnotatedInput(raw_ostream &OS, const FileCheckRequest &Req, 433 bool DumpInputFilterOnError, 434 unsigned DumpInputContext, 435 StringRef InputFileText, 436 std::vector<InputAnnotation> &Annotations, 437 unsigned LabelWidth) { 438 OS << "Input was:\n<<<<<<\n"; 439 440 // Sort annotations. 441 std::sort(Annotations.begin(), Annotations.end(), 442 [](const InputAnnotation &A, const InputAnnotation &B) { 443 // 1. Sort annotations in the order of the input lines. 444 // 445 // This makes it easier to find relevant annotations while 446 // iterating input lines in the implementation below. FileCheck 447 // does not always produce diagnostics in the order of input 448 // lines due to, for example, CHECK-DAG and CHECK-NOT. 449 if (A.InputLine != B.InputLine) 450 return A.InputLine < B.InputLine; 451 // 2. Sort annotations in the temporal order FileCheck produced 452 // their associated diagnostics. 453 // 454 // This sort offers several benefits: 455 // 456 // A. On a single input line, the order of annotations reflects 457 // the FileCheck logic for processing directives/patterns. 458 // This can be helpful in understanding cases in which the 459 // order of the associated directives/patterns in the check 460 // file or on the command line either (i) does not match the 461 // temporal order in which FileCheck looks for matches for the 462 // directives/patterns (due to, for example, CHECK-LABEL, 463 // CHECK-NOT, or `--implicit-check-not`) or (ii) does match 464 // that order but does not match the order of those 465 // diagnostics along an input line (due to, for example, 466 // CHECK-DAG). 467 // 468 // On the other hand, because our presentation format presents 469 // input lines in order, there's no clear way to offer the 470 // same benefit across input lines. For consistency, it might 471 // then seem worthwhile to have annotations on a single line 472 // also sorted in input order (that is, by input column). 473 // However, in practice, this appears to be more confusing 474 // than helpful. Perhaps it's intuitive to expect annotations 475 // to be listed in the temporal order in which they were 476 // produced except in cases the presentation format obviously 477 // and inherently cannot support it (that is, across input 478 // lines). 479 // 480 // B. When diagnostics' annotations are split among multiple 481 // input lines, the user must track them from one input line 482 // to the next. One property of the sort chosen here is that 483 // it facilitates the user in this regard by ensuring the 484 // following: when comparing any two input lines, a 485 // diagnostic's annotations are sorted in the same position 486 // relative to all other diagnostics' annotations. 487 return A.DiagIndex < B.DiagIndex; 488 }); 489 490 // Compute the width of the label column. 491 const unsigned char *InputFilePtr = InputFileText.bytes_begin(), 492 *InputFileEnd = InputFileText.bytes_end(); 493 unsigned LineCount = InputFileText.count('\n'); 494 if (InputFileEnd[-1] != '\n') 495 ++LineCount; 496 unsigned LineNoWidth = std::log10(LineCount) + 1; 497 // +3 below adds spaces (1) to the left of the (right-aligned) line numbers 498 // on input lines and (2) to the right of the (left-aligned) labels on 499 // annotation lines so that input lines and annotation lines are more 500 // visually distinct. For example, the spaces on the annotation lines ensure 501 // that input line numbers and check directive line numbers never align 502 // horizontally. Those line numbers might not even be for the same file. 503 // One space would be enough to achieve that, but more makes it even easier 504 // to see. 505 LabelWidth = std::max(LabelWidth, LineNoWidth) + 3; 506 507 // Print annotated input lines. 508 unsigned PrevLineInFilter = 0; // 0 means none so far 509 unsigned NextLineInFilter = 0; // 0 means uncomputed, UINT_MAX means none 510 bool PrevLineElided = false; 511 auto AnnotationItr = Annotations.begin(), AnnotationEnd = Annotations.end(); 512 for (unsigned Line = 1; 513 InputFilePtr != InputFileEnd || AnnotationItr != AnnotationEnd; 514 ++Line) { 515 const unsigned char *InputFileLine = InputFilePtr; 516 517 // Compute the previous and next line included by the filter. 518 if (NextLineInFilter < Line) 519 NextLineInFilter = FindInputLineInFilter(DumpInputFilterOnError, Line, 520 AnnotationItr, AnnotationEnd); 521 assert(NextLineInFilter && "expected NextLineInFilter to be computed"); 522 if (NextLineInFilter == Line) 523 PrevLineInFilter = Line; 524 525 // Elide this input line and its annotations if it's not within the 526 // context specified by -dump-input-context of an input line included by 527 // the dump filter. 528 if ((!PrevLineInFilter || PrevLineInFilter + DumpInputContext < Line) && 529 (NextLineInFilter == UINT_MAX || 530 Line + DumpInputContext < NextLineInFilter)) { 531 while (InputFilePtr != InputFileEnd && *InputFilePtr != '\n') 532 ++InputFilePtr; 533 if (InputFilePtr != InputFileEnd) 534 ++InputFilePtr; 535 while (AnnotationItr != AnnotationEnd && AnnotationItr->InputLine == Line) 536 ++AnnotationItr; 537 if (!PrevLineElided) { 538 for (unsigned i = 0; i < 3; ++i) { 539 WithColor(OS, raw_ostream::BLACK, /*Bold=*/true) 540 << right_justify(".", LabelWidth); 541 OS << '\n'; 542 } 543 PrevLineElided = true; 544 } 545 continue; 546 } 547 PrevLineElided = false; 548 549 // Print right-aligned line number. 550 WithColor(OS, raw_ostream::BLACK, true) 551 << format_decimal(Line, LabelWidth) << ": "; 552 553 // For the case where -v and colors are enabled, find the annotations for 554 // good matches for expected patterns in order to highlight everything 555 // else in the line. There are no such annotations if -v is disabled. 556 std::vector<InputAnnotation> FoundAndExpectedMatches; 557 if (Req.Verbose && WithColor(OS).colorsEnabled()) { 558 for (auto I = AnnotationItr; I != AnnotationEnd && I->InputLine == Line; 559 ++I) { 560 if (I->FoundAndExpectedMatch) 561 FoundAndExpectedMatches.push_back(*I); 562 } 563 } 564 565 // Print numbered line with highlighting where there are no matches for 566 // expected patterns. 567 bool Newline = false; 568 { 569 WithColor COS(OS); 570 bool InMatch = false; 571 if (Req.Verbose) 572 COS.changeColor(raw_ostream::CYAN, true, true); 573 for (unsigned Col = 1; InputFilePtr != InputFileEnd && !Newline; ++Col) { 574 bool WasInMatch = InMatch; 575 InMatch = false; 576 for (auto M : FoundAndExpectedMatches) { 577 if (M.InputStartCol <= Col && Col < M.InputEndCol) { 578 InMatch = true; 579 break; 580 } 581 } 582 if (!WasInMatch && InMatch) 583 COS.resetColor(); 584 else if (WasInMatch && !InMatch) 585 COS.changeColor(raw_ostream::CYAN, true, true); 586 if (*InputFilePtr == '\n') 587 Newline = true; 588 else 589 COS << *InputFilePtr; 590 ++InputFilePtr; 591 } 592 } 593 OS << '\n'; 594 unsigned InputLineWidth = InputFilePtr - InputFileLine - Newline; 595 596 // Print any annotations. 597 while (AnnotationItr != AnnotationEnd && 598 AnnotationItr->InputLine == Line) { 599 WithColor COS(OS, AnnotationItr->Marker.Color, true); 600 // The two spaces below are where the ": " appears on input lines. 601 COS << left_justify(AnnotationItr->Label, LabelWidth) << " "; 602 unsigned Col; 603 for (Col = 1; Col < AnnotationItr->InputStartCol; ++Col) 604 COS << ' '; 605 COS << AnnotationItr->Marker.Lead; 606 // If InputEndCol=UINT_MAX, stop at InputLineWidth. 607 for (++Col; Col < AnnotationItr->InputEndCol && Col <= InputLineWidth; 608 ++Col) 609 COS << '~'; 610 const std::string &Note = AnnotationItr->Marker.Note; 611 if (!Note.empty()) { 612 // Put the note at the end of the input line. If we were to instead 613 // put the note right after the marker, subsequent annotations for the 614 // same input line might appear to mark this note instead of the input 615 // line. 616 for (; Col <= InputLineWidth; ++Col) 617 COS << ' '; 618 COS << ' ' << Note; 619 } 620 COS << '\n'; 621 ++AnnotationItr; 622 } 623 } 624 625 OS << ">>>>>>\n"; 626 } 627 628 int main(int argc, char **argv) { 629 // Enable use of ANSI color codes because FileCheck is using them to 630 // highlight text. 631 llvm::sys::Process::UseANSIEscapeCodes(true); 632 633 InitLLVM X(argc, argv); 634 cl::ParseCommandLineOptions(argc, argv, /*Overview*/ "", /*Errs*/ nullptr, 635 "FILECHECK_OPTS"); 636 637 // Select -dump-input* values. The -help documentation specifies the default 638 // value and which value to choose if an option is specified multiple times. 639 // In the latter case, the general rule of thumb is to choose the value that 640 // provides the most information. 641 DumpInputValue DumpInput = 642 DumpInputs.empty() 643 ? DumpInputFail 644 : *std::max_element(DumpInputs.begin(), DumpInputs.end()); 645 bool DumpInputFilterOnError = DumpInput == DumpInputFail; 646 unsigned DumpInputContext = DumpInputContexts.empty() 647 ? 5 648 : *std::max_element(DumpInputContexts.begin(), 649 DumpInputContexts.end()); 650 651 if (DumpInput == DumpInputHelp) { 652 DumpInputAnnotationHelp(outs()); 653 return 0; 654 } 655 if (CheckFilename.empty()) { 656 errs() << "<check-file> not specified\n"; 657 return 2; 658 } 659 660 FileCheckRequest Req; 661 for (StringRef Prefix : CheckPrefixes) 662 Req.CheckPrefixes.push_back(Prefix); 663 664 for (StringRef Prefix : CommentPrefixes) 665 Req.CommentPrefixes.push_back(Prefix); 666 667 for (StringRef CheckNot : ImplicitCheckNot) 668 Req.ImplicitCheckNot.push_back(CheckNot); 669 670 bool GlobalDefineError = false; 671 for (StringRef G : GlobalDefines) { 672 size_t EqIdx = G.find('='); 673 if (EqIdx == std::string::npos) { 674 errs() << "Missing equal sign in command-line definition '-D" << G 675 << "'\n"; 676 GlobalDefineError = true; 677 continue; 678 } 679 if (EqIdx == 0) { 680 errs() << "Missing variable name in command-line definition '-D" << G 681 << "'\n"; 682 GlobalDefineError = true; 683 continue; 684 } 685 Req.GlobalDefines.push_back(G); 686 } 687 if (GlobalDefineError) 688 return 2; 689 690 Req.AllowEmptyInput = AllowEmptyInput; 691 Req.EnableVarScope = EnableVarScope; 692 Req.AllowDeprecatedDagOverlap = AllowDeprecatedDagOverlap; 693 Req.Verbose = Verbose; 694 Req.VerboseVerbose = VerboseVerbose; 695 Req.NoCanonicalizeWhiteSpace = NoCanonicalizeWhiteSpace; 696 Req.MatchFullLines = MatchFullLines; 697 Req.IgnoreCase = IgnoreCase; 698 699 if (VerboseVerbose) 700 Req.Verbose = true; 701 702 FileCheck FC(Req); 703 if (!FC.ValidateCheckPrefixes()) 704 return 2; 705 706 Regex PrefixRE = FC.buildCheckPrefixRegex(); 707 std::string REError; 708 if (!PrefixRE.isValid(REError)) { 709 errs() << "Unable to combine check-prefix strings into a prefix regular " 710 "expression! This is likely a bug in FileCheck's verification of " 711 "the check-prefix strings. Regular expression parsing failed " 712 "with the following error: " 713 << REError << "\n"; 714 return 2; 715 } 716 717 SourceMgr SM; 718 719 // Read the expected strings from the check file. 720 ErrorOr<std::unique_ptr<MemoryBuffer>> CheckFileOrErr = 721 MemoryBuffer::getFileOrSTDIN(CheckFilename); 722 if (std::error_code EC = CheckFileOrErr.getError()) { 723 errs() << "Could not open check file '" << CheckFilename 724 << "': " << EC.message() << '\n'; 725 return 2; 726 } 727 MemoryBuffer &CheckFile = *CheckFileOrErr.get(); 728 729 SmallString<4096> CheckFileBuffer; 730 StringRef CheckFileText = FC.CanonicalizeFile(CheckFile, CheckFileBuffer); 731 732 unsigned CheckFileBufferID = 733 SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer( 734 CheckFileText, CheckFile.getBufferIdentifier()), 735 SMLoc()); 736 737 std::pair<unsigned, unsigned> ImpPatBufferIDRange; 738 if (FC.readCheckFile(SM, CheckFileText, PrefixRE, &ImpPatBufferIDRange)) 739 return 2; 740 741 // Open the file to check and add it to SourceMgr. 742 ErrorOr<std::unique_ptr<MemoryBuffer>> InputFileOrErr = 743 MemoryBuffer::getFileOrSTDIN(InputFilename); 744 if (InputFilename == "-") 745 InputFilename = "<stdin>"; // Overwrite for improved diagnostic messages 746 if (std::error_code EC = InputFileOrErr.getError()) { 747 errs() << "Could not open input file '" << InputFilename 748 << "': " << EC.message() << '\n'; 749 return 2; 750 } 751 MemoryBuffer &InputFile = *InputFileOrErr.get(); 752 753 if (InputFile.getBufferSize() == 0 && !AllowEmptyInput) { 754 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n"; 755 DumpCommandLine(argc, argv); 756 return 2; 757 } 758 759 SmallString<4096> InputFileBuffer; 760 StringRef InputFileText = FC.CanonicalizeFile(InputFile, InputFileBuffer); 761 762 SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer( 763 InputFileText, InputFile.getBufferIdentifier()), 764 SMLoc()); 765 766 std::vector<FileCheckDiag> Diags; 767 int ExitCode = FC.checkInput(SM, InputFileText, 768 DumpInput == DumpInputNever ? nullptr : &Diags) 769 ? EXIT_SUCCESS 770 : 1; 771 if (DumpInput == DumpInputAlways || 772 (ExitCode == 1 && DumpInput == DumpInputFail)) { 773 errs() << "\n" 774 << "Input file: " << InputFilename << "\n" 775 << "Check file: " << CheckFilename << "\n" 776 << "\n" 777 << "-dump-input=help explains the following input dump.\n" 778 << "\n"; 779 std::vector<InputAnnotation> Annotations; 780 unsigned LabelWidth; 781 BuildInputAnnotations(SM, CheckFileBufferID, ImpPatBufferIDRange, Diags, 782 Annotations, LabelWidth); 783 DumpAnnotatedInput(errs(), Req, DumpInputFilterOnError, DumpInputContext, 784 InputFileText, Annotations, LabelWidth); 785 } 786 787 return ExitCode; 788 } 789