FileCheck.cpp revision ee4f5eae1c416eddbecbb2d742e2bb8dc0032bf6
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/ADT/SmallString.h" 21#include "llvm/ADT/StringExtras.h" 22#include "llvm/ADT/StringMap.h" 23#include "llvm/ADT/StringSet.h" 24#include "llvm/Support/CommandLine.h" 25#include "llvm/Support/MemoryBuffer.h" 26#include "llvm/Support/PrettyStackTrace.h" 27#include "llvm/Support/Regex.h" 28#include "llvm/Support/Signals.h" 29#include "llvm/Support/SourceMgr.h" 30#include "llvm/Support/raw_ostream.h" 31#include "llvm/Support/system_error.h" 32#include <algorithm> 33#include <cctype> 34#include <map> 35#include <string> 36#include <vector> 37using namespace llvm; 38 39static cl::opt<std::string> 40CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required); 41 42static cl::opt<std::string> 43InputFilename("input-file", cl::desc("File to check (defaults to stdin)"), 44 cl::init("-"), cl::value_desc("filename")); 45 46static cl::list<std::string> 47CheckPrefixes("check-prefix", 48 cl::desc("Prefix to use from check file (defaults to 'CHECK')")); 49 50static cl::opt<bool> 51NoCanonicalizeWhiteSpace("strict-whitespace", 52 cl::desc("Do not treat all horizontal whitespace as equivalent")); 53 54typedef cl::list<std::string>::const_iterator prefix_iterator; 55 56//===----------------------------------------------------------------------===// 57// Pattern Handling Code. 58//===----------------------------------------------------------------------===// 59 60namespace Check { 61 enum CheckType { 62 CheckNone = 0, 63 CheckPlain, 64 CheckNext, 65 CheckNot, 66 CheckDAG, 67 CheckLabel, 68 69 /// MatchEOF - When set, this pattern only matches the end of file. This is 70 /// used for trailing CHECK-NOTs. 71 CheckEOF 72 }; 73} 74 75class Pattern { 76 SMLoc PatternLoc; 77 78 Check::CheckType CheckTy; 79 80 /// FixedStr - If non-empty, this pattern is a fixed string match with the 81 /// specified fixed string. 82 StringRef FixedStr; 83 84 /// RegEx - If non-empty, this is a regex pattern. 85 std::string RegExStr; 86 87 /// \brief Contains the number of line this pattern is in. 88 unsigned LineNumber; 89 90 /// VariableUses - Entries in this vector map to uses of a variable in the 91 /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain 92 /// "foobaz" and we'll get an entry in this vector that tells us to insert the 93 /// value of bar at offset 3. 94 std::vector<std::pair<StringRef, unsigned> > VariableUses; 95 96 /// VariableDefs - Maps definitions of variables to their parenthesized 97 /// capture numbers. 98 /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1. 99 std::map<StringRef, unsigned> VariableDefs; 100 101public: 102 103 Pattern(Check::CheckType Ty) 104 : CheckTy(Ty) { } 105 106 /// getLoc - Return the location in source code. 107 SMLoc getLoc() const { return PatternLoc; } 108 109 /// ParsePattern - Parse the given string into the Pattern. Prefix provides 110 /// which prefix is being matched, SM provides the SourceMgr used for error 111 /// reports, and LineNumber is the line number in the input file from which 112 /// the pattern string was read. Returns true in case of an error, false 113 /// otherwise. 114 bool ParsePattern(StringRef PatternStr, 115 StringRef Prefix, 116 SourceMgr &SM, 117 unsigned LineNumber); 118 119 /// Match - Match the pattern string against the input buffer Buffer. This 120 /// returns the position that is matched or npos if there is no match. If 121 /// there is a match, the size of the matched string is returned in MatchLen. 122 /// 123 /// The VariableTable StringMap provides the current values of filecheck 124 /// variables and is updated if this match defines new values. 125 size_t Match(StringRef Buffer, size_t &MatchLen, 126 StringMap<StringRef> &VariableTable) const; 127 128 /// PrintFailureInfo - Print additional information about a failure to match 129 /// involving this pattern. 130 void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, 131 const StringMap<StringRef> &VariableTable) const; 132 133 bool hasVariable() const { return !(VariableUses.empty() && 134 VariableDefs.empty()); } 135 136 Check::CheckType getCheckTy() const { return CheckTy; } 137 138private: 139 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr); 140 bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM); 141 void AddBackrefToRegEx(unsigned BackrefNum); 142 143 /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of 144 /// matching this pattern at the start of \arg Buffer; a distance of zero 145 /// should correspond to a perfect match. 146 unsigned ComputeMatchDistance(StringRef Buffer, 147 const StringMap<StringRef> &VariableTable) const; 148 149 /// \brief Evaluates expression and stores the result to \p Value. 150 /// \return true on success. false when the expression has invalid syntax. 151 bool EvaluateExpression(StringRef Expr, std::string &Value) const; 152 153 /// \brief Finds the closing sequence of a regex variable usage or 154 /// definition. Str has to point in the beginning of the definition 155 /// (right after the opening sequence). 156 /// \return offset of the closing sequence within Str, or npos if it was not 157 /// found. 158 size_t FindRegexVarEnd(StringRef Str); 159}; 160 161 162bool Pattern::ParsePattern(StringRef PatternStr, 163 StringRef Prefix, 164 SourceMgr &SM, 165 unsigned LineNumber) { 166 this->LineNumber = LineNumber; 167 PatternLoc = SMLoc::getFromPointer(PatternStr.data()); 168 169 // Ignore trailing whitespace. 170 while (!PatternStr.empty() && 171 (PatternStr.back() == ' ' || PatternStr.back() == '\t')) 172 PatternStr = PatternStr.substr(0, PatternStr.size()-1); 173 174 // Check that there is something on the line. 175 if (PatternStr.empty()) { 176 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error, 177 "found empty check string with prefix '" + 178 Prefix + ":'"); 179 return true; 180 } 181 182 // Check to see if this is a fixed string, or if it has regex pieces. 183 if (PatternStr.size() < 2 || 184 (PatternStr.find("{{") == StringRef::npos && 185 PatternStr.find("[[") == StringRef::npos)) { 186 FixedStr = PatternStr; 187 return false; 188 } 189 190 // Paren value #0 is for the fully matched string. Any new parenthesized 191 // values add from there. 192 unsigned CurParen = 1; 193 194 // Otherwise, there is at least one regex piece. Build up the regex pattern 195 // by escaping scary characters in fixed strings, building up one big regex. 196 while (!PatternStr.empty()) { 197 // RegEx matches. 198 if (PatternStr.startswith("{{")) { 199 // This is the start of a regex match. Scan for the }}. 200 size_t End = PatternStr.find("}}"); 201 if (End == StringRef::npos) { 202 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()), 203 SourceMgr::DK_Error, 204 "found start of regex string with no end '}}'"); 205 return true; 206 } 207 208 // Enclose {{}} patterns in parens just like [[]] even though we're not 209 // capturing the result for any purpose. This is required in case the 210 // expression contains an alternation like: CHECK: abc{{x|z}}def. We 211 // want this to turn into: "abc(x|z)def" not "abcx|zdef". 212 RegExStr += '('; 213 ++CurParen; 214 215 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM)) 216 return true; 217 RegExStr += ')'; 218 219 PatternStr = PatternStr.substr(End+2); 220 continue; 221 } 222 223 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .* 224 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The 225 // second form is [[foo]] which is a reference to foo. The variable name 226 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject 227 // it. This is to catch some common errors. 228 if (PatternStr.startswith("[[")) { 229 // Find the closing bracket pair ending the match. End is going to be an 230 // offset relative to the beginning of the match string. 231 size_t End = FindRegexVarEnd(PatternStr.substr(2)); 232 233 if (End == StringRef::npos) { 234 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()), 235 SourceMgr::DK_Error, 236 "invalid named regex reference, no ]] found"); 237 return true; 238 } 239 240 StringRef MatchStr = PatternStr.substr(2, End); 241 PatternStr = PatternStr.substr(End+4); 242 243 // Get the regex name (e.g. "foo"). 244 size_t NameEnd = MatchStr.find(':'); 245 StringRef Name = MatchStr.substr(0, NameEnd); 246 247 if (Name.empty()) { 248 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, 249 "invalid name in named regex: empty name"); 250 return true; 251 } 252 253 // Verify that the name/expression is well formed. FileCheck currently 254 // supports @LINE, @LINE+number, @LINE-number expressions. The check here 255 // is relaxed, more strict check is performed in \c EvaluateExpression. 256 bool IsExpression = false; 257 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 258 if (i == 0 && Name[i] == '@') { 259 if (NameEnd != StringRef::npos) { 260 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), 261 SourceMgr::DK_Error, 262 "invalid name in named regex definition"); 263 return true; 264 } 265 IsExpression = true; 266 continue; 267 } 268 if (Name[i] != '_' && !isalnum(Name[i]) && 269 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) { 270 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i), 271 SourceMgr::DK_Error, "invalid name in named regex"); 272 return true; 273 } 274 } 275 276 // Name can't start with a digit. 277 if (isdigit(static_cast<unsigned char>(Name[0]))) { 278 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error, 279 "invalid name in named regex"); 280 return true; 281 } 282 283 // Handle [[foo]]. 284 if (NameEnd == StringRef::npos) { 285 // Handle variables that were defined earlier on the same line by 286 // emitting a backreference. 287 if (VariableDefs.find(Name) != VariableDefs.end()) { 288 unsigned VarParenNum = VariableDefs[Name]; 289 if (VarParenNum < 1 || VarParenNum > 9) { 290 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), 291 SourceMgr::DK_Error, 292 "Can't back-reference more than 9 variables"); 293 return true; 294 } 295 AddBackrefToRegEx(VarParenNum); 296 } else { 297 VariableUses.push_back(std::make_pair(Name, RegExStr.size())); 298 } 299 continue; 300 } 301 302 // Handle [[foo:.*]]. 303 VariableDefs[Name] = CurParen; 304 RegExStr += '('; 305 ++CurParen; 306 307 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM)) 308 return true; 309 310 RegExStr += ')'; 311 } 312 313 // Handle fixed string matches. 314 // Find the end, which is the start of the next regex. 315 size_t FixedMatchEnd = PatternStr.find("{{"); 316 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[[")); 317 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr); 318 PatternStr = PatternStr.substr(FixedMatchEnd); 319 } 320 321 return false; 322} 323 324void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) { 325 // Add the characters from FixedStr to the regex, escaping as needed. This 326 // avoids "leaning toothpicks" in common patterns. 327 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) { 328 switch (FixedStr[i]) { 329 // These are the special characters matched in "p_ere_exp". 330 case '(': 331 case ')': 332 case '^': 333 case '$': 334 case '|': 335 case '*': 336 case '+': 337 case '?': 338 case '.': 339 case '[': 340 case '\\': 341 case '{': 342 TheStr += '\\'; 343 // FALL THROUGH. 344 default: 345 TheStr += FixedStr[i]; 346 break; 347 } 348 } 349} 350 351bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, 352 SourceMgr &SM) { 353 Regex R(RS); 354 std::string Error; 355 if (!R.isValid(Error)) { 356 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error, 357 "invalid regex: " + Error); 358 return true; 359 } 360 361 RegExStr += RS.str(); 362 CurParen += R.getNumMatches(); 363 return false; 364} 365 366void Pattern::AddBackrefToRegEx(unsigned BackrefNum) { 367 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number"); 368 std::string Backref = std::string("\\") + 369 std::string(1, '0' + BackrefNum); 370 RegExStr += Backref; 371} 372 373bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const { 374 // The only supported expression is @LINE([\+-]\d+)? 375 if (!Expr.startswith("@LINE")) 376 return false; 377 Expr = Expr.substr(StringRef("@LINE").size()); 378 int Offset = 0; 379 if (!Expr.empty()) { 380 if (Expr[0] == '+') 381 Expr = Expr.substr(1); 382 else if (Expr[0] != '-') 383 return false; 384 if (Expr.getAsInteger(10, Offset)) 385 return false; 386 } 387 Value = llvm::itostr(LineNumber + Offset); 388 return true; 389} 390 391/// Match - Match the pattern string against the input buffer Buffer. This 392/// returns the position that is matched or npos if there is no match. If 393/// there is a match, the size of the matched string is returned in MatchLen. 394size_t Pattern::Match(StringRef Buffer, size_t &MatchLen, 395 StringMap<StringRef> &VariableTable) const { 396 // If this is the EOF pattern, match it immediately. 397 if (CheckTy == Check::CheckEOF) { 398 MatchLen = 0; 399 return Buffer.size(); 400 } 401 402 // If this is a fixed string pattern, just match it now. 403 if (!FixedStr.empty()) { 404 MatchLen = FixedStr.size(); 405 return Buffer.find(FixedStr); 406 } 407 408 // Regex match. 409 410 // If there are variable uses, we need to create a temporary string with the 411 // actual value. 412 StringRef RegExToMatch = RegExStr; 413 std::string TmpStr; 414 if (!VariableUses.empty()) { 415 TmpStr = RegExStr; 416 417 unsigned InsertOffset = 0; 418 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) { 419 std::string Value; 420 421 if (VariableUses[i].first[0] == '@') { 422 if (!EvaluateExpression(VariableUses[i].first, Value)) 423 return StringRef::npos; 424 } else { 425 StringMap<StringRef>::iterator it = 426 VariableTable.find(VariableUses[i].first); 427 // If the variable is undefined, return an error. 428 if (it == VariableTable.end()) 429 return StringRef::npos; 430 431 // Look up the value and escape it so that we can plop it into the regex. 432 AddFixedStringToRegEx(it->second, Value); 433 } 434 435 // Plop it into the regex at the adjusted offset. 436 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset, 437 Value.begin(), Value.end()); 438 InsertOffset += Value.size(); 439 } 440 441 // Match the newly constructed regex. 442 RegExToMatch = TmpStr; 443 } 444 445 446 SmallVector<StringRef, 4> MatchInfo; 447 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo)) 448 return StringRef::npos; 449 450 // Successful regex match. 451 assert(!MatchInfo.empty() && "Didn't get any match"); 452 StringRef FullMatch = MatchInfo[0]; 453 454 // If this defines any variables, remember their values. 455 for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(), 456 E = VariableDefs.end(); 457 I != E; ++I) { 458 assert(I->second < MatchInfo.size() && "Internal paren error"); 459 VariableTable[I->first] = MatchInfo[I->second]; 460 } 461 462 MatchLen = FullMatch.size(); 463 return FullMatch.data()-Buffer.data(); 464} 465 466unsigned Pattern::ComputeMatchDistance(StringRef Buffer, 467 const StringMap<StringRef> &VariableTable) const { 468 // Just compute the number of matching characters. For regular expressions, we 469 // just compare against the regex itself and hope for the best. 470 // 471 // FIXME: One easy improvement here is have the regex lib generate a single 472 // example regular expression which matches, and use that as the example 473 // string. 474 StringRef ExampleString(FixedStr); 475 if (ExampleString.empty()) 476 ExampleString = RegExStr; 477 478 // Only compare up to the first line in the buffer, or the string size. 479 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size()); 480 BufferPrefix = BufferPrefix.split('\n').first; 481 return BufferPrefix.edit_distance(ExampleString); 482} 483 484void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer, 485 const StringMap<StringRef> &VariableTable) const{ 486 // If this was a regular expression using variables, print the current 487 // variable values. 488 if (!VariableUses.empty()) { 489 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) { 490 SmallString<256> Msg; 491 raw_svector_ostream OS(Msg); 492 StringRef Var = VariableUses[i].first; 493 if (Var[0] == '@') { 494 std::string Value; 495 if (EvaluateExpression(Var, Value)) { 496 OS << "with expression \""; 497 OS.write_escaped(Var) << "\" equal to \""; 498 OS.write_escaped(Value) << "\""; 499 } else { 500 OS << "uses incorrect expression \""; 501 OS.write_escaped(Var) << "\""; 502 } 503 } else { 504 StringMap<StringRef>::const_iterator it = VariableTable.find(Var); 505 506 // Check for undefined variable references. 507 if (it == VariableTable.end()) { 508 OS << "uses undefined variable \""; 509 OS.write_escaped(Var) << "\""; 510 } else { 511 OS << "with variable \""; 512 OS.write_escaped(Var) << "\" equal to \""; 513 OS.write_escaped(it->second) << "\""; 514 } 515 } 516 517 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, 518 OS.str()); 519 } 520 } 521 522 // Attempt to find the closest/best fuzzy match. Usually an error happens 523 // because some string in the output didn't exactly match. In these cases, we 524 // would like to show the user a best guess at what "should have" matched, to 525 // save them having to actually check the input manually. 526 size_t NumLinesForward = 0; 527 size_t Best = StringRef::npos; 528 double BestQuality = 0; 529 530 // Use an arbitrary 4k limit on how far we will search. 531 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) { 532 if (Buffer[i] == '\n') 533 ++NumLinesForward; 534 535 // Patterns have leading whitespace stripped, so skip whitespace when 536 // looking for something which looks like a pattern. 537 if (Buffer[i] == ' ' || Buffer[i] == '\t') 538 continue; 539 540 // Compute the "quality" of this match as an arbitrary combination of the 541 // match distance and the number of lines skipped to get to this match. 542 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable); 543 double Quality = Distance + (NumLinesForward / 100.); 544 545 if (Quality < BestQuality || Best == StringRef::npos) { 546 Best = i; 547 BestQuality = Quality; 548 } 549 } 550 551 // Print the "possible intended match here" line if we found something 552 // reasonable and not equal to what we showed in the "scanning from here" 553 // line. 554 if (Best && Best != StringRef::npos && BestQuality < 50) { 555 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best), 556 SourceMgr::DK_Note, "possible intended match here"); 557 558 // FIXME: If we wanted to be really friendly we would show why the match 559 // failed, as it can be hard to spot simple one character differences. 560 } 561} 562 563size_t Pattern::FindRegexVarEnd(StringRef Str) { 564 // Offset keeps track of the current offset within the input Str 565 size_t Offset = 0; 566 // [...] Nesting depth 567 size_t BracketDepth = 0; 568 569 while (!Str.empty()) { 570 if (Str.startswith("]]") && BracketDepth == 0) 571 return Offset; 572 if (Str[0] == '\\') { 573 // Backslash escapes the next char within regexes, so skip them both. 574 Str = Str.substr(2); 575 Offset += 2; 576 } else { 577 switch (Str[0]) { 578 default: 579 break; 580 case '[': 581 BracketDepth++; 582 break; 583 case ']': 584 assert(BracketDepth > 0 && "Invalid regex"); 585 BracketDepth--; 586 break; 587 } 588 Str = Str.substr(1); 589 Offset++; 590 } 591 } 592 593 return StringRef::npos; 594} 595 596 597//===----------------------------------------------------------------------===// 598// Check Strings. 599//===----------------------------------------------------------------------===// 600 601/// CheckString - This is a check that we found in the input file. 602struct CheckString { 603 /// Pat - The pattern to match. 604 Pattern Pat; 605 606 /// Prefix - Which prefix name this check matched. 607 StringRef Prefix; 608 609 /// Loc - The location in the match file that the check string was specified. 610 SMLoc Loc; 611 612 /// CheckTy - Specify what kind of check this is. e.g. CHECK-NEXT: directive, 613 /// as opposed to a CHECK: directive. 614 Check::CheckType CheckTy; 615 616 /// DagNotStrings - These are all of the strings that are disallowed from 617 /// occurring between this match string and the previous one (or start of 618 /// file). 619 std::vector<Pattern> DagNotStrings; 620 621 622 CheckString(const Pattern &P, 623 StringRef S, 624 SMLoc L, 625 Check::CheckType Ty) 626 : Pat(P), Prefix(S), Loc(L), CheckTy(Ty) {} 627 628 /// Check - Match check string and its "not strings" and/or "dag strings". 629 size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode, 630 size_t &MatchLen, StringMap<StringRef> &VariableTable) const; 631 632 /// CheckNext - Verify there is a single line in the given buffer. 633 bool CheckNext(const SourceMgr &SM, StringRef Buffer) const; 634 635 /// CheckNot - Verify there's no "not strings" in the given buffer. 636 bool CheckNot(const SourceMgr &SM, StringRef Buffer, 637 const std::vector<const Pattern *> &NotStrings, 638 StringMap<StringRef> &VariableTable) const; 639 640 /// CheckDag - Match "dag strings" and their mixed "not strings". 641 size_t CheckDag(const SourceMgr &SM, StringRef Buffer, 642 std::vector<const Pattern *> &NotStrings, 643 StringMap<StringRef> &VariableTable) const; 644}; 645 646/// Canonicalize whitespaces in the input file. Line endings are replaced 647/// with UNIX-style '\n'. 648/// 649/// \param PreserveHorizontal Don't squash consecutive horizontal whitespace 650/// characters to a single space. 651static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB, 652 bool PreserveHorizontal) { 653 SmallString<128> NewFile; 654 NewFile.reserve(MB->getBufferSize()); 655 656 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd(); 657 Ptr != End; ++Ptr) { 658 // Eliminate trailing dosish \r. 659 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') { 660 continue; 661 } 662 663 // If current char is not a horizontal whitespace or if horizontal 664 // whitespace canonicalization is disabled, dump it to output as is. 665 if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) { 666 NewFile.push_back(*Ptr); 667 continue; 668 } 669 670 // Otherwise, add one space and advance over neighboring space. 671 NewFile.push_back(' '); 672 while (Ptr+1 != End && 673 (Ptr[1] == ' ' || Ptr[1] == '\t')) 674 ++Ptr; 675 } 676 677 // Free the old buffer and return a new one. 678 MemoryBuffer *MB2 = 679 MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier()); 680 681 delete MB; 682 return MB2; 683} 684 685static bool IsPartOfWord(char c) { 686 return (isalnum(c) || c == '-' || c == '_'); 687} 688 689// Get the size of the prefix extension. 690static size_t CheckTypeSize(Check::CheckType Ty) { 691 switch (Ty) { 692 case Check::CheckNone: 693 return 0; 694 695 case Check::CheckPlain: 696 return sizeof(":") - 1; 697 698 case Check::CheckNext: 699 return sizeof("-NEXT:") - 1; 700 701 case Check::CheckNot: 702 return sizeof("-NOT:") - 1; 703 704 case Check::CheckDAG: 705 return sizeof("-DAG:") - 1; 706 707 case Check::CheckLabel: 708 return sizeof("-LABEL:") - 1; 709 710 case Check::CheckEOF: 711 llvm_unreachable("Should not be using EOF size"); 712 } 713 714 llvm_unreachable("Bad check type"); 715} 716 717static Check::CheckType FindCheckType(StringRef Buffer, StringRef Prefix) { 718 char NextChar = Buffer[Prefix.size()]; 719 720 // Verify that the : is present after the prefix. 721 if (NextChar == ':') 722 return Check::CheckPlain; 723 724 if (NextChar != '-') 725 return Check::CheckNone; 726 727 StringRef Rest = Buffer.drop_front(Prefix.size() + 1); 728 if (Rest.startswith("NEXT:")) 729 return Check::CheckNext; 730 731 if (Rest.startswith("NOT:")) 732 return Check::CheckNot; 733 734 if (Rest.startswith("DAG:")) 735 return Check::CheckDAG; 736 737 if (Rest.startswith("LABEL:")) 738 return Check::CheckLabel; 739 740 return Check::CheckNone; 741} 742 743// From the given position, find the next character after the word. 744static size_t SkipWord(StringRef Str, size_t Loc) { 745 while (Loc < Str.size() && IsPartOfWord(Str[Loc])) 746 ++Loc; 747 return Loc; 748} 749 750// Try to find the first match in buffer for any prefix. If a valid match is 751// found, return that prefix and set its type and location. If there are almost 752// matches (e.g. the actual prefix string is found, but is not an actual check 753// string), but no valid match, return an empty string and set the position to 754// resume searching from. If no partial matches are found, return an empty 755// string and the location will be StringRef::npos. If one prefix is a substring 756// of another, the maximal match should be found. e.g. if "A" and "AA" are 757// prefixes then AA-CHECK: should match the second one. 758static StringRef FindFirstCandidateMatch(StringRef &Buffer, 759 Check::CheckType &CheckTy, 760 size_t &CheckLoc) { 761 StringRef FirstPrefix; 762 size_t FirstLoc = StringRef::npos; 763 size_t SearchLoc = StringRef::npos; 764 Check::CheckType FirstTy = Check::CheckNone; 765 766 CheckTy = Check::CheckNone; 767 CheckLoc = StringRef::npos; 768 769 for (prefix_iterator I = CheckPrefixes.begin(), E = CheckPrefixes.end(); 770 I != E; ++I) { 771 StringRef Prefix(*I); 772 size_t PrefixLoc = Buffer.find(Prefix); 773 774 if (PrefixLoc == StringRef::npos) 775 continue; 776 777 // Track where we are searching for invalid prefixes that look almost right. 778 // We need to only advance to the first partial match on the next attempt 779 // since a partial match could be a substring of a later, valid prefix. 780 // Need to skip to the end of the word, otherwise we could end up 781 // matching a prefix in a substring later. 782 if (PrefixLoc < SearchLoc) 783 SearchLoc = SkipWord(Buffer, PrefixLoc); 784 785 // We only want to find the first match to avoid skipping some. 786 if (PrefixLoc > FirstLoc) 787 continue; 788 789 StringRef Rest = Buffer.drop_front(PrefixLoc); 790 // Make sure we have actually found the prefix, and not a word containing 791 // it. This should also prevent matching the wrong prefix when one is a 792 // substring of another. 793 if (PrefixLoc != 0 && IsPartOfWord(Buffer[PrefixLoc - 1])) 794 continue; 795 796 Check::CheckType Ty = FindCheckType(Rest, Prefix); 797 if (Ty == Check::CheckNone) 798 continue; 799 800 FirstLoc = PrefixLoc; 801 FirstTy = Ty; 802 FirstPrefix = Prefix; 803 } 804 805 if (FirstPrefix.empty()) { 806 CheckLoc = SearchLoc; 807 } else { 808 CheckTy = FirstTy; 809 CheckLoc = FirstLoc; 810 } 811 812 return FirstPrefix; 813} 814 815static StringRef FindFirstMatchingPrefix(StringRef &Buffer, 816 unsigned &LineNumber, 817 Check::CheckType &CheckTy, 818 size_t &CheckLoc) { 819 while (!Buffer.empty()) { 820 StringRef Prefix = FindFirstCandidateMatch(Buffer, CheckTy, CheckLoc); 821 // If we found a real match, we are done. 822 if (!Prefix.empty()) { 823 LineNumber += Buffer.substr(0, CheckLoc).count('\n'); 824 return Prefix; 825 } 826 827 // We didn't find any almost matches either, we are also done. 828 if (CheckLoc == StringRef::npos) 829 return StringRef(); 830 831 LineNumber += Buffer.substr(0, CheckLoc + 1).count('\n'); 832 833 // Advance to the last possible match we found and try again. 834 Buffer = Buffer.drop_front(CheckLoc + 1); 835 } 836 837 return StringRef(); 838} 839 840/// ReadCheckFile - Read the check file, which specifies the sequence of 841/// expected strings. The strings are added to the CheckStrings vector. 842/// Returns true in case of an error, false otherwise. 843static bool ReadCheckFile(SourceMgr &SM, 844 std::vector<CheckString> &CheckStrings) { 845 OwningPtr<MemoryBuffer> File; 846 if (error_code ec = 847 MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) { 848 errs() << "Could not open check file '" << CheckFilename << "': " 849 << ec.message() << '\n'; 850 return true; 851 } 852 853 // If we want to canonicalize whitespace, strip excess whitespace from the 854 // buffer containing the CHECK lines. Remove DOS style line endings. 855 MemoryBuffer *F = 856 CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace); 857 858 SM.AddNewSourceBuffer(F, SMLoc()); 859 860 // Find all instances of CheckPrefix followed by : in the file. 861 StringRef Buffer = F->getBuffer(); 862 std::vector<Pattern> DagNotMatches; 863 864 // LineNumber keeps track of the line on which CheckPrefix instances are 865 // found. 866 unsigned LineNumber = 1; 867 868 while (1) { 869 Check::CheckType CheckTy; 870 size_t PrefixLoc; 871 872 // See if a prefix occurs in the memory buffer. 873 StringRef UsedPrefix = FindFirstMatchingPrefix(Buffer, 874 LineNumber, 875 CheckTy, 876 PrefixLoc); 877 if (UsedPrefix.empty()) 878 break; 879 880 Buffer = Buffer.drop_front(PrefixLoc); 881 882 // Location to use for error messages. 883 const char *UsedPrefixStart = Buffer.data() + (PrefixLoc == 0 ? 0 : 1); 884 885 // PrefixLoc is to the start of the prefix. Skip to the end. 886 Buffer = Buffer.drop_front(UsedPrefix.size() + CheckTypeSize(CheckTy)); 887 888 // Okay, we found the prefix, yay. Remember the rest of the line, but ignore 889 // leading and trailing whitespace. 890 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t")); 891 892 // Scan ahead to the end of line. 893 size_t EOL = Buffer.find_first_of("\n\r"); 894 895 // Remember the location of the start of the pattern, for diagnostics. 896 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data()); 897 898 // Parse the pattern. 899 Pattern P(CheckTy); 900 if (P.ParsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, LineNumber)) 901 return true; 902 903 // Verify that CHECK-LABEL lines do not define or use variables 904 if ((CheckTy == Check::CheckLabel) && P.hasVariable()) { 905 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart), 906 SourceMgr::DK_Error, 907 "found '" + UsedPrefix + "-LABEL:'" 908 " with variable definition or use"); 909 return true; 910 } 911 912 Buffer = Buffer.substr(EOL); 913 914 // Verify that CHECK-NEXT lines have at least one CHECK line before them. 915 if ((CheckTy == Check::CheckNext) && CheckStrings.empty()) { 916 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart), 917 SourceMgr::DK_Error, 918 "found '" + UsedPrefix + "-NEXT:' without previous '" 919 + UsedPrefix + ": line"); 920 return true; 921 } 922 923 // Handle CHECK-DAG/-NOT. 924 if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) { 925 DagNotMatches.push_back(P); 926 continue; 927 } 928 929 // Okay, add the string we captured to the output vector and move on. 930 CheckStrings.push_back(CheckString(P, 931 UsedPrefix, 932 PatternLoc, 933 CheckTy)); 934 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings); 935 } 936 937 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first 938 // prefix as a filler for the error message. 939 if (!DagNotMatches.empty()) { 940 CheckStrings.push_back(CheckString(Pattern(Check::CheckEOF), 941 CheckPrefixes[0], 942 SMLoc::getFromPointer(Buffer.data()), 943 Check::CheckEOF)); 944 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings); 945 } 946 947 if (CheckStrings.empty()) { 948 errs() << "error: no check strings found with prefix" 949 << (CheckPrefixes.size() > 1 ? "es " : " "); 950 for (size_t I = 0, N = CheckPrefixes.size(); I != N; ++I) { 951 StringRef Prefix(CheckPrefixes[I]); 952 errs() << '\'' << Prefix << ":'"; 953 if (I != N - 1) 954 errs() << ", "; 955 } 956 957 errs() << '\n'; 958 return true; 959 } 960 961 return false; 962} 963 964static void PrintCheckFailed(const SourceMgr &SM, const SMLoc &Loc, 965 const Pattern &Pat, StringRef Buffer, 966 StringMap<StringRef> &VariableTable) { 967 // Otherwise, we have an error, emit an error message. 968 SM.PrintMessage(Loc, SourceMgr::DK_Error, 969 "expected string not found in input"); 970 971 // Print the "scanning from here" line. If the current position is at the 972 // end of a line, advance to the start of the next line. 973 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r")); 974 975 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, 976 "scanning from here"); 977 978 // Allow the pattern to print additional information if desired. 979 Pat.PrintFailureInfo(SM, Buffer, VariableTable); 980} 981 982static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr, 983 StringRef Buffer, 984 StringMap<StringRef> &VariableTable) { 985 PrintCheckFailed(SM, CheckStr.Loc, CheckStr.Pat, Buffer, VariableTable); 986} 987 988/// CountNumNewlinesBetween - Count the number of newlines in the specified 989/// range. 990static unsigned CountNumNewlinesBetween(StringRef Range) { 991 unsigned NumNewLines = 0; 992 while (1) { 993 // Scan for newline. 994 Range = Range.substr(Range.find_first_of("\n\r")); 995 if (Range.empty()) return NumNewLines; 996 997 ++NumNewLines; 998 999 // Handle \n\r and \r\n as a single newline. 1000 if (Range.size() > 1 && 1001 (Range[1] == '\n' || Range[1] == '\r') && 1002 (Range[0] != Range[1])) 1003 Range = Range.substr(1); 1004 Range = Range.substr(1); 1005 } 1006} 1007 1008size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer, 1009 bool IsLabelScanMode, size_t &MatchLen, 1010 StringMap<StringRef> &VariableTable) const { 1011 size_t LastPos = 0; 1012 std::vector<const Pattern *> NotStrings; 1013 1014 // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL 1015 // bounds; we have not processed variable definitions within the bounded block 1016 // yet so cannot handle any final CHECK-DAG yet; this is handled when going 1017 // over the block again (including the last CHECK-LABEL) in normal mode. 1018 if (!IsLabelScanMode) { 1019 // Match "dag strings" (with mixed "not strings" if any). 1020 LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable); 1021 if (LastPos == StringRef::npos) 1022 return StringRef::npos; 1023 } 1024 1025 // Match itself from the last position after matching CHECK-DAG. 1026 StringRef MatchBuffer = Buffer.substr(LastPos); 1027 size_t MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable); 1028 if (MatchPos == StringRef::npos) { 1029 PrintCheckFailed(SM, *this, MatchBuffer, VariableTable); 1030 return StringRef::npos; 1031 } 1032 MatchPos += LastPos; 1033 1034 // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT 1035 // or CHECK-NOT 1036 if (!IsLabelScanMode) { 1037 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos); 1038 1039 // If this check is a "CHECK-NEXT", verify that the previous match was on 1040 // the previous line (i.e. that there is one newline between them). 1041 if (CheckNext(SM, SkippedRegion)) 1042 return StringRef::npos; 1043 1044 // If this match had "not strings", verify that they don't exist in the 1045 // skipped region. 1046 if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable)) 1047 return StringRef::npos; 1048 } 1049 1050 return MatchPos; 1051} 1052 1053bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const { 1054 if (CheckTy != Check::CheckNext) 1055 return false; 1056 1057 // Count the number of newlines between the previous match and this one. 1058 assert(Buffer.data() != 1059 SM.getMemoryBuffer( 1060 SM.FindBufferContainingLoc( 1061 SMLoc::getFromPointer(Buffer.data())))->getBufferStart() && 1062 "CHECK-NEXT can't be the first check in a file"); 1063 1064 unsigned NumNewLines = CountNumNewlinesBetween(Buffer); 1065 1066 if (NumNewLines == 0) { 1067 SM.PrintMessage(Loc, SourceMgr::DK_Error, Prefix + 1068 "-NEXT: is on the same line as previous match"); 1069 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), 1070 SourceMgr::DK_Note, "'next' match was here"); 1071 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, 1072 "previous match ended here"); 1073 return true; 1074 } 1075 1076 if (NumNewLines != 1) { 1077 SM.PrintMessage(Loc, SourceMgr::DK_Error, Prefix + 1078 "-NEXT: is not on the line after the previous match"); 1079 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), 1080 SourceMgr::DK_Note, "'next' match was here"); 1081 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note, 1082 "previous match ended here"); 1083 return true; 1084 } 1085 1086 return false; 1087} 1088 1089bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer, 1090 const std::vector<const Pattern *> &NotStrings, 1091 StringMap<StringRef> &VariableTable) const { 1092 for (unsigned ChunkNo = 0, e = NotStrings.size(); 1093 ChunkNo != e; ++ChunkNo) { 1094 const Pattern *Pat = NotStrings[ChunkNo]; 1095 assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!"); 1096 1097 size_t MatchLen = 0; 1098 size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable); 1099 1100 if (Pos == StringRef::npos) continue; 1101 1102 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos), 1103 SourceMgr::DK_Error, 1104 Prefix + "-NOT: string occurred!"); 1105 SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note, 1106 Prefix + "-NOT: pattern specified here"); 1107 return true; 1108 } 1109 1110 return false; 1111} 1112 1113size_t CheckString::CheckDag(const SourceMgr &SM, StringRef Buffer, 1114 std::vector<const Pattern *> &NotStrings, 1115 StringMap<StringRef> &VariableTable) const { 1116 if (DagNotStrings.empty()) 1117 return 0; 1118 1119 size_t LastPos = 0; 1120 size_t StartPos = LastPos; 1121 1122 for (unsigned ChunkNo = 0, e = DagNotStrings.size(); 1123 ChunkNo != e; ++ChunkNo) { 1124 const Pattern &Pat = DagNotStrings[ChunkNo]; 1125 1126 assert((Pat.getCheckTy() == Check::CheckDAG || 1127 Pat.getCheckTy() == Check::CheckNot) && 1128 "Invalid CHECK-DAG or CHECK-NOT!"); 1129 1130 if (Pat.getCheckTy() == Check::CheckNot) { 1131 NotStrings.push_back(&Pat); 1132 continue; 1133 } 1134 1135 assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!"); 1136 1137 size_t MatchLen = 0, MatchPos; 1138 1139 // CHECK-DAG always matches from the start. 1140 StringRef MatchBuffer = Buffer.substr(StartPos); 1141 MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable); 1142 // With a group of CHECK-DAGs, a single mismatching means the match on 1143 // that group of CHECK-DAGs fails immediately. 1144 if (MatchPos == StringRef::npos) { 1145 PrintCheckFailed(SM, Pat.getLoc(), Pat, MatchBuffer, VariableTable); 1146 return StringRef::npos; 1147 } 1148 // Re-calc it as the offset relative to the start of the original string. 1149 MatchPos += StartPos; 1150 1151 if (!NotStrings.empty()) { 1152 if (MatchPos < LastPos) { 1153 // Reordered? 1154 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + MatchPos), 1155 SourceMgr::DK_Error, 1156 Prefix + "-DAG: found a match of CHECK-DAG" 1157 " reordering across a CHECK-NOT"); 1158 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + LastPos), 1159 SourceMgr::DK_Note, 1160 Prefix + "-DAG: the farthest match of CHECK-DAG" 1161 " is found here"); 1162 SM.PrintMessage(NotStrings[0]->getLoc(), SourceMgr::DK_Note, 1163 Prefix + "-NOT: the crossed pattern specified" 1164 " here"); 1165 SM.PrintMessage(Pat.getLoc(), SourceMgr::DK_Note, 1166 Prefix + "-DAG: the reordered pattern specified" 1167 " here"); 1168 return StringRef::npos; 1169 } 1170 // All subsequent CHECK-DAGs should be matched from the farthest 1171 // position of all precedent CHECK-DAGs (including this one.) 1172 StartPos = LastPos; 1173 // If there's CHECK-NOTs between two CHECK-DAGs or from CHECK to 1174 // CHECK-DAG, verify that there's no 'not' strings occurred in that 1175 // region. 1176 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos); 1177 if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable)) 1178 return StringRef::npos; 1179 // Clear "not strings". 1180 NotStrings.clear(); 1181 } 1182 1183 // Update the last position with CHECK-DAG matches. 1184 LastPos = std::max(MatchPos + MatchLen, LastPos); 1185 } 1186 1187 return LastPos; 1188} 1189 1190// A check prefix must contain only alphanumeric, hyphens and underscores. 1191static bool ValidateCheckPrefix(StringRef CheckPrefix) { 1192 Regex Validator("^[a-zA-Z0-9_-]*$"); 1193 return Validator.match(CheckPrefix); 1194} 1195 1196static bool ValidateCheckPrefixes() { 1197 StringSet<> PrefixSet; 1198 1199 for (prefix_iterator I = CheckPrefixes.begin(), E = CheckPrefixes.end(); 1200 I != E; ++I) { 1201 StringRef Prefix(*I); 1202 1203 if (!PrefixSet.insert(Prefix)) 1204 return false; 1205 1206 if (!ValidateCheckPrefix(Prefix)) 1207 return false; 1208 } 1209 1210 return true; 1211} 1212 1213// I don't think there's a way to specify an initial value for cl::list, 1214// so if nothing was specified, add the default 1215static void AddCheckPrefixIfNeeded() { 1216 if (CheckPrefixes.empty()) 1217 CheckPrefixes.push_back("CHECK"); 1218} 1219 1220int main(int argc, char **argv) { 1221 sys::PrintStackTraceOnErrorSignal(); 1222 PrettyStackTraceProgram X(argc, argv); 1223 cl::ParseCommandLineOptions(argc, argv); 1224 1225 if (!ValidateCheckPrefixes()) { 1226 errs() << "Supplied check-prefix is invalid! Prefixes must be unique and " 1227 "start with a letter and contain only alphanumeric characters, " 1228 "hyphens and underscores\n"; 1229 return 2; 1230 } 1231 1232 AddCheckPrefixIfNeeded(); 1233 1234 SourceMgr SM; 1235 1236 // Read the expected strings from the check file. 1237 std::vector<CheckString> CheckStrings; 1238 if (ReadCheckFile(SM, CheckStrings)) 1239 return 2; 1240 1241 // Open the file to check and add it to SourceMgr. 1242 OwningPtr<MemoryBuffer> File; 1243 if (error_code ec = 1244 MemoryBuffer::getFileOrSTDIN(InputFilename, File)) { 1245 errs() << "Could not open input file '" << InputFilename << "': " 1246 << ec.message() << '\n'; 1247 return 2; 1248 } 1249 1250 if (File->getBufferSize() == 0) { 1251 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n"; 1252 return 2; 1253 } 1254 1255 // Remove duplicate spaces in the input file if requested. 1256 // Remove DOS style line endings. 1257 MemoryBuffer *F = 1258 CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace); 1259 1260 SM.AddNewSourceBuffer(F, SMLoc()); 1261 1262 /// VariableTable - This holds all the current filecheck variables. 1263 StringMap<StringRef> VariableTable; 1264 1265 // Check that we have all of the expected strings, in order, in the input 1266 // file. 1267 StringRef Buffer = F->getBuffer(); 1268 1269 bool hasError = false; 1270 1271 unsigned i = 0, j = 0, e = CheckStrings.size(); 1272 1273 while (true) { 1274 StringRef CheckRegion; 1275 if (j == e) { 1276 CheckRegion = Buffer; 1277 } else { 1278 const CheckString &CheckLabelStr = CheckStrings[j]; 1279 if (CheckLabelStr.CheckTy != Check::CheckLabel) { 1280 ++j; 1281 continue; 1282 } 1283 1284 // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG 1285 size_t MatchLabelLen = 0; 1286 size_t MatchLabelPos = CheckLabelStr.Check(SM, Buffer, true, 1287 MatchLabelLen, VariableTable); 1288 if (MatchLabelPos == StringRef::npos) { 1289 hasError = true; 1290 break; 1291 } 1292 1293 CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen); 1294 Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen); 1295 ++j; 1296 } 1297 1298 for ( ; i != j; ++i) { 1299 const CheckString &CheckStr = CheckStrings[i]; 1300 1301 // Check each string within the scanned region, including a second check 1302 // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG) 1303 size_t MatchLen = 0; 1304 size_t MatchPos = CheckStr.Check(SM, CheckRegion, false, MatchLen, 1305 VariableTable); 1306 1307 if (MatchPos == StringRef::npos) { 1308 hasError = true; 1309 i = j; 1310 break; 1311 } 1312 1313 CheckRegion = CheckRegion.substr(MatchPos + MatchLen); 1314 } 1315 1316 if (j == e) 1317 break; 1318 } 1319 1320 return hasError ? 1 : 0; 1321} 1322