[ARM] MVE integer min and max
[llvm-complete.git] / lib / Support / FileCheck.cpp
blob9fb4d798849d704942b74ecf04dc189ed34b1a2c
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.
12 // This file implements most of the API that will be used by the FileCheck utility
13 // as well as various unittests.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Support/FileCheck.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/Support/FormatVariadic.h"
19 #include <cstdint>
20 #include <list>
21 #include <map>
22 #include <tuple>
23 #include <utility>
25 using namespace llvm;
27 void FileCheckNumericVariable::setValue(uint64_t NewValue) {
28 assert(!Value && "Overwriting numeric variable's value is not allowed");
29 Value = NewValue;
32 void FileCheckNumericVariable::clearValue() {
33 if (!Value)
34 return;
35 Value = None;
38 Expected<uint64_t> FileCheckNumericVariableUse::eval() const {
39 Optional<uint64_t> Value = NumericVariable->getValue();
40 if (Value)
41 return *Value;
42 return make_error<FileCheckUndefVarError>(Name);
45 Expected<uint64_t> FileCheckASTBinop::eval() const {
46 Expected<uint64_t> LeftOp = LeftOperand->eval();
47 Expected<uint64_t> RightOp = RightOperand->eval();
49 // Bubble up any error (e.g. undefined variables) in the recursive
50 // evaluation.
51 if (!LeftOp || !RightOp) {
52 Error Err = Error::success();
53 if (!LeftOp)
54 Err = joinErrors(std::move(Err), LeftOp.takeError());
55 if (!RightOp)
56 Err = joinErrors(std::move(Err), RightOp.takeError());
57 return std::move(Err);
60 return EvalBinop(*LeftOp, *RightOp);
63 Expected<std::string> FileCheckNumericSubstitution::getResult() const {
64 Expected<uint64_t> EvaluatedValue = ExpressionAST->eval();
65 if (!EvaluatedValue)
66 return EvaluatedValue.takeError();
67 return utostr(*EvaluatedValue);
70 Expected<std::string> FileCheckStringSubstitution::getResult() const {
71 // Look up the value and escape it so that we can put it into the regex.
72 Expected<StringRef> VarVal = Context->getPatternVarValue(FromStr);
73 if (!VarVal)
74 return VarVal.takeError();
75 return Regex::escape(*VarVal);
78 bool FileCheckPattern::isValidVarNameStart(char C) {
79 return C == '_' || isalpha(C);
82 Expected<FileCheckPattern::VariableProperties>
83 FileCheckPattern::parseVariable(StringRef &Str, const SourceMgr &SM) {
84 if (Str.empty())
85 return FileCheckErrorDiagnostic::get(SM, Str, "empty variable name");
87 bool ParsedOneChar = false;
88 unsigned I = 0;
89 bool IsPseudo = Str[0] == '@';
91 // Global vars start with '$'.
92 if (Str[0] == '$' || IsPseudo)
93 ++I;
95 for (unsigned E = Str.size(); I != E; ++I) {
96 if (!ParsedOneChar && !isValidVarNameStart(Str[I]))
97 return FileCheckErrorDiagnostic::get(SM, Str, "invalid variable name");
99 // Variable names are composed of alphanumeric characters and underscores.
100 if (Str[I] != '_' && !isalnum(Str[I]))
101 break;
102 ParsedOneChar = true;
105 StringRef Name = Str.take_front(I);
106 Str = Str.substr(I);
107 return VariableProperties {Name, IsPseudo};
110 // StringRef holding all characters considered as horizontal whitespaces by
111 // FileCheck input canonicalization.
112 StringRef SpaceChars = " \t";
114 // Parsing helper function that strips the first character in S and returns it.
115 static char popFront(StringRef &S) {
116 char C = S.front();
117 S = S.drop_front();
118 return C;
121 char FileCheckUndefVarError::ID = 0;
122 char FileCheckErrorDiagnostic::ID = 0;
123 char FileCheckNotFoundError::ID = 0;
125 Expected<FileCheckNumericVariable *>
126 FileCheckPattern::parseNumericVariableDefinition(
127 StringRef &Expr, FileCheckPatternContext *Context, size_t LineNumber,
128 const SourceMgr &SM) {
129 Expected<VariableProperties> ParseVarResult = parseVariable(Expr, SM);
130 if (!ParseVarResult)
131 return ParseVarResult.takeError();
132 StringRef Name = ParseVarResult->Name;
134 if (ParseVarResult->IsPseudo)
135 return FileCheckErrorDiagnostic::get(
136 SM, Name, "definition of pseudo numeric variable unsupported");
138 // Detect collisions between string and numeric variables when the latter
139 // is created later than the former.
140 if (Context->DefinedVariableTable.find(Name) !=
141 Context->DefinedVariableTable.end())
142 return FileCheckErrorDiagnostic::get(
143 SM, Name, "string variable with name '" + Name + "' already exists");
145 Expr = Expr.ltrim(SpaceChars);
146 if (!Expr.empty())
147 return FileCheckErrorDiagnostic::get(
148 SM, Expr, "unexpected characters after numeric variable name");
150 FileCheckNumericVariable *DefinedNumericVariable;
151 auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
152 if (VarTableIter != Context->GlobalNumericVariableTable.end())
153 DefinedNumericVariable = VarTableIter->second;
154 else
155 DefinedNumericVariable = Context->makeNumericVariable(LineNumber, Name);
157 return DefinedNumericVariable;
160 Expected<std::unique_ptr<FileCheckNumericVariableUse>>
161 FileCheckPattern::parseNumericVariableUse(StringRef Name, bool IsPseudo,
162 const SourceMgr &SM) const {
163 if (IsPseudo && !Name.equals("@LINE"))
164 return FileCheckErrorDiagnostic::get(
165 SM, Name, "invalid pseudo numeric variable '" + Name + "'");
167 // Numeric variable definitions and uses are parsed in the order in which
168 // they appear in the CHECK patterns. For each definition, the pointer to the
169 // class instance of the corresponding numeric variable definition is stored
170 // in GlobalNumericVariableTable in parsePattern. Therefore, if the pointer
171 // we get below is null, it means no such variable was defined before. When
172 // that happens, we create a dummy variable so that parsing can continue. All
173 // uses of undefined variables, whether string or numeric, are then diagnosed
174 // in printSubstitutions() after failing to match.
175 auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
176 FileCheckNumericVariable *NumericVariable;
177 if (VarTableIter != Context->GlobalNumericVariableTable.end())
178 NumericVariable = VarTableIter->second;
179 else {
180 NumericVariable = Context->makeNumericVariable(0, Name);
181 Context->GlobalNumericVariableTable[Name] = NumericVariable;
184 if (!IsPseudo && NumericVariable->getDefLineNumber() == LineNumber)
185 return FileCheckErrorDiagnostic::get(
186 SM, Name,
187 "numeric variable '" + Name + "' defined on the same line as used");
189 return llvm::make_unique<FileCheckNumericVariableUse>(Name, NumericVariable);
192 Expected<std::unique_ptr<FileCheckExpressionAST>>
193 FileCheckPattern::parseNumericOperand(StringRef &Expr, AllowedOperand AO,
194 const SourceMgr &SM) const {
195 if (AO == AllowedOperand::LineVar || AO == AllowedOperand::Any) {
196 // Try to parse as a numeric variable use.
197 Expected<FileCheckPattern::VariableProperties> ParseVarResult =
198 parseVariable(Expr, SM);
199 if (ParseVarResult)
200 return parseNumericVariableUse(ParseVarResult->Name,
201 ParseVarResult->IsPseudo, SM);
202 if (AO == AllowedOperand::LineVar)
203 return ParseVarResult.takeError();
204 // Ignore the error and retry parsing as a literal.
205 consumeError(ParseVarResult.takeError());
208 // Otherwise, parse it as a literal.
209 uint64_t LiteralValue;
210 if (!Expr.consumeInteger(/*Radix=*/10, LiteralValue))
211 return llvm::make_unique<FileCheckExpressionLiteral>(LiteralValue);
213 return FileCheckErrorDiagnostic::get(SM, Expr,
214 "invalid operand format '" + Expr + "'");
217 static uint64_t add(uint64_t LeftOp, uint64_t RightOp) {
218 return LeftOp + RightOp;
221 static uint64_t sub(uint64_t LeftOp, uint64_t RightOp) {
222 return LeftOp - RightOp;
225 Expected<std::unique_ptr<FileCheckExpressionAST>>
226 FileCheckPattern::parseBinop(StringRef &Expr,
227 std::unique_ptr<FileCheckExpressionAST> LeftOp,
228 bool IsLegacyLineExpr, const SourceMgr &SM) const {
229 Expr = Expr.ltrim(SpaceChars);
230 if (Expr.empty())
231 return std::move(LeftOp);
233 // Check if this is a supported operation and select a function to perform
234 // it.
235 SMLoc OpLoc = SMLoc::getFromPointer(Expr.data());
236 char Operator = popFront(Expr);
237 binop_eval_t EvalBinop;
238 switch (Operator) {
239 case '+':
240 EvalBinop = add;
241 break;
242 case '-':
243 EvalBinop = sub;
244 break;
245 default:
246 return FileCheckErrorDiagnostic::get(
247 SM, OpLoc, Twine("unsupported operation '") + Twine(Operator) + "'");
250 // Parse right operand.
251 Expr = Expr.ltrim(SpaceChars);
252 if (Expr.empty())
253 return FileCheckErrorDiagnostic::get(SM, Expr,
254 "missing operand in expression");
255 // The second operand in a legacy @LINE expression is always a literal.
256 AllowedOperand AO =
257 IsLegacyLineExpr ? AllowedOperand::Literal : AllowedOperand::Any;
258 Expected<std::unique_ptr<FileCheckExpressionAST>> RightOpResult =
259 parseNumericOperand(Expr, AO, SM);
260 if (!RightOpResult)
261 return RightOpResult;
263 Expr = Expr.ltrim(SpaceChars);
264 return llvm::make_unique<FileCheckASTBinop>(EvalBinop, std::move(LeftOp),
265 std::move(*RightOpResult));
268 Expected<std::unique_ptr<FileCheckExpressionAST>>
269 FileCheckPattern::parseNumericSubstitutionBlock(
270 StringRef Expr,
271 Optional<FileCheckNumericVariable *> &DefinedNumericVariable,
272 bool IsLegacyLineExpr, const SourceMgr &SM) const {
273 // Parse the numeric variable definition.
274 DefinedNumericVariable = None;
275 size_t DefEnd = Expr.find(':');
276 if (DefEnd != StringRef::npos) {
277 StringRef DefExpr = Expr.substr(0, DefEnd);
278 StringRef UseExpr = Expr.substr(DefEnd + 1);
280 UseExpr = UseExpr.ltrim(SpaceChars);
281 if (!UseExpr.empty())
282 return FileCheckErrorDiagnostic::get(
283 SM, UseExpr,
284 "unexpected string after variable definition: '" + UseExpr + "'");
286 DefExpr = DefExpr.ltrim(SpaceChars);
287 Expected<FileCheckNumericVariable *> ParseResult =
288 parseNumericVariableDefinition(DefExpr, Context, LineNumber, SM);
289 if (!ParseResult)
290 return ParseResult.takeError();
291 DefinedNumericVariable = *ParseResult;
293 return nullptr;
296 // Parse the expression itself.
297 Expr = Expr.ltrim(SpaceChars);
298 // The first operand in a legacy @LINE expression is always the @LINE pseudo
299 // variable.
300 AllowedOperand AO =
301 IsLegacyLineExpr ? AllowedOperand::LineVar : AllowedOperand::Any;
302 Expected<std::unique_ptr<FileCheckExpressionAST>> ParseResult =
303 parseNumericOperand(Expr, AO, SM);
304 while (ParseResult && !Expr.empty()) {
305 ParseResult =
306 parseBinop(Expr, std::move(*ParseResult), IsLegacyLineExpr, SM);
307 // Legacy @LINE expressions only allow 2 operands.
308 if (ParseResult && IsLegacyLineExpr && !Expr.empty())
309 return FileCheckErrorDiagnostic::get(
310 SM, Expr,
311 "unexpected characters at end of expression '" + Expr + "'");
313 if (!ParseResult)
314 return ParseResult;
315 return std::move(*ParseResult);
318 bool FileCheckPattern::parsePattern(StringRef PatternStr, StringRef Prefix,
319 SourceMgr &SM,
320 const FileCheckRequest &Req) {
321 bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
323 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
325 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
326 // Ignore trailing whitespace.
327 while (!PatternStr.empty() &&
328 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
329 PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
331 // Check that there is something on the line.
332 if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
333 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
334 "found empty check string with prefix '" + Prefix + ":'");
335 return true;
338 if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
339 SM.PrintMessage(
340 PatternLoc, SourceMgr::DK_Error,
341 "found non-empty check string for empty check with prefix '" + Prefix +
342 ":'");
343 return true;
346 if (CheckTy == Check::CheckEmpty) {
347 RegExStr = "(\n$)";
348 return false;
351 // Check to see if this is a fixed string, or if it has regex pieces.
352 if (!MatchFullLinesHere &&
353 (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
354 PatternStr.find("[[") == StringRef::npos))) {
355 FixedStr = PatternStr;
356 return false;
359 if (MatchFullLinesHere) {
360 RegExStr += '^';
361 if (!Req.NoCanonicalizeWhiteSpace)
362 RegExStr += " *";
365 // Paren value #0 is for the fully matched string. Any new parenthesized
366 // values add from there.
367 unsigned CurParen = 1;
369 // Otherwise, there is at least one regex piece. Build up the regex pattern
370 // by escaping scary characters in fixed strings, building up one big regex.
371 while (!PatternStr.empty()) {
372 // RegEx matches.
373 if (PatternStr.startswith("{{")) {
374 // This is the start of a regex match. Scan for the }}.
375 size_t End = PatternStr.find("}}");
376 if (End == StringRef::npos) {
377 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
378 SourceMgr::DK_Error,
379 "found start of regex string with no end '}}'");
380 return true;
383 // Enclose {{}} patterns in parens just like [[]] even though we're not
384 // capturing the result for any purpose. This is required in case the
385 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
386 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
387 RegExStr += '(';
388 ++CurParen;
390 if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
391 return true;
392 RegExStr += ')';
394 PatternStr = PatternStr.substr(End + 2);
395 continue;
398 // String and numeric substitution blocks. String substitution blocks come
399 // in two forms: [[foo:.*]] and [[foo]]. The former matches .* (or some
400 // other regex) and assigns it to the string variable 'foo'. The latter
401 // substitutes foo's value. Numeric substitution blocks work the same way
402 // as string ones, but start with a '#' sign after the double brackets.
403 // Both string and numeric variable names must satisfy the regular
404 // expression "[a-zA-Z_][0-9a-zA-Z_]*" to be valid, as this helps catch
405 // some common errors.
406 if (PatternStr.startswith("[[")) {
407 StringRef UnparsedPatternStr = PatternStr.substr(2);
408 // Find the closing bracket pair ending the match. End is going to be an
409 // offset relative to the beginning of the match string.
410 size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
411 StringRef MatchStr = UnparsedPatternStr.substr(0, End);
412 bool IsNumBlock = MatchStr.consume_front("#");
414 if (End == StringRef::npos) {
415 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
416 SourceMgr::DK_Error,
417 "Invalid substitution block, no ]] found");
418 return true;
420 // Strip the substitution block we are parsing. End points to the start
421 // of the "]]" closing the expression so account for it in computing the
422 // index of the first unparsed character.
423 PatternStr = UnparsedPatternStr.substr(End + 2);
425 bool IsDefinition = false;
426 // Whether the substitution block is a legacy use of @LINE with string
427 // substitution block syntax.
428 bool IsLegacyLineExpr = false;
429 StringRef DefName;
430 StringRef SubstStr;
431 StringRef MatchRegexp;
432 size_t SubstInsertIdx = RegExStr.size();
434 // Parse string variable or legacy @LINE expression.
435 if (!IsNumBlock) {
436 size_t VarEndIdx = MatchStr.find(":");
437 size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
438 if (SpacePos != StringRef::npos) {
439 SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
440 SourceMgr::DK_Error, "unexpected whitespace");
441 return true;
444 // Get the name (e.g. "foo") and verify it is well formed.
445 StringRef OrigMatchStr = MatchStr;
446 Expected<FileCheckPattern::VariableProperties> ParseVarResult =
447 parseVariable(MatchStr, SM);
448 if (!ParseVarResult) {
449 logAllUnhandledErrors(ParseVarResult.takeError(), errs());
450 return true;
452 StringRef Name = ParseVarResult->Name;
453 bool IsPseudo = ParseVarResult->IsPseudo;
455 IsDefinition = (VarEndIdx != StringRef::npos);
456 if (IsDefinition) {
457 if ((IsPseudo || !MatchStr.consume_front(":"))) {
458 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
459 SourceMgr::DK_Error,
460 "invalid name in string variable definition");
461 return true;
464 // Detect collisions between string and numeric variables when the
465 // former is created later than the latter.
466 if (Context->GlobalNumericVariableTable.find(Name) !=
467 Context->GlobalNumericVariableTable.end()) {
468 SM.PrintMessage(
469 SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
470 "numeric variable with name '" + Name + "' already exists");
471 return true;
473 DefName = Name;
474 MatchRegexp = MatchStr;
475 } else {
476 if (IsPseudo) {
477 MatchStr = OrigMatchStr;
478 IsLegacyLineExpr = IsNumBlock = true;
479 } else
480 SubstStr = Name;
484 // Parse numeric substitution block.
485 std::unique_ptr<FileCheckExpressionAST> ExpressionAST;
486 Optional<FileCheckNumericVariable *> DefinedNumericVariable;
487 if (IsNumBlock) {
488 Expected<std::unique_ptr<FileCheckExpressionAST>> ParseResult =
489 parseNumericSubstitutionBlock(MatchStr, DefinedNumericVariable,
490 IsLegacyLineExpr, SM);
491 if (!ParseResult) {
492 logAllUnhandledErrors(ParseResult.takeError(), errs());
493 return true;
495 ExpressionAST = std::move(*ParseResult);
496 if (DefinedNumericVariable) {
497 IsDefinition = true;
498 DefName = (*DefinedNumericVariable)->getName();
499 MatchRegexp = StringRef("[0-9]+");
500 } else
501 SubstStr = MatchStr;
504 // Handle substitutions: [[foo]] and [[#<foo expr>]].
505 if (!IsDefinition) {
506 // Handle substitution of string variables that were defined earlier on
507 // the same line by emitting a backreference. Expressions do not
508 // support substituting a numeric variable defined on the same line.
509 if (!IsNumBlock && VariableDefs.find(SubstStr) != VariableDefs.end()) {
510 unsigned CaptureParenGroup = VariableDefs[SubstStr];
511 if (CaptureParenGroup < 1 || CaptureParenGroup > 9) {
512 SM.PrintMessage(SMLoc::getFromPointer(SubstStr.data()),
513 SourceMgr::DK_Error,
514 "Can't back-reference more than 9 variables");
515 return true;
517 AddBackrefToRegEx(CaptureParenGroup);
518 } else {
519 // Handle substitution of string variables ([[<var>]]) defined in
520 // previous CHECK patterns, and substitution of expressions.
521 FileCheckSubstitution *Substitution =
522 IsNumBlock
523 ? Context->makeNumericSubstitution(
524 SubstStr, std::move(ExpressionAST), SubstInsertIdx)
525 : Context->makeStringSubstitution(SubstStr, SubstInsertIdx);
526 Substitutions.push_back(Substitution);
528 continue;
531 // Handle variable definitions: [[<def>:(...)]] and
532 // [[#(...)<def>:(...)]].
533 if (IsNumBlock) {
534 FileCheckNumericVariableMatch NumericVariableDefinition = {
535 *DefinedNumericVariable, CurParen};
536 NumericVariableDefs[DefName] = NumericVariableDefinition;
537 // This store is done here rather than in match() to allow
538 // parseNumericVariableUse() to get the pointer to the class instance
539 // of the right variable definition corresponding to a given numeric
540 // variable use.
541 Context->GlobalNumericVariableTable[DefName] = *DefinedNumericVariable;
542 } else {
543 VariableDefs[DefName] = CurParen;
544 // Mark the string variable as defined to detect collisions between
545 // string and numeric variables in parseNumericVariableUse() and
546 // DefineCmdlineVariables() when the latter is created later than the
547 // former. We cannot reuse GlobalVariableTable for this by populating
548 // it with an empty string since we would then lose the ability to
549 // detect the use of an undefined variable in match().
550 Context->DefinedVariableTable[DefName] = true;
552 RegExStr += '(';
553 ++CurParen;
555 if (AddRegExToRegEx(MatchRegexp, CurParen, SM))
556 return true;
558 RegExStr += ')';
561 // Handle fixed string matches.
562 // Find the end, which is the start of the next regex.
563 size_t FixedMatchEnd = PatternStr.find("{{");
564 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
565 RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
566 PatternStr = PatternStr.substr(FixedMatchEnd);
569 if (MatchFullLinesHere) {
570 if (!Req.NoCanonicalizeWhiteSpace)
571 RegExStr += " *";
572 RegExStr += '$';
575 return false;
578 bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
579 Regex R(RS);
580 std::string Error;
581 if (!R.isValid(Error)) {
582 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
583 "invalid regex: " + Error);
584 return true;
587 RegExStr += RS.str();
588 CurParen += R.getNumMatches();
589 return false;
592 void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
593 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
594 std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
595 RegExStr += Backref;
598 Expected<size_t> FileCheckPattern::match(StringRef Buffer, size_t &MatchLen,
599 const SourceMgr &SM) const {
600 // If this is the EOF pattern, match it immediately.
601 if (CheckTy == Check::CheckEOF) {
602 MatchLen = 0;
603 return Buffer.size();
606 // If this is a fixed string pattern, just match it now.
607 if (!FixedStr.empty()) {
608 MatchLen = FixedStr.size();
609 size_t Pos = Buffer.find(FixedStr);
610 if (Pos == StringRef::npos)
611 return make_error<FileCheckNotFoundError>();
612 return Pos;
615 // Regex match.
617 // If there are substitutions, we need to create a temporary string with the
618 // actual value.
619 StringRef RegExToMatch = RegExStr;
620 std::string TmpStr;
621 if (!Substitutions.empty()) {
622 TmpStr = RegExStr;
623 Context->LineVariable->setValue(LineNumber);
625 size_t InsertOffset = 0;
626 // Substitute all string variables and expressions whose values are only
627 // now known. Use of string variables defined on the same line are handled
628 // by back-references.
629 for (const auto &Substitution : Substitutions) {
630 // Substitute and check for failure (e.g. use of undefined variable).
631 Expected<std::string> Value = Substitution->getResult();
632 if (!Value) {
633 Context->LineVariable->clearValue();
634 return Value.takeError();
637 // Plop it into the regex at the adjusted offset.
638 TmpStr.insert(TmpStr.begin() + Substitution->getIndex() + InsertOffset,
639 Value->begin(), Value->end());
640 InsertOffset += Value->size();
643 // Match the newly constructed regex.
644 RegExToMatch = TmpStr;
645 Context->LineVariable->clearValue();
648 SmallVector<StringRef, 4> MatchInfo;
649 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
650 return make_error<FileCheckNotFoundError>();
652 // Successful regex match.
653 assert(!MatchInfo.empty() && "Didn't get any match");
654 StringRef FullMatch = MatchInfo[0];
656 // If this defines any string variables, remember their values.
657 for (const auto &VariableDef : VariableDefs) {
658 assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
659 Context->GlobalVariableTable[VariableDef.first] =
660 MatchInfo[VariableDef.second];
663 // If this defines any numeric variables, remember their values.
664 for (const auto &NumericVariableDef : NumericVariableDefs) {
665 const FileCheckNumericVariableMatch &NumericVariableMatch =
666 NumericVariableDef.getValue();
667 unsigned CaptureParenGroup = NumericVariableMatch.CaptureParenGroup;
668 assert(CaptureParenGroup < MatchInfo.size() && "Internal paren error");
669 FileCheckNumericVariable *DefinedNumericVariable =
670 NumericVariableMatch.DefinedNumericVariable;
672 StringRef MatchedValue = MatchInfo[CaptureParenGroup];
673 uint64_t Val;
674 if (MatchedValue.getAsInteger(10, Val))
675 return FileCheckErrorDiagnostic::get(SM, MatchedValue,
676 "Unable to represent numeric value");
677 DefinedNumericVariable->setValue(Val);
680 // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
681 // the required preceding newline, which is consumed by the pattern in the
682 // case of CHECK-EMPTY but not CHECK-NEXT.
683 size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
684 MatchLen = FullMatch.size() - MatchStartSkip;
685 return FullMatch.data() - Buffer.data() + MatchStartSkip;
688 unsigned FileCheckPattern::computeMatchDistance(StringRef Buffer) const {
689 // Just compute the number of matching characters. For regular expressions, we
690 // just compare against the regex itself and hope for the best.
692 // FIXME: One easy improvement here is have the regex lib generate a single
693 // example regular expression which matches, and use that as the example
694 // string.
695 StringRef ExampleString(FixedStr);
696 if (ExampleString.empty())
697 ExampleString = RegExStr;
699 // Only compare up to the first line in the buffer, or the string size.
700 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
701 BufferPrefix = BufferPrefix.split('\n').first;
702 return BufferPrefix.edit_distance(ExampleString);
705 void FileCheckPattern::printSubstitutions(const SourceMgr &SM, StringRef Buffer,
706 SMRange MatchRange) const {
707 // Print what we know about substitutions.
708 if (!Substitutions.empty()) {
709 for (const auto &Substitution : Substitutions) {
710 SmallString<256> Msg;
711 raw_svector_ostream OS(Msg);
712 Expected<std::string> MatchedValue = Substitution->getResult();
714 // Substitution failed or is not known at match time, print the undefined
715 // variables it uses.
716 if (!MatchedValue) {
717 bool UndefSeen = false;
718 handleAllErrors(MatchedValue.takeError(),
719 [](const FileCheckNotFoundError &E) {},
720 // Handled in PrintNoMatch().
721 [](const FileCheckErrorDiagnostic &E) {},
722 [&](const FileCheckUndefVarError &E) {
723 if (!UndefSeen) {
724 OS << "uses undefined variable(s):";
725 UndefSeen = true;
727 OS << " ";
728 E.log(OS);
730 } else {
731 // Substitution succeeded. Print substituted value.
732 OS << "with \"";
733 OS.write_escaped(Substitution->getFromString()) << "\" equal to \"";
734 OS.write_escaped(*MatchedValue) << "\"";
737 if (MatchRange.isValid())
738 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
739 {MatchRange});
740 else
741 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
742 SourceMgr::DK_Note, OS.str());
747 static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
748 const SourceMgr &SM, SMLoc Loc,
749 Check::FileCheckType CheckTy,
750 StringRef Buffer, size_t Pos, size_t Len,
751 std::vector<FileCheckDiag> *Diags,
752 bool AdjustPrevDiag = false) {
753 SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
754 SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
755 SMRange Range(Start, End);
756 if (Diags) {
757 if (AdjustPrevDiag)
758 Diags->rbegin()->MatchTy = MatchTy;
759 else
760 Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
762 return Range;
765 void FileCheckPattern::printFuzzyMatch(
766 const SourceMgr &SM, StringRef Buffer,
767 std::vector<FileCheckDiag> *Diags) const {
768 // Attempt to find the closest/best fuzzy match. Usually an error happens
769 // because some string in the output didn't exactly match. In these cases, we
770 // would like to show the user a best guess at what "should have" matched, to
771 // save them having to actually check the input manually.
772 size_t NumLinesForward = 0;
773 size_t Best = StringRef::npos;
774 double BestQuality = 0;
776 // Use an arbitrary 4k limit on how far we will search.
777 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
778 if (Buffer[i] == '\n')
779 ++NumLinesForward;
781 // Patterns have leading whitespace stripped, so skip whitespace when
782 // looking for something which looks like a pattern.
783 if (Buffer[i] == ' ' || Buffer[i] == '\t')
784 continue;
786 // Compute the "quality" of this match as an arbitrary combination of the
787 // match distance and the number of lines skipped to get to this match.
788 unsigned Distance = computeMatchDistance(Buffer.substr(i));
789 double Quality = Distance + (NumLinesForward / 100.);
791 if (Quality < BestQuality || Best == StringRef::npos) {
792 Best = i;
793 BestQuality = Quality;
797 // Print the "possible intended match here" line if we found something
798 // reasonable and not equal to what we showed in the "scanning from here"
799 // line.
800 if (Best && Best != StringRef::npos && BestQuality < 50) {
801 SMRange MatchRange =
802 ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
803 getCheckTy(), Buffer, Best, 0, Diags);
804 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
805 "possible intended match here");
807 // FIXME: If we wanted to be really friendly we would show why the match
808 // failed, as it can be hard to spot simple one character differences.
812 Expected<StringRef>
813 FileCheckPatternContext::getPatternVarValue(StringRef VarName) {
814 auto VarIter = GlobalVariableTable.find(VarName);
815 if (VarIter == GlobalVariableTable.end())
816 return make_error<FileCheckUndefVarError>(VarName);
818 return VarIter->second;
821 template <class... Types>
822 FileCheckNumericVariable *
823 FileCheckPatternContext::makeNumericVariable(Types... args) {
824 NumericVariables.push_back(
825 llvm::make_unique<FileCheckNumericVariable>(args...));
826 return NumericVariables.back().get();
829 FileCheckSubstitution *
830 FileCheckPatternContext::makeStringSubstitution(StringRef VarName,
831 size_t InsertIdx) {
832 Substitutions.push_back(
833 llvm::make_unique<FileCheckStringSubstitution>(this, VarName, InsertIdx));
834 return Substitutions.back().get();
837 FileCheckSubstitution *FileCheckPatternContext::makeNumericSubstitution(
838 StringRef ExpressionStr,
839 std::unique_ptr<FileCheckExpressionAST> ExpressionAST, size_t InsertIdx) {
840 Substitutions.push_back(llvm::make_unique<FileCheckNumericSubstitution>(
841 this, ExpressionStr, std::move(ExpressionAST), InsertIdx));
842 return Substitutions.back().get();
845 size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
846 // Offset keeps track of the current offset within the input Str
847 size_t Offset = 0;
848 // [...] Nesting depth
849 size_t BracketDepth = 0;
851 while (!Str.empty()) {
852 if (Str.startswith("]]") && BracketDepth == 0)
853 return Offset;
854 if (Str[0] == '\\') {
855 // Backslash escapes the next char within regexes, so skip them both.
856 Str = Str.substr(2);
857 Offset += 2;
858 } else {
859 switch (Str[0]) {
860 default:
861 break;
862 case '[':
863 BracketDepth++;
864 break;
865 case ']':
866 if (BracketDepth == 0) {
867 SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
868 SourceMgr::DK_Error,
869 "missing closing \"]\" for regex variable");
870 exit(1);
872 BracketDepth--;
873 break;
875 Str = Str.substr(1);
876 Offset++;
880 return StringRef::npos;
883 StringRef FileCheck::CanonicalizeFile(MemoryBuffer &MB,
884 SmallVectorImpl<char> &OutputBuffer) {
885 OutputBuffer.reserve(MB.getBufferSize());
887 for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
888 Ptr != End; ++Ptr) {
889 // Eliminate trailing dosish \r.
890 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
891 continue;
894 // If current char is not a horizontal whitespace or if horizontal
895 // whitespace canonicalization is disabled, dump it to output as is.
896 if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
897 OutputBuffer.push_back(*Ptr);
898 continue;
901 // Otherwise, add one space and advance over neighboring space.
902 OutputBuffer.push_back(' ');
903 while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
904 ++Ptr;
907 // Add a null byte and then return all but that byte.
908 OutputBuffer.push_back('\0');
909 return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
912 FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
913 const Check::FileCheckType &CheckTy,
914 SMLoc CheckLoc, MatchType MatchTy,
915 SMRange InputRange)
916 : CheckTy(CheckTy), MatchTy(MatchTy) {
917 auto Start = SM.getLineAndColumn(InputRange.Start);
918 auto End = SM.getLineAndColumn(InputRange.End);
919 InputStartLine = Start.first;
920 InputStartCol = Start.second;
921 InputEndLine = End.first;
922 InputEndCol = End.second;
923 Start = SM.getLineAndColumn(CheckLoc);
924 CheckLine = Start.first;
925 CheckCol = Start.second;
928 static bool IsPartOfWord(char c) {
929 return (isalnum(c) || c == '-' || c == '_');
932 Check::FileCheckType &Check::FileCheckType::setCount(int C) {
933 assert(Count > 0 && "zero and negative counts are not supported");
934 assert((C == 1 || Kind == CheckPlain) &&
935 "count supported only for plain CHECK directives");
936 Count = C;
937 return *this;
940 std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
941 switch (Kind) {
942 case Check::CheckNone:
943 return "invalid";
944 case Check::CheckPlain:
945 if (Count > 1)
946 return Prefix.str() + "-COUNT";
947 return Prefix;
948 case Check::CheckNext:
949 return Prefix.str() + "-NEXT";
950 case Check::CheckSame:
951 return Prefix.str() + "-SAME";
952 case Check::CheckNot:
953 return Prefix.str() + "-NOT";
954 case Check::CheckDAG:
955 return Prefix.str() + "-DAG";
956 case Check::CheckLabel:
957 return Prefix.str() + "-LABEL";
958 case Check::CheckEmpty:
959 return Prefix.str() + "-EMPTY";
960 case Check::CheckEOF:
961 return "implicit EOF";
962 case Check::CheckBadNot:
963 return "bad NOT";
964 case Check::CheckBadCount:
965 return "bad COUNT";
967 llvm_unreachable("unknown FileCheckType");
970 static std::pair<Check::FileCheckType, StringRef>
971 FindCheckType(StringRef Buffer, StringRef Prefix) {
972 if (Buffer.size() <= Prefix.size())
973 return {Check::CheckNone, StringRef()};
975 char NextChar = Buffer[Prefix.size()];
977 StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
978 // Verify that the : is present after the prefix.
979 if (NextChar == ':')
980 return {Check::CheckPlain, Rest};
982 if (NextChar != '-')
983 return {Check::CheckNone, StringRef()};
985 if (Rest.consume_front("COUNT-")) {
986 int64_t Count;
987 if (Rest.consumeInteger(10, Count))
988 // Error happened in parsing integer.
989 return {Check::CheckBadCount, Rest};
990 if (Count <= 0 || Count > INT32_MAX)
991 return {Check::CheckBadCount, Rest};
992 if (!Rest.consume_front(":"))
993 return {Check::CheckBadCount, Rest};
994 return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
997 if (Rest.consume_front("NEXT:"))
998 return {Check::CheckNext, Rest};
1000 if (Rest.consume_front("SAME:"))
1001 return {Check::CheckSame, Rest};
1003 if (Rest.consume_front("NOT:"))
1004 return {Check::CheckNot, Rest};
1006 if (Rest.consume_front("DAG:"))
1007 return {Check::CheckDAG, Rest};
1009 if (Rest.consume_front("LABEL:"))
1010 return {Check::CheckLabel, Rest};
1012 if (Rest.consume_front("EMPTY:"))
1013 return {Check::CheckEmpty, Rest};
1015 // You can't combine -NOT with another suffix.
1016 if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
1017 Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
1018 Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
1019 Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
1020 return {Check::CheckBadNot, Rest};
1022 return {Check::CheckNone, Rest};
1025 // From the given position, find the next character after the word.
1026 static size_t SkipWord(StringRef Str, size_t Loc) {
1027 while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
1028 ++Loc;
1029 return Loc;
1032 /// Searches the buffer for the first prefix in the prefix regular expression.
1034 /// This searches the buffer using the provided regular expression, however it
1035 /// enforces constraints beyond that:
1036 /// 1) The found prefix must not be a suffix of something that looks like
1037 /// a valid prefix.
1038 /// 2) The found prefix must be followed by a valid check type suffix using \c
1039 /// FindCheckType above.
1041 /// \returns a pair of StringRefs into the Buffer, which combines:
1042 /// - the first match of the regular expression to satisfy these two is
1043 /// returned,
1044 /// otherwise an empty StringRef is returned to indicate failure.
1045 /// - buffer rewound to the location right after parsed suffix, for parsing
1046 /// to continue from
1048 /// If this routine returns a valid prefix, it will also shrink \p Buffer to
1049 /// start at the beginning of the returned prefix, increment \p LineNumber for
1050 /// each new line consumed from \p Buffer, and set \p CheckTy to the type of
1051 /// check found by examining the suffix.
1053 /// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
1054 /// is unspecified.
1055 static std::pair<StringRef, StringRef>
1056 FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer,
1057 unsigned &LineNumber, Check::FileCheckType &CheckTy) {
1058 SmallVector<StringRef, 2> Matches;
1060 while (!Buffer.empty()) {
1061 // Find the first (longest) match using the RE.
1062 if (!PrefixRE.match(Buffer, &Matches))
1063 // No match at all, bail.
1064 return {StringRef(), StringRef()};
1066 StringRef Prefix = Matches[0];
1067 Matches.clear();
1069 assert(Prefix.data() >= Buffer.data() &&
1070 Prefix.data() < Buffer.data() + Buffer.size() &&
1071 "Prefix doesn't start inside of buffer!");
1072 size_t Loc = Prefix.data() - Buffer.data();
1073 StringRef Skipped = Buffer.substr(0, Loc);
1074 Buffer = Buffer.drop_front(Loc);
1075 LineNumber += Skipped.count('\n');
1077 // Check that the matched prefix isn't a suffix of some other check-like
1078 // word.
1079 // FIXME: This is a very ad-hoc check. it would be better handled in some
1080 // other way. Among other things it seems hard to distinguish between
1081 // intentional and unintentional uses of this feature.
1082 if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
1083 // Now extract the type.
1084 StringRef AfterSuffix;
1085 std::tie(CheckTy, AfterSuffix) = FindCheckType(Buffer, Prefix);
1087 // If we've found a valid check type for this prefix, we're done.
1088 if (CheckTy != Check::CheckNone)
1089 return {Prefix, AfterSuffix};
1092 // If we didn't successfully find a prefix, we need to skip this invalid
1093 // prefix and continue scanning. We directly skip the prefix that was
1094 // matched and any additional parts of that check-like word.
1095 Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
1098 // We ran out of buffer while skipping partial matches so give up.
1099 return {StringRef(), StringRef()};
1102 void FileCheckPatternContext::createLineVariable() {
1103 assert(!LineVariable && "@LINE pseudo numeric variable already created");
1104 StringRef LineName = "@LINE";
1105 LineVariable = makeNumericVariable(0, LineName);
1106 GlobalNumericVariableTable[LineName] = LineVariable;
1109 bool FileCheck::ReadCheckFile(SourceMgr &SM, StringRef Buffer, Regex &PrefixRE,
1110 std::vector<FileCheckString> &CheckStrings) {
1111 Error DefineError =
1112 PatternContext.defineCmdlineVariables(Req.GlobalDefines, SM);
1113 if (DefineError) {
1114 logAllUnhandledErrors(std::move(DefineError), errs());
1115 return true;
1118 PatternContext.createLineVariable();
1120 std::vector<FileCheckPattern> ImplicitNegativeChecks;
1121 for (const auto &PatternString : Req.ImplicitCheckNot) {
1122 // Create a buffer with fake command line content in order to display the
1123 // command line option responsible for the specific implicit CHECK-NOT.
1124 std::string Prefix = "-implicit-check-not='";
1125 std::string Suffix = "'";
1126 std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
1127 Prefix + PatternString + Suffix, "command line");
1129 StringRef PatternInBuffer =
1130 CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
1131 SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
1133 ImplicitNegativeChecks.push_back(
1134 FileCheckPattern(Check::CheckNot, &PatternContext, 0));
1135 ImplicitNegativeChecks.back().parsePattern(PatternInBuffer,
1136 "IMPLICIT-CHECK", SM, Req);
1139 std::vector<FileCheckPattern> DagNotMatches = ImplicitNegativeChecks;
1141 // LineNumber keeps track of the line on which CheckPrefix instances are
1142 // found.
1143 unsigned LineNumber = 1;
1145 while (1) {
1146 Check::FileCheckType CheckTy;
1148 // See if a prefix occurs in the memory buffer.
1149 StringRef UsedPrefix;
1150 StringRef AfterSuffix;
1151 std::tie(UsedPrefix, AfterSuffix) =
1152 FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, CheckTy);
1153 if (UsedPrefix.empty())
1154 break;
1155 assert(UsedPrefix.data() == Buffer.data() &&
1156 "Failed to move Buffer's start forward, or pointed prefix outside "
1157 "of the buffer!");
1158 assert(AfterSuffix.data() >= Buffer.data() &&
1159 AfterSuffix.data() < Buffer.data() + Buffer.size() &&
1160 "Parsing after suffix doesn't start inside of buffer!");
1162 // Location to use for error messages.
1163 const char *UsedPrefixStart = UsedPrefix.data();
1165 // Skip the buffer to the end of parsed suffix (or just prefix, if no good
1166 // suffix was processed).
1167 Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
1168 : AfterSuffix;
1170 // Complain about useful-looking but unsupported suffixes.
1171 if (CheckTy == Check::CheckBadNot) {
1172 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
1173 "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
1174 return true;
1177 // Complain about invalid count specification.
1178 if (CheckTy == Check::CheckBadCount) {
1179 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
1180 "invalid count in -COUNT specification on prefix '" +
1181 UsedPrefix + "'");
1182 return true;
1185 // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
1186 // leading whitespace.
1187 if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
1188 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
1190 // Scan ahead to the end of line.
1191 size_t EOL = Buffer.find_first_of("\n\r");
1193 // Remember the location of the start of the pattern, for diagnostics.
1194 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
1196 // Parse the pattern.
1197 FileCheckPattern P(CheckTy, &PatternContext, LineNumber);
1198 if (P.parsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, Req))
1199 return true;
1201 // Verify that CHECK-LABEL lines do not define or use variables
1202 if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
1203 SM.PrintMessage(
1204 SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
1205 "found '" + UsedPrefix + "-LABEL:'"
1206 " with variable definition or use");
1207 return true;
1210 Buffer = Buffer.substr(EOL);
1212 // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
1213 if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
1214 CheckTy == Check::CheckEmpty) &&
1215 CheckStrings.empty()) {
1216 StringRef Type = CheckTy == Check::CheckNext
1217 ? "NEXT"
1218 : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
1219 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
1220 SourceMgr::DK_Error,
1221 "found '" + UsedPrefix + "-" + Type +
1222 "' without previous '" + UsedPrefix + ": line");
1223 return true;
1226 // Handle CHECK-DAG/-NOT.
1227 if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
1228 DagNotMatches.push_back(P);
1229 continue;
1232 // Okay, add the string we captured to the output vector and move on.
1233 CheckStrings.emplace_back(P, UsedPrefix, PatternLoc);
1234 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1235 DagNotMatches = ImplicitNegativeChecks;
1238 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
1239 // prefix as a filler for the error message.
1240 if (!DagNotMatches.empty()) {
1241 CheckStrings.emplace_back(
1242 FileCheckPattern(Check::CheckEOF, &PatternContext, LineNumber + 1),
1243 *Req.CheckPrefixes.begin(), SMLoc::getFromPointer(Buffer.data()));
1244 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1247 if (CheckStrings.empty()) {
1248 errs() << "error: no check strings found with prefix"
1249 << (Req.CheckPrefixes.size() > 1 ? "es " : " ");
1250 auto I = Req.CheckPrefixes.begin();
1251 auto E = Req.CheckPrefixes.end();
1252 if (I != E) {
1253 errs() << "\'" << *I << ":'";
1254 ++I;
1256 for (; I != E; ++I)
1257 errs() << ", \'" << *I << ":'";
1259 errs() << '\n';
1260 return true;
1263 return false;
1266 static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
1267 StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat,
1268 int MatchedCount, StringRef Buffer, size_t MatchPos,
1269 size_t MatchLen, const FileCheckRequest &Req,
1270 std::vector<FileCheckDiag> *Diags) {
1271 bool PrintDiag = true;
1272 if (ExpectedMatch) {
1273 if (!Req.Verbose)
1274 return;
1275 if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
1276 return;
1277 // Due to their verbosity, we don't print verbose diagnostics here if we're
1278 // gathering them for a different rendering, but we always print other
1279 // diagnostics.
1280 PrintDiag = !Diags;
1282 SMRange MatchRange = ProcessMatchResult(
1283 ExpectedMatch ? FileCheckDiag::MatchFoundAndExpected
1284 : FileCheckDiag::MatchFoundButExcluded,
1285 SM, Loc, Pat.getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
1286 if (!PrintDiag)
1287 return;
1289 std::string Message = formatv("{0}: {1} string found in input",
1290 Pat.getCheckTy().getDescription(Prefix),
1291 (ExpectedMatch ? "expected" : "excluded"))
1292 .str();
1293 if (Pat.getCount() > 1)
1294 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
1296 SM.PrintMessage(
1297 Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
1298 SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
1299 {MatchRange});
1300 Pat.printSubstitutions(SM, Buffer, MatchRange);
1303 static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
1304 const FileCheckString &CheckStr, int MatchedCount,
1305 StringRef Buffer, size_t MatchPos, size_t MatchLen,
1306 FileCheckRequest &Req,
1307 std::vector<FileCheckDiag> *Diags) {
1308 PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
1309 MatchedCount, Buffer, MatchPos, MatchLen, Req, Diags);
1312 static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
1313 StringRef Prefix, SMLoc Loc,
1314 const FileCheckPattern &Pat, int MatchedCount,
1315 StringRef Buffer, bool VerboseVerbose,
1316 std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
1317 assert(MatchErrors && "Called on successful match");
1318 bool PrintDiag = true;
1319 if (!ExpectedMatch) {
1320 if (!VerboseVerbose) {
1321 consumeError(std::move(MatchErrors));
1322 return;
1324 // Due to their verbosity, we don't print verbose diagnostics here if we're
1325 // gathering them for a different rendering, but we always print other
1326 // diagnostics.
1327 PrintDiag = !Diags;
1330 // If the current position is at the end of a line, advance to the start of
1331 // the next line.
1332 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
1333 SMRange SearchRange = ProcessMatchResult(
1334 ExpectedMatch ? FileCheckDiag::MatchNoneButExpected
1335 : FileCheckDiag::MatchNoneAndExcluded,
1336 SM, Loc, Pat.getCheckTy(), Buffer, 0, Buffer.size(), Diags);
1337 if (!PrintDiag) {
1338 consumeError(std::move(MatchErrors));
1339 return;
1342 MatchErrors =
1343 handleErrors(std::move(MatchErrors),
1344 [](const FileCheckErrorDiagnostic &E) { E.log(errs()); });
1346 // No problem matching the string per se.
1347 if (!MatchErrors)
1348 return;
1349 consumeError(std::move(MatchErrors));
1351 // Print "not found" diagnostic.
1352 std::string Message = formatv("{0}: {1} string not found in input",
1353 Pat.getCheckTy().getDescription(Prefix),
1354 (ExpectedMatch ? "expected" : "excluded"))
1355 .str();
1356 if (Pat.getCount() > 1)
1357 Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
1358 SM.PrintMessage(
1359 Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
1361 // Print the "scanning from here" line.
1362 SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
1364 // Allow the pattern to print additional information if desired.
1365 Pat.printSubstitutions(SM, Buffer);
1367 if (ExpectedMatch)
1368 Pat.printFuzzyMatch(SM, Buffer, Diags);
1371 static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
1372 const FileCheckString &CheckStr, int MatchedCount,
1373 StringRef Buffer, bool VerboseVerbose,
1374 std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
1375 PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
1376 MatchedCount, Buffer, VerboseVerbose, Diags,
1377 std::move(MatchErrors));
1380 /// Counts the number of newlines in the specified range.
1381 static unsigned CountNumNewlinesBetween(StringRef Range,
1382 const char *&FirstNewLine) {
1383 unsigned NumNewLines = 0;
1384 while (1) {
1385 // Scan for newline.
1386 Range = Range.substr(Range.find_first_of("\n\r"));
1387 if (Range.empty())
1388 return NumNewLines;
1390 ++NumNewLines;
1392 // Handle \n\r and \r\n as a single newline.
1393 if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
1394 (Range[0] != Range[1]))
1395 Range = Range.substr(1);
1396 Range = Range.substr(1);
1398 if (NumNewLines == 1)
1399 FirstNewLine = Range.begin();
1403 size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
1404 bool IsLabelScanMode, size_t &MatchLen,
1405 FileCheckRequest &Req,
1406 std::vector<FileCheckDiag> *Diags) const {
1407 size_t LastPos = 0;
1408 std::vector<const FileCheckPattern *> NotStrings;
1410 // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
1411 // bounds; we have not processed variable definitions within the bounded block
1412 // yet so cannot handle any final CHECK-DAG yet; this is handled when going
1413 // over the block again (including the last CHECK-LABEL) in normal mode.
1414 if (!IsLabelScanMode) {
1415 // Match "dag strings" (with mixed "not strings" if any).
1416 LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
1417 if (LastPos == StringRef::npos)
1418 return StringRef::npos;
1421 // Match itself from the last position after matching CHECK-DAG.
1422 size_t LastMatchEnd = LastPos;
1423 size_t FirstMatchPos = 0;
1424 // Go match the pattern Count times. Majority of patterns only match with
1425 // count 1 though.
1426 assert(Pat.getCount() != 0 && "pattern count can not be zero");
1427 for (int i = 1; i <= Pat.getCount(); i++) {
1428 StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
1429 size_t CurrentMatchLen;
1430 // get a match at current start point
1431 Expected<size_t> MatchResult = Pat.match(MatchBuffer, CurrentMatchLen, SM);
1433 // report
1434 if (!MatchResult) {
1435 PrintNoMatch(true, SM, *this, i, MatchBuffer, Req.VerboseVerbose, Diags,
1436 MatchResult.takeError());
1437 return StringRef::npos;
1439 size_t MatchPos = *MatchResult;
1440 PrintMatch(true, SM, *this, i, MatchBuffer, MatchPos, CurrentMatchLen, Req,
1441 Diags);
1442 if (i == 1)
1443 FirstMatchPos = LastPos + MatchPos;
1445 // move start point after the match
1446 LastMatchEnd += MatchPos + CurrentMatchLen;
1448 // Full match len counts from first match pos.
1449 MatchLen = LastMatchEnd - FirstMatchPos;
1451 // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1452 // or CHECK-NOT
1453 if (!IsLabelScanMode) {
1454 size_t MatchPos = FirstMatchPos - LastPos;
1455 StringRef MatchBuffer = Buffer.substr(LastPos);
1456 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1458 // If this check is a "CHECK-NEXT", verify that the previous match was on
1459 // the previous line (i.e. that there is one newline between them).
1460 if (CheckNext(SM, SkippedRegion)) {
1461 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
1462 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
1463 Diags, Req.Verbose);
1464 return StringRef::npos;
1467 // If this check is a "CHECK-SAME", verify that the previous match was on
1468 // the same line (i.e. that there is no newline between them).
1469 if (CheckSame(SM, SkippedRegion)) {
1470 ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
1471 Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
1472 Diags, Req.Verbose);
1473 return StringRef::npos;
1476 // If this match had "not strings", verify that they don't exist in the
1477 // skipped region.
1478 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
1479 return StringRef::npos;
1482 return FirstMatchPos;
1485 bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1486 if (Pat.getCheckTy() != Check::CheckNext &&
1487 Pat.getCheckTy() != Check::CheckEmpty)
1488 return false;
1490 Twine CheckName =
1491 Prefix +
1492 Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
1494 // Count the number of newlines between the previous match and this one.
1495 const char *FirstNewLine = nullptr;
1496 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1498 if (NumNewLines == 0) {
1499 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1500 CheckName + ": is on the same line as previous match");
1501 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1502 "'next' match was here");
1503 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1504 "previous match ended here");
1505 return true;
1508 if (NumNewLines != 1) {
1509 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1510 CheckName +
1511 ": is not on the line after the previous match");
1512 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1513 "'next' match was here");
1514 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1515 "previous match ended here");
1516 SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
1517 "non-matching line after previous match is here");
1518 return true;
1521 return false;
1524 bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
1525 if (Pat.getCheckTy() != Check::CheckSame)
1526 return false;
1528 // Count the number of newlines between the previous match and this one.
1529 const char *FirstNewLine = nullptr;
1530 unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1532 if (NumNewLines != 0) {
1533 SM.PrintMessage(Loc, SourceMgr::DK_Error,
1534 Prefix +
1535 "-SAME: is not on the same line as the previous match");
1536 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1537 "'next' match was here");
1538 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1539 "previous match ended here");
1540 return true;
1543 return false;
1546 bool FileCheckString::CheckNot(
1547 const SourceMgr &SM, StringRef Buffer,
1548 const std::vector<const FileCheckPattern *> &NotStrings,
1549 const FileCheckRequest &Req, std::vector<FileCheckDiag> *Diags) const {
1550 for (const FileCheckPattern *Pat : NotStrings) {
1551 assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1553 size_t MatchLen = 0;
1554 Expected<size_t> MatchResult = Pat->match(Buffer, MatchLen, SM);
1556 if (!MatchResult) {
1557 PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
1558 Req.VerboseVerbose, Diags, MatchResult.takeError());
1559 continue;
1561 size_t Pos = *MatchResult;
1563 PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, Pos, MatchLen,
1564 Req, Diags);
1566 return true;
1569 return false;
1572 size_t
1573 FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1574 std::vector<const FileCheckPattern *> &NotStrings,
1575 const FileCheckRequest &Req,
1576 std::vector<FileCheckDiag> *Diags) const {
1577 if (DagNotStrings.empty())
1578 return 0;
1580 // The start of the search range.
1581 size_t StartPos = 0;
1583 struct MatchRange {
1584 size_t Pos;
1585 size_t End;
1587 // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
1588 // ranges are erased from this list once they are no longer in the search
1589 // range.
1590 std::list<MatchRange> MatchRanges;
1592 // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
1593 // group, so we don't use a range-based for loop here.
1594 for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
1595 PatItr != PatEnd; ++PatItr) {
1596 const FileCheckPattern &Pat = *PatItr;
1597 assert((Pat.getCheckTy() == Check::CheckDAG ||
1598 Pat.getCheckTy() == Check::CheckNot) &&
1599 "Invalid CHECK-DAG or CHECK-NOT!");
1601 if (Pat.getCheckTy() == Check::CheckNot) {
1602 NotStrings.push_back(&Pat);
1603 continue;
1606 assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1608 // CHECK-DAG always matches from the start.
1609 size_t MatchLen = 0, MatchPos = StartPos;
1611 // Search for a match that doesn't overlap a previous match in this
1612 // CHECK-DAG group.
1613 for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
1614 StringRef MatchBuffer = Buffer.substr(MatchPos);
1615 Expected<size_t> MatchResult = Pat.match(MatchBuffer, MatchLen, SM);
1616 // With a group of CHECK-DAGs, a single mismatching means the match on
1617 // that group of CHECK-DAGs fails immediately.
1618 if (!MatchResult) {
1619 PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
1620 Req.VerboseVerbose, Diags, MatchResult.takeError());
1621 return StringRef::npos;
1623 size_t MatchPosBuf = *MatchResult;
1624 // Re-calc it as the offset relative to the start of the original string.
1625 MatchPos += MatchPosBuf;
1626 if (Req.VerboseVerbose)
1627 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1628 MatchLen, Req, Diags);
1629 MatchRange M{MatchPos, MatchPos + MatchLen};
1630 if (Req.AllowDeprecatedDagOverlap) {
1631 // We don't need to track all matches in this mode, so we just maintain
1632 // one match range that encompasses the current CHECK-DAG group's
1633 // matches.
1634 if (MatchRanges.empty())
1635 MatchRanges.insert(MatchRanges.end(), M);
1636 else {
1637 auto Block = MatchRanges.begin();
1638 Block->Pos = std::min(Block->Pos, M.Pos);
1639 Block->End = std::max(Block->End, M.End);
1641 break;
1643 // Iterate previous matches until overlapping match or insertion point.
1644 bool Overlap = false;
1645 for (; MI != ME; ++MI) {
1646 if (M.Pos < MI->End) {
1647 // !Overlap => New match has no overlap and is before this old match.
1648 // Overlap => New match overlaps this old match.
1649 Overlap = MI->Pos < M.End;
1650 break;
1653 if (!Overlap) {
1654 // Insert non-overlapping match into list.
1655 MatchRanges.insert(MI, M);
1656 break;
1658 if (Req.VerboseVerbose) {
1659 // Due to their verbosity, we don't print verbose diagnostics here if
1660 // we're gathering them for a different rendering, but we always print
1661 // other diagnostics.
1662 if (!Diags) {
1663 SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
1664 SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
1665 SMRange OldRange(OldStart, OldEnd);
1666 SM.PrintMessage(OldStart, SourceMgr::DK_Note,
1667 "match discarded, overlaps earlier DAG match here",
1668 {OldRange});
1669 } else
1670 Diags->rbegin()->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
1672 MatchPos = MI->End;
1674 if (!Req.VerboseVerbose)
1675 PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1676 MatchLen, Req, Diags);
1678 // Handle the end of a CHECK-DAG group.
1679 if (std::next(PatItr) == PatEnd ||
1680 std::next(PatItr)->getCheckTy() == Check::CheckNot) {
1681 if (!NotStrings.empty()) {
1682 // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
1683 // CHECK-DAG, verify that there are no 'not' strings occurred in that
1684 // region.
1685 StringRef SkippedRegion =
1686 Buffer.slice(StartPos, MatchRanges.begin()->Pos);
1687 if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
1688 return StringRef::npos;
1689 // Clear "not strings".
1690 NotStrings.clear();
1692 // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
1693 // end of this CHECK-DAG group's match range.
1694 StartPos = MatchRanges.rbegin()->End;
1695 // Don't waste time checking for (impossible) overlaps before that.
1696 MatchRanges.clear();
1700 return StartPos;
1703 // A check prefix must contain only alphanumeric, hyphens and underscores.
1704 static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1705 Regex Validator("^[a-zA-Z0-9_-]*$");
1706 return Validator.match(CheckPrefix);
1709 bool FileCheck::ValidateCheckPrefixes() {
1710 StringSet<> PrefixSet;
1712 for (StringRef Prefix : Req.CheckPrefixes) {
1713 // Reject empty prefixes.
1714 if (Prefix == "")
1715 return false;
1717 if (!PrefixSet.insert(Prefix).second)
1718 return false;
1720 if (!ValidateCheckPrefix(Prefix))
1721 return false;
1724 return true;
1727 Regex FileCheck::buildCheckPrefixRegex() {
1728 // I don't think there's a way to specify an initial value for cl::list,
1729 // so if nothing was specified, add the default
1730 if (Req.CheckPrefixes.empty())
1731 Req.CheckPrefixes.push_back("CHECK");
1733 // We already validated the contents of CheckPrefixes so just concatenate
1734 // them as alternatives.
1735 SmallString<32> PrefixRegexStr;
1736 for (StringRef Prefix : Req.CheckPrefixes) {
1737 if (Prefix != Req.CheckPrefixes.front())
1738 PrefixRegexStr.push_back('|');
1740 PrefixRegexStr.append(Prefix);
1743 return Regex(PrefixRegexStr);
1746 Error FileCheckPatternContext::defineCmdlineVariables(
1747 std::vector<std::string> &CmdlineDefines, SourceMgr &SM) {
1748 assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
1749 "Overriding defined variable with command-line variable definitions");
1751 if (CmdlineDefines.empty())
1752 return Error::success();
1754 // Create a string representing the vector of command-line definitions. Each
1755 // definition is on its own line and prefixed with a definition number to
1756 // clarify which definition a given diagnostic corresponds to.
1757 unsigned I = 0;
1758 Error Errs = Error::success();
1759 std::string CmdlineDefsDiag;
1760 StringRef Prefix1 = "Global define #";
1761 StringRef Prefix2 = ": ";
1762 for (StringRef CmdlineDef : CmdlineDefines)
1763 CmdlineDefsDiag +=
1764 (Prefix1 + Twine(++I) + Prefix2 + CmdlineDef + "\n").str();
1766 // Create a buffer with fake command line content in order to display
1767 // parsing diagnostic with location information and point to the
1768 // global definition with invalid syntax.
1769 std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
1770 MemoryBuffer::getMemBufferCopy(CmdlineDefsDiag, "Global defines");
1771 StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
1772 SM.AddNewSourceBuffer(std::move(CmdLineDefsDiagBuffer), SMLoc());
1774 SmallVector<StringRef, 4> CmdlineDefsDiagVec;
1775 CmdlineDefsDiagRef.split(CmdlineDefsDiagVec, '\n', -1 /*MaxSplit*/,
1776 false /*KeepEmpty*/);
1777 for (StringRef CmdlineDefDiag : CmdlineDefsDiagVec) {
1778 unsigned DefStart = CmdlineDefDiag.find(Prefix2) + Prefix2.size();
1779 StringRef CmdlineDef = CmdlineDefDiag.substr(DefStart);
1780 size_t EqIdx = CmdlineDef.find('=');
1781 if (EqIdx == StringRef::npos) {
1782 Errs = joinErrors(
1783 std::move(Errs),
1784 FileCheckErrorDiagnostic::get(
1785 SM, CmdlineDef, "missing equal sign in global definition"));
1786 continue;
1789 // Numeric variable definition.
1790 if (CmdlineDef[0] == '#') {
1791 StringRef CmdlineName = CmdlineDef.substr(1, EqIdx - 1);
1792 Expected<FileCheckNumericVariable *> ParseResult =
1793 FileCheckPattern::parseNumericVariableDefinition(CmdlineName, this, 0,
1794 SM);
1795 if (!ParseResult) {
1796 Errs = joinErrors(std::move(Errs), ParseResult.takeError());
1797 continue;
1800 StringRef CmdlineVal = CmdlineDef.substr(EqIdx + 1);
1801 uint64_t Val;
1802 if (CmdlineVal.getAsInteger(10, Val)) {
1803 Errs = joinErrors(std::move(Errs),
1804 FileCheckErrorDiagnostic::get(
1805 SM, CmdlineVal,
1806 "invalid value in numeric variable definition '" +
1807 CmdlineVal + "'"));
1808 continue;
1810 FileCheckNumericVariable *DefinedNumericVariable = *ParseResult;
1811 DefinedNumericVariable->setValue(Val);
1813 // Record this variable definition.
1814 GlobalNumericVariableTable[DefinedNumericVariable->getName()] =
1815 DefinedNumericVariable;
1816 } else {
1817 // String variable definition.
1818 std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.split('=');
1819 StringRef CmdlineName = CmdlineNameVal.first;
1820 StringRef OrigCmdlineName = CmdlineName;
1821 Expected<FileCheckPattern::VariableProperties> ParseVarResult =
1822 FileCheckPattern::parseVariable(CmdlineName, SM);
1823 if (!ParseVarResult) {
1824 Errs = joinErrors(std::move(Errs), ParseVarResult.takeError());
1825 continue;
1827 // Check that CmdlineName does not denote a pseudo variable is only
1828 // composed of the parsed numeric variable. This catches cases like
1829 // "FOO+2" in a "FOO+2=10" definition.
1830 if (ParseVarResult->IsPseudo || !CmdlineName.empty()) {
1831 Errs = joinErrors(std::move(Errs),
1832 FileCheckErrorDiagnostic::get(
1833 SM, OrigCmdlineName,
1834 "invalid name in string variable definition '" +
1835 OrigCmdlineName + "'"));
1836 continue;
1838 StringRef Name = ParseVarResult->Name;
1840 // Detect collisions between string and numeric variables when the former
1841 // is created later than the latter.
1842 if (GlobalNumericVariableTable.find(Name) !=
1843 GlobalNumericVariableTable.end()) {
1844 Errs = joinErrors(std::move(Errs), FileCheckErrorDiagnostic::get(
1845 SM, Name,
1846 "numeric variable with name '" +
1847 Name + "' already exists"));
1848 continue;
1850 GlobalVariableTable.insert(CmdlineNameVal);
1851 // Mark the string variable as defined to detect collisions between
1852 // string and numeric variables in DefineCmdlineVariables when the latter
1853 // is created later than the former. We cannot reuse GlobalVariableTable
1854 // for this by populating it with an empty string since we would then
1855 // lose the ability to detect the use of an undefined variable in
1856 // match().
1857 DefinedVariableTable[Name] = true;
1861 return Errs;
1864 void FileCheckPatternContext::clearLocalVars() {
1865 SmallVector<StringRef, 16> LocalPatternVars, LocalNumericVars;
1866 for (const StringMapEntry<StringRef> &Var : GlobalVariableTable)
1867 if (Var.first()[0] != '$')
1868 LocalPatternVars.push_back(Var.first());
1870 // Numeric substitution reads the value of a variable directly, not via
1871 // GlobalNumericVariableTable. Therefore, we clear local variables by
1872 // clearing their value which will lead to a numeric substitution failure. We
1873 // also mark the variable for removal from GlobalNumericVariableTable since
1874 // this is what defineCmdlineVariables checks to decide that no global
1875 // variable has been defined.
1876 for (const auto &Var : GlobalNumericVariableTable)
1877 if (Var.first()[0] != '$') {
1878 Var.getValue()->clearValue();
1879 LocalNumericVars.push_back(Var.first());
1882 for (const auto &Var : LocalPatternVars)
1883 GlobalVariableTable.erase(Var);
1884 for (const auto &Var : LocalNumericVars)
1885 GlobalNumericVariableTable.erase(Var);
1888 bool FileCheck::CheckInput(SourceMgr &SM, StringRef Buffer,
1889 ArrayRef<FileCheckString> CheckStrings,
1890 std::vector<FileCheckDiag> *Diags) {
1891 bool ChecksFailed = false;
1893 unsigned i = 0, j = 0, e = CheckStrings.size();
1894 while (true) {
1895 StringRef CheckRegion;
1896 if (j == e) {
1897 CheckRegion = Buffer;
1898 } else {
1899 const FileCheckString &CheckLabelStr = CheckStrings[j];
1900 if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
1901 ++j;
1902 continue;
1905 // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1906 size_t MatchLabelLen = 0;
1907 size_t MatchLabelPos =
1908 CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, Req, Diags);
1909 if (MatchLabelPos == StringRef::npos)
1910 // Immediately bail if CHECK-LABEL fails, nothing else we can do.
1911 return false;
1913 CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1914 Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1915 ++j;
1918 // Do not clear the first region as it's the one before the first
1919 // CHECK-LABEL and it would clear variables defined on the command-line
1920 // before they get used.
1921 if (i != 0 && Req.EnableVarScope)
1922 PatternContext.clearLocalVars();
1924 for (; i != j; ++i) {
1925 const FileCheckString &CheckStr = CheckStrings[i];
1927 // Check each string within the scanned region, including a second check
1928 // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1929 size_t MatchLen = 0;
1930 size_t MatchPos =
1931 CheckStr.Check(SM, CheckRegion, false, MatchLen, Req, Diags);
1933 if (MatchPos == StringRef::npos) {
1934 ChecksFailed = true;
1935 i = j;
1936 break;
1939 CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1942 if (j == e)
1943 break;
1946 // Success if no checks failed.
1947 return !ChecksFailed;