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