1 //===- FileCheck.cpp - Check that File's Contents match what is expected --===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // FileCheck does a line-by line check of a file that validates whether it 11 // contains the expected content. This is useful for regression tests etc. 12 // 13 // This program exits with an error status of 2 on error, exit status of 0 if 14 // the file matched the expected contents, and exit status of 1 if it did not 15 // contain the expected contents. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/ADT/OwningPtr.h" 20 #include "llvm/Support/CommandLine.h" 21 #include "llvm/Support/MemoryBuffer.h" 22 #include "llvm/Support/PrettyStackTrace.h" 23 #include "llvm/Support/Regex.h" 24 #include "llvm/Support/SourceMgr.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Support/Signals.h" 27 #include "llvm/Support/system_error.h" 28 #include "llvm/ADT/SmallString.h" 29 #include "llvm/ADT/StringExtras.h" 30 #include "llvm/ADT/StringMap.h" 31 #include <algorithm> 32 using namespace llvm; 33 34 static cl::opt<std::string> 35 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required); 36 37 static cl::opt<std::string> 38 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"), 39 cl::init("-"), cl::value_desc("filename")); 40 41 static cl::opt<std::string> 42 CheckPrefix("check-prefix", cl::init("CHECK"), 43 cl::desc("Prefix to use from check file (defaults to 'CHECK')")); 44 45 static cl::opt<bool> 46 NoCanonicalizeWhiteSpace("strict-whitespace", 47 cl::desc("Do not treat all horizontal whitespace as equivalent")); 48 49 //===----------------------------------------------------------------------===// 50 // Pattern Handling Code. 51 //===----------------------------------------------------------------------===// 52 53 class Pattern { 54 SMLoc PatternLoc; 55 56 /// MatchEOF - When set, this pattern only matches the end of file. This is 57 /// used for trailing CHECK-NOTs. 58 bool MatchEOF; 59 60 /// FixedStr - If non-empty, this pattern is a fixed string match with the 61 /// specified fixed string. 62 StringRef FixedStr; 63 64 /// RegEx - If non-empty, this is a regex pattern. 65 std::string RegExStr; 66 67 /// \brief Contains the number of line this pattern is in. 68 unsigned LineNumber; 69 70 /// VariableUses - Entries in this vector map to uses of a variable in the 71 /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain 72 /// "foobaz" and we'll get an entry in this vector that tells us to insert the 73 /// value of bar at offset 3. 74 std::vector<std::pair<StringRef, unsigned> > VariableUses; 75 76 /// VariableDefs - Entries in this vector map to definitions of a variable in 77 /// the pattern, e.g. "foo[[bar:.*]]baz". In this case, the RegExStr will 78 /// contain "foo(.*)baz" and VariableDefs will contain the pair "bar",1. The 79 /// index indicates what parenthesized value captures the variable value. 80 std::vector<std::pair<StringRef, unsigned> > VariableDefs; 81 82 public: 83 84 Pattern(bool matchEOF = false) : MatchEOF(matchEOF) { } 85 86 bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber); 87 88 /// Match - Match the pattern string against the input buffer Buffer. This 89 /// returns the position that is matched or npos if there is no match. If 90 /// there is a match, the size of the matched string is returned in MatchLen. 91 /// 92 /// The VariableTable StringMap provides the current values of filecheck 93 /// variables and is updated if this match defines new values. 94 size_t Match(StringRef Buffer, size_t &MatchLen, 95 StringMap<StringRef> &VariableTable) const; 96 97 /// PrintFailureInfo - Print additional information about a failure to match 98 /// involving this pattern. 99 void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, 100 const StringMap<StringRef> &VariableTable) const; 101 102 private: 103 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr); 104 bool AddRegExToRegEx(StringRef RegExStr, unsigned &CurParen, SourceMgr &SM); 105 106 /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of 107 /// matching this pattern at the start of \arg Buffer; a distance of zero 108 /// should correspond to a perfect match. 109 unsigned ComputeMatchDistance(StringRef Buffer, 110 const StringMap<StringRef> &VariableTable) const; 111 112 /// \brief Evaluates expression and stores the result to \p Value. 113 /// \return true on success. false when the expression has invalid syntax. 114 bool EvaluateExpression(StringRef Expr, std::string &Value) const; 115 }; 116 117 118 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM, 119 unsigned LineNumber) { 120 this->LineNumber = LineNumber; 121 PatternLoc = SMLoc::getFromPointer(PatternStr.data()); 122 123 // Ignore trailing whitespace. 124 while (!PatternStr.empty() && 125 (PatternStr.back() == ' ' || PatternStr.back() == '\t')) 126 PatternStr = PatternStr.substr(0, PatternStr.size()-1); 127 128 // Check that there is something on the line. 129 if (PatternStr.empty()) { 130 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error, 131 "found empty check string with prefix '" + 132 CheckPrefix+":'"); 133 return true; 134 } 135 136 // Check to see if this is a fixed string, or if it has regex pieces. 137 if (PatternStr.size() < 2 || 138 (PatternStr.find("{{") == StringRef::npos && 139 PatternStr.find("[[") == StringRef::npos)) { 140 FixedStr = PatternStr; 141 return false; 142 } 143 144 // Paren value #0 is for the fully matched string. Any new parenthesized 145 // values add from there. 146 unsigned CurParen = 1; 147 148 // Otherwise, there is at least one regex piece. Build up the regex pattern 149 // by escaping scary characters in fixed strings, building up one big regex. 150 while (!PatternStr.empty()) { 151 // RegEx matches. 152 if (PatternStr.startswith("{{")) { 153 154 // Otherwise, this is the start of a regex match. Scan for the }}. 155 size_t End = PatternStr.find("}}"); 156 if (End == StringRef::npos) { 157 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()), 158 SourceMgr::DK_Error, 159 "found start of regex string with no end '}}'"); 160 return true; 161 } 162 163 // Enclose {{}} patterns in parens just like [[]] even though we're not 164 // capturing the result for any purpose. This is required in case the 165 // expression contains an alternation like: CHECK: abc{{x|z}}def. We 166 // want this to turn into: "abc(x|z)def" not "abcx|zdef". 167 RegExStr += '('; 168 ++CurParen; 169 170 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM)) 171 return true; 172 RegExStr += ')'; 173 174 PatternStr = PatternStr.substr(End+2); 175 continue; 176 } 177 178 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .* 179 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The 180 // second form is [[foo]] which is a reference to foo. The variable name 181 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject 182 // it. This is to catch some common errors. 183 if (PatternStr.startswith("[[")) { 184 // Verify that it is terminated properly. 185 size_t End = PatternStr.find("]]"); 186 if (End == StringRef::npos) { 187 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()), 188 SourceMgr::DK_Error, 189 "invalid named regex reference, no ]] found"); 190 return true; 191 } 192 193 StringRef MatchStr = PatternStr.substr(2, End-2); 194 PatternStr = PatternStr.substr(End+2); 195 196 // Get the regex name (e.g. "foo"). 197 size_t NameEnd = MatchStr.find(':'); 198 StringRef Name = MatchStr.substr(0, NameEnd); 199 200 if (Name.empty()) { 201 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, 202 "invalid name in named regex: empty name"); 203 return true; 204 } 205 206 // Verify that the name/expression is well formed. FileCheck currently 207 // supports @LINE, @LINE+number, @LINE-number expressions. The check here 208 // is relaxed, more strict check is performed in \c EvaluateExpression. 209 bool IsExpression = false; 210 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 211 if (i == 0 && Name[i] == '@') { 212 if (NameEnd != StringRef::npos) { 213 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), 214 SourceMgr::DK_Error, 215 "invalid name in named regex definition"); 216 return true; 217 } 218 IsExpression = true; 219 continue; 220 } 221 if (Name[i] != '_' && !isalnum(Name[i]) && 222 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) { 223 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i), 224 SourceMgr::DK_Error, "invalid name in named regex"); 225 return true; 226 } 227 } 228 229 // Name can't start with a digit. 230 if (isdigit(Name[0])) { 231 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, 232 "invalid name in named regex"); 233 return true; 234 } 235 236 // Handle [[foo]]. 237 if (NameEnd == StringRef::npos) { 238 VariableUses.push_back(std::make_pair(Name, RegExStr.size())); 239 continue; 240 } 241 242 // Handle [[foo:.*]]. 243 VariableDefs.push_back(std::make_pair(Name, CurParen)); 244 RegExStr += '('; 245 ++CurParen; 246 247 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM)) 248 return true; 249 250 RegExStr += ')'; 251 } 252 253 // Handle fixed string matches. 254 // Find the end, which is the start of the next regex. 255 size_t FixedMatchEnd = PatternStr.find("{{"); 256 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[[")); 257 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr); 258 PatternStr = PatternStr.substr(FixedMatchEnd); 259 continue; 260 } 261 262 return false; 263 } 264 265 void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) { 266 // Add the characters from FixedStr to the regex, escaping as needed. This 267 // avoids "leaning toothpicks" in common patterns. 268 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) { 269 switch (FixedStr[i]) { 270 // These are the special characters matched in "p_ere_exp". 271 case '(': 272 case ')': 273 case '^': 274 case '$': 275 case '|': 276 case '*': 277 case '+': 278 case '?': 279 case '.': 280 case '[': 281 case '\\': 282 case '{': 283 TheStr += '\\'; 284 // FALL THROUGH. 285 default: 286 TheStr += FixedStr[i]; 287 break; 288 } 289 } 290 } 291 292 bool Pattern::AddRegExToRegEx(StringRef RegexStr, unsigned &CurParen, 293 SourceMgr &SM) { 294 Regex R(RegexStr); 295 std::string Error; 296 if (!R.isValid(Error)) { 297 SM.PrintMessage(SMLoc::getFromPointer(RegexStr.data()), SourceMgr::DK_Error, 298 "invalid regex: " + Error); 299 return true; 300 } 301 302 RegExStr += RegexStr.str(); 303 CurParen += R.getNumMatches(); 304 return false; 305 } 306 307 bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const { 308 // The only supported expression is @LINE([\+-]\d+)? 309 if (!Expr.startswith("@LINE")) 310 return false; 311 Expr = Expr.substr(StringRef("@LINE").size()); 312 int Offset = 0; 313 if (!Expr.empty()) { 314 if (Expr[0] == '+') 315 Expr = Expr.substr(1); 316 else if (Expr[0] != '-') 317 return false; 318 if (Expr.getAsInteger(10, Offset)) 319 return false; 320 } 321 Value = llvm::itostr(LineNumber + Offset); 322 return true; 323 } 324 325 /// Match - Match the pattern string against the input buffer Buffer. This 326 /// returns the position that is matched or npos if there is no match. If 327 /// there is a match, the size of the matched string is returned in MatchLen. 328 size_t Pattern::Match(StringRef Buffer, size_t &MatchLen, 329 StringMap<StringRef> &VariableTable) const { 330 // If this is the EOF pattern, match it immediately. 331 if (MatchEOF) { 332 MatchLen = 0; 333 return Buffer.size(); 334 } 335 336 // If this is a fixed string pattern, just match it now. 337 if (!FixedStr.empty()) { 338 MatchLen = FixedStr.size(); 339 return Buffer.find(FixedStr); 340 } 341 342 // Regex match. 343 344 // If there are variable uses, we need to create a temporary string with the 345 // actual value. 346 StringRef RegExToMatch = RegExStr; 347 std::string TmpStr; 348 if (!VariableUses.empty()) { 349 TmpStr = RegExStr; 350 351 unsigned InsertOffset = 0; 352 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) { 353 std::string Value; 354 355 if (VariableUses[i].first[0] == '@') { 356 if (!EvaluateExpression(VariableUses[i].first, Value)) 357 return StringRef::npos; 358 } else { 359 StringMap<StringRef>::iterator it = 360 VariableTable.find(VariableUses[i].first); 361 // If the variable is undefined, return an error. 362 if (it == VariableTable.end()) 363 return StringRef::npos; 364 365 // Look up the value and escape it so that we can plop it into the regex. 366 AddFixedStringToRegEx(it->second, Value); 367 } 368 369 // Plop it into the regex at the adjusted offset. 370 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset, 371 Value.begin(), Value.end()); 372 InsertOffset += Value.size(); 373 } 374 375 // Match the newly constructed regex. 376 RegExToMatch = TmpStr; 377 } 378 379 380 SmallVector<StringRef, 4> MatchInfo; 381 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo)) 382 return StringRef::npos; 383 384 // Successful regex match. 385 assert(!MatchInfo.empty() && "Didn't get any match"); 386 StringRef FullMatch = MatchInfo[0]; 387 388 // If this defines any variables, remember their values. 389 for (unsigned i = 0, e = VariableDefs.size(); i != e; ++i) { 390 assert(VariableDefs[i].second < MatchInfo.size() && 391 "Internal paren error"); 392 VariableTable[VariableDefs[i].first] = MatchInfo[VariableDefs[i].second]; 393 } 394 395 MatchLen = FullMatch.size(); 396 return FullMatch.data()-Buffer.data(); 397 } 398 399 unsigned Pattern::ComputeMatchDistance(StringRef Buffer, 400 const StringMap<StringRef> &VariableTable) const { 401 // Just compute the number of matching characters. For regular expressions, we 402 // just compare against the regex itself and hope for the best. 403 // 404 // FIXME: One easy improvement here is have the regex lib generate a single 405 // example regular expression which matches, and use that as the example 406 // string. 407 StringRef ExampleString(FixedStr); 408 if (ExampleString.empty()) 409 ExampleString = RegExStr; 410 411 // Only compare up to the first line in the buffer, or the string size. 412 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size()); 413 BufferPrefix = BufferPrefix.split('\n').first; 414 return BufferPrefix.edit_distance(ExampleString); 415 } 416 417 void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, 418 const StringMap<StringRef> &VariableTable) const{ 419 // If this was a regular expression using variables, print the current 420 // variable values. 421 if (!VariableUses.empty()) { 422 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) { 423 SmallString<256> Msg; 424 raw_svector_ostream OS(Msg); 425 StringRef Var = VariableUses[i].first; 426 if (Var[0] == '@') { 427 std::string Value; 428 if (EvaluateExpression(Var, Value)) { 429 OS << "with expression \""; 430 OS.write_escaped(Var) << "\" equal to \""; 431 OS.write_escaped(Value) << "\""; 432 } else { 433 OS << "uses incorrect expression \""; 434 OS.write_escaped(Var) << "\""; 435 } 436 } else { 437 StringMap<StringRef>::const_iterator it = VariableTable.find(Var); 438 439 // Check for undefined variable references. 440 if (it == VariableTable.end()) { 441 OS << "uses undefined variable \""; 442 OS.write_escaped(Var) << "\""; 443 } else { 444 OS << "with variable \""; 445 OS.write_escaped(Var) << "\" equal to \""; 446 OS.write_escaped(it->second) << "\""; 447 } 448 } 449 450 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, 451 OS.str()); 452 } 453 } 454 455 // Attempt to find the closest/best fuzzy match. Usually an error happens 456 // because some string in the output didn't exactly match. In these cases, we 457 // would like to show the user a best guess at what "should have" matched, to 458 // save them having to actually check the input manually. 459 size_t NumLinesForward = 0; 460 size_t Best = StringRef::npos; 461 double BestQuality = 0; 462 463 // Use an arbitrary 4k limit on how far we will search. 464 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) { 465 if (Buffer[i] == '\n') 466 ++NumLinesForward; 467 468 // Patterns have leading whitespace stripped, so skip whitespace when 469 // looking for something which looks like a pattern. 470 if (Buffer[i] == ' ' || Buffer[i] == '\t') 471 continue; 472 473 // Compute the "quality" of this match as an arbitrary combination of the 474 // match distance and the number of lines skipped to get to this match. 475 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable); 476 double Quality = Distance + (NumLinesForward / 100.); 477 478 if (Quality < BestQuality || Best == StringRef::npos) { 479 Best = i; 480 BestQuality = Quality; 481 } 482 } 483 484 // Print the "possible intended match here" line if we found something 485 // reasonable and not equal to what we showed in the "scanning from here" 486 // line. 487 if (Best && Best != StringRef::npos && BestQuality < 50) { 488 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best), 489 SourceMgr::DK_Note, "possible intended match here"); 490 491 // FIXME: If we wanted to be really friendly we would show why the match 492 // failed, as it can be hard to spot simple one character differences. 493 } 494 } 495 496 //===----------------------------------------------------------------------===// 497 // Check Strings. 498 //===----------------------------------------------------------------------===// 499 500 /// CheckString - This is a check that we found in the input file. 501 struct CheckString { 502 /// Pat - The pattern to match. 503 Pattern Pat; 504 505 /// Loc - The location in the match file that the check string was specified. 506 SMLoc Loc; 507 508 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed 509 /// to a CHECK: directive. 510 bool IsCheckNext; 511 512 /// NotStrings - These are all of the strings that are disallowed from 513 /// occurring between this match string and the previous one (or start of 514 /// file). 515 std::vector<std::pair<SMLoc, Pattern> > NotStrings; 516 517 CheckString(const Pattern &P, SMLoc L, bool isCheckNext) 518 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {} 519 }; 520 521 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified 522 /// memory buffer, free it, and return a new one. 523 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) { 524 SmallString<128> NewFile; 525 NewFile.reserve(MB->getBufferSize()); 526 527 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd(); 528 Ptr != End; ++Ptr) { 529 // Eliminate trailing dosish \r. 530 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') { 531 continue; 532 } 533 534 // If current char is not a horizontal whitespace, dump it to output as is. 535 if (*Ptr != ' ' && *Ptr != '\t') { 536 NewFile.push_back(*Ptr); 537 continue; 538 } 539 540 // Otherwise, add one space and advance over neighboring space. 541 NewFile.push_back(' '); 542 while (Ptr+1 != End && 543 (Ptr[1] == ' ' || Ptr[1] == '\t')) 544 ++Ptr; 545 } 546 547 // Free the old buffer and return a new one. 548 MemoryBuffer *MB2 = 549 MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier()); 550 551 delete MB; 552 return MB2; 553 } 554 555 556 /// ReadCheckFile - Read the check file, which specifies the sequence of 557 /// expected strings. The strings are added to the CheckStrings vector. 558 static bool ReadCheckFile(SourceMgr &SM, 559 std::vector<CheckString> &CheckStrings) { 560 // Open the check file, and tell SourceMgr about it. 561 OwningPtr<MemoryBuffer> File; 562 if (error_code ec = 563 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) { 564 errs() << "Could not open check file '" << CheckFilename << "': " 565 << ec.message() << '\n'; 566 return true; 567 } 568 MemoryBuffer *F = File.take(); 569 570 // If we want to canonicalize whitespace, strip excess whitespace from the 571 // buffer containing the CHECK lines. 572 if (!NoCanonicalizeWhiteSpace) 573 F = CanonicalizeInputFile(F); 574 575 SM.AddNewSourceBuffer(F, SMLoc()); 576 577 // Find all instances of CheckPrefix followed by : in the file. 578 StringRef Buffer = F->getBuffer(); 579 580 std::vector<std::pair<SMLoc, Pattern> > NotMatches; 581 582 unsigned LineNumber = 1; 583 584 while (1) { 585 // See if Prefix occurs in the memory buffer. 586 size_t PrefixLoc = Buffer.find(CheckPrefix); 587 // If we didn't find a match, we're done. 588 if (PrefixLoc == StringRef::npos) 589 break; 590 591 // Recalculate line number. 592 LineNumber += Buffer.substr(0, PrefixLoc).count('\n'); 593 594 Buffer = Buffer.substr(PrefixLoc); 595 596 const char *CheckPrefixStart = Buffer.data(); 597 598 // When we find a check prefix, keep track of whether we find CHECK: or 599 // CHECK-NEXT: 600 bool IsCheckNext = false, IsCheckNot = false; 601 602 // Verify that the : is present after the prefix. 603 if (Buffer[CheckPrefix.size()] == ':') { 604 Buffer = Buffer.substr(CheckPrefix.size()+1); 605 } else if (Buffer.size() > CheckPrefix.size()+6 && 606 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) { 607 Buffer = Buffer.substr(CheckPrefix.size()+6); 608 IsCheckNext = true; 609 } else if (Buffer.size() > CheckPrefix.size()+5 && 610 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) { 611 Buffer = Buffer.substr(CheckPrefix.size()+5); 612 IsCheckNot = true; 613 } else { 614 Buffer = Buffer.substr(1); 615 continue; 616 } 617 618 // Okay, we found the prefix, yay. Remember the rest of the line, but 619 // ignore leading and trailing whitespace. 620 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t")); 621 622 // Scan ahead to the end of line. 623 size_t EOL = Buffer.find_first_of("\n\r"); 624 625 // Remember the location of the start of the pattern, for diagnostics. 626 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data()); 627 628 // Parse the pattern. 629 Pattern P; 630 if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber)) 631 return true; 632 633 Buffer = Buffer.substr(EOL); 634 635 636 // Verify that CHECK-NEXT lines have at least one CHECK line before them. 637 if (IsCheckNext && CheckStrings.empty()) { 638 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart), 639 SourceMgr::DK_Error, 640 "found '"+CheckPrefix+"-NEXT:' without previous '"+ 641 CheckPrefix+ ": line"); 642 return true; 643 } 644 645 // Handle CHECK-NOT. 646 if (IsCheckNot) { 647 NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()), 648 P)); 649 continue; 650 } 651 652 653 // Okay, add the string we captured to the output vector and move on. 654 CheckStrings.push_back(CheckString(P, 655 PatternLoc, 656 IsCheckNext)); 657 std::swap(NotMatches, CheckStrings.back().NotStrings); 658 } 659 660 // Add an EOF pattern for any trailing CHECK-NOTs. 661 if (!NotMatches.empty()) { 662 CheckStrings.push_back(CheckString(Pattern(true), 663 SMLoc::getFromPointer(Buffer.data()), 664 false)); 665 std::swap(NotMatches, CheckStrings.back().NotStrings); 666 } 667 668 if (CheckStrings.empty()) { 669 errs() << "error: no check strings found with prefix '" << CheckPrefix 670 << ":'\n"; 671 return true; 672 } 673 674 return false; 675 } 676 677 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr, 678 StringRef Buffer, 679 StringMap<StringRef> &VariableTable) { 680 // Otherwise, we have an error, emit an error message. 681 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, 682 "expected string not found in input"); 683 684 // Print the "scanning from here" line. If the current position is at the 685 // end of a line, advance to the start of the next line. 686 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r")); 687 688 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, 689 "scanning from here"); 690 691 // Allow the pattern to print additional information if desired. 692 CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable); 693 } 694 695 /// CountNumNewlinesBetween - Count the number of newlines in the specified 696 /// range. 697 static unsigned CountNumNewlinesBetween(StringRef Range) { 698 unsigned NumNewLines = 0; 699 while (1) { 700 // Scan for newline. 701 Range = Range.substr(Range.find_first_of("\n\r")); 702 if (Range.empty()) return NumNewLines; 703 704 ++NumNewLines; 705 706 // Handle \n\r and \r\n as a single newline. 707 if (Range.size() > 1 && 708 (Range[1] == '\n' || Range[1] == '\r') && 709 (Range[0] != Range[1])) 710 Range = Range.substr(1); 711 Range = Range.substr(1); 712 } 713 } 714 715 int main(int argc, char **argv) { 716 sys::PrintStackTraceOnErrorSignal(); 717 PrettyStackTraceProgram X(argc, argv); 718 cl::ParseCommandLineOptions(argc, argv); 719 720 SourceMgr SM; 721 722 // Read the expected strings from the check file. 723 std::vector<CheckString> CheckStrings; 724 if (ReadCheckFile(SM, CheckStrings)) 725 return 2; 726 727 // Open the file to check and add it to SourceMgr. 728 OwningPtr<MemoryBuffer> File; 729 if (error_code ec = 730 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) { 731 errs() << "Could not open input file '" << InputFilename << "': " 732 << ec.message() << '\n'; 733 return true; 734 } 735 MemoryBuffer *F = File.take(); 736 737 if (F->getBufferSize() == 0) { 738 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n"; 739 return 1; 740 } 741 742 // Remove duplicate spaces in the input file if requested. 743 if (!NoCanonicalizeWhiteSpace) 744 F = CanonicalizeInputFile(F); 745 746 SM.AddNewSourceBuffer(F, SMLoc()); 747 748 /// VariableTable - This holds all the current filecheck variables. 749 StringMap<StringRef> VariableTable; 750 751 // Check that we have all of the expected strings, in order, in the input 752 // file. 753 StringRef Buffer = F->getBuffer(); 754 755 const char *LastMatch = Buffer.data(); 756 757 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) { 758 const CheckString &CheckStr = CheckStrings[StrNo]; 759 760 StringRef SearchFrom = Buffer; 761 762 // Find StrNo in the file. 763 size_t MatchLen = 0; 764 size_t MatchPos = CheckStr.Pat.Match(Buffer, MatchLen, VariableTable); 765 Buffer = Buffer.substr(MatchPos); 766 767 // If we didn't find a match, reject the input. 768 if (MatchPos == StringRef::npos) { 769 PrintCheckFailed(SM, CheckStr, SearchFrom, VariableTable); 770 return 1; 771 } 772 773 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch); 774 775 // If this check is a "CHECK-NEXT", verify that the previous match was on 776 // the previous line (i.e. that there is one newline between them). 777 if (CheckStr.IsCheckNext) { 778 // Count the number of newlines between the previous match and this one. 779 assert(LastMatch != F->getBufferStart() && 780 "CHECK-NEXT can't be the first check in a file"); 781 782 unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion); 783 if (NumNewLines == 0) { 784 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, 785 CheckPrefix+"-NEXT: is on the same line as previous match"); 786 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), 787 SourceMgr::DK_Note, "'next' match was here"); 788 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note, 789 "previous match was here"); 790 return 1; 791 } 792 793 if (NumNewLines != 1) { 794 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+ 795 "-NEXT: is not on the line after the previous match"); 796 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), 797 SourceMgr::DK_Note, "'next' match was here"); 798 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note, 799 "previous match was here"); 800 return 1; 801 } 802 } 803 804 // If this match had "not strings", verify that they don't exist in the 805 // skipped region. 806 for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size(); 807 ChunkNo != e; ++ChunkNo) { 808 size_t MatchLen = 0; 809 size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion, 810 MatchLen, 811 VariableTable); 812 if (Pos == StringRef::npos) continue; 813 814 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos), SourceMgr::DK_Error, 815 CheckPrefix+"-NOT: string occurred!"); 816 SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first, SourceMgr::DK_Note, 817 CheckPrefix+"-NOT: pattern specified here"); 818 return 1; 819 } 820 821 822 // Otherwise, everything is good. Step over the matched text and remember 823 // the position after the match as the end of the last match. 824 Buffer = Buffer.substr(MatchLen); 825 LastMatch = Buffer.data(); 826 } 827 828 return 0; 829 } 830