xref: /llvm-project/llvm/lib/FileCheck/FileCheck.cpp (revision 0726cb00471850ead0835e5d3806c7aef5bb0b21)
1 //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // FileCheck does a line-by line check of a file that validates whether it
10 // contains the expected content.  This is useful for regression tests etc.
11 //
12 // This file implements most of the API that will be used by the FileCheck utility
13 // as well as various unittests.
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/FileCheck/FileCheck.h"
17 #include "FileCheckImpl.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSet.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/CheckedArithmetic.h"
23 #include "llvm/Support/FormatVariadic.h"
24 #include <cstdint>
25 #include <list>
26 #include <set>
27 #include <tuple>
28 #include <utility>
29 
30 using namespace llvm;
31 
32 StringRef ExpressionFormat::toString() const {
33   switch (Value) {
34   case Kind::NoFormat:
35     return StringRef("<none>");
36   case Kind::Unsigned:
37     return StringRef("%u");
38   case Kind::Signed:
39     return StringRef("%d");
40   case Kind::HexUpper:
41     return StringRef("%X");
42   case Kind::HexLower:
43     return StringRef("%x");
44   }
45   llvm_unreachable("unknown expression format");
46 }
47 
48 Expected<std::string> ExpressionFormat::getWildcardRegex() const {
49   StringRef AlternateFormPrefix = AlternateForm ? StringRef("0x") : StringRef();
50 
51   auto CreatePrecisionRegex = [&](StringRef S) {
52     return (Twine(AlternateFormPrefix) + S + Twine('{') + Twine(Precision) +
53             "}")
54         .str();
55   };
56 
57   switch (Value) {
58   case Kind::Unsigned:
59     if (Precision)
60       return CreatePrecisionRegex("([1-9][0-9]*)?[0-9]");
61     return std::string("[0-9]+");
62   case Kind::Signed:
63     if (Precision)
64       return CreatePrecisionRegex("-?([1-9][0-9]*)?[0-9]");
65     return std::string("-?[0-9]+");
66   case Kind::HexUpper:
67     if (Precision)
68       return CreatePrecisionRegex("([1-9A-F][0-9A-F]*)?[0-9A-F]");
69     return (Twine(AlternateFormPrefix) + Twine("[0-9A-F]+")).str();
70   case Kind::HexLower:
71     if (Precision)
72       return CreatePrecisionRegex("([1-9a-f][0-9a-f]*)?[0-9a-f]");
73     return (Twine(AlternateFormPrefix) + Twine("[0-9a-f]+")).str();
74   default:
75     return createStringError(std::errc::invalid_argument,
76                              "trying to match value with invalid format");
77   }
78 }
79 
80 Expected<std::string>
81 ExpressionFormat::getMatchingString(ExpressionValue IntegerValue) const {
82   APInt IntValue = IntegerValue.getAPIntValue();
83   if (Value != Kind::Signed && IntValue.isNegative())
84     return make_error<OverflowError>();
85 
86   unsigned Radix;
87   bool UpperCase = false;
88   SmallString<8> AbsoluteValueStr;
89   StringRef SignPrefix = IntValue.isNegative() ? "-" : "";
90   switch (Value) {
91   case Kind::Unsigned:
92   case Kind::Signed:
93     Radix = 10;
94     break;
95   case Kind::HexUpper:
96     UpperCase = true;
97     Radix = 16;
98     break;
99   case Kind::HexLower:
100     Radix = 16;
101     UpperCase = false;
102     break;
103   default:
104     return createStringError(std::errc::invalid_argument,
105                              "trying to match value with invalid format");
106   }
107   IntValue.abs().toString(AbsoluteValueStr, Radix, /*Signed=*/false,
108                           /*formatAsCLiteral=*/false,
109                           /*UpperCase=*/UpperCase);
110 
111   StringRef AlternateFormPrefix = AlternateForm ? StringRef("0x") : StringRef();
112 
113   if (Precision > AbsoluteValueStr.size()) {
114     unsigned LeadingZeros = Precision - AbsoluteValueStr.size();
115     return (Twine(SignPrefix) + Twine(AlternateFormPrefix) +
116             std::string(LeadingZeros, '0') + AbsoluteValueStr)
117         .str();
118   }
119 
120   return (Twine(SignPrefix) + Twine(AlternateFormPrefix) + AbsoluteValueStr)
121       .str();
122 }
123 
124 static unsigned nextAPIntBitWidth(unsigned BitWidth) {
125   return (BitWidth < APInt::APINT_BITS_PER_WORD) ? APInt::APINT_BITS_PER_WORD
126                                                  : BitWidth * 2;
127 }
128 
129 static APInt toSigned(APInt AbsVal, bool Negative) {
130   if (AbsVal.isSignBitSet())
131     AbsVal = AbsVal.zext(nextAPIntBitWidth(AbsVal.getBitWidth()));
132   APInt Result = AbsVal;
133   if (Negative)
134     Result.negate();
135   return Result;
136 }
137 
138 Expected<ExpressionValue>
139 ExpressionFormat::valueFromStringRepr(StringRef StrVal,
140                                       const SourceMgr &SM) const {
141   bool ValueIsSigned = Value == Kind::Signed;
142   // Both the FileCheck utility and library only call this method with a valid
143   // value in StrVal. This is guaranteed by the regex returned by
144   // getWildcardRegex() above. Only underflow and overflow errors can thus
145   // occur. However new uses of this method could be added in the future so
146   // the error message does not make assumptions about StrVal.
147   bool Negative = StrVal.consume_front("-");
148   bool Hex = Value == Kind::HexUpper || Value == Kind::HexLower;
149   bool MissingFormPrefix =
150       !ValueIsSigned && AlternateForm && !StrVal.consume_front("0x");
151   (void)MissingFormPrefix;
152   assert(!MissingFormPrefix && "missing alternate form prefix");
153   APInt ResultValue;
154   bool ParseFailure = StrVal.getAsInteger(Hex ? 16 : 10, ResultValue);
155   if (ParseFailure)
156     return ErrorDiagnostic::get(SM, StrVal,
157                                 "unable to represent numeric value");
158   return ExpressionValue(toSigned(ResultValue, Negative));
159 }
160 
161 Expected<ExpressionValue> llvm::exprAdd(const ExpressionValue &LeftOperand,
162                                         const ExpressionValue &RightOperand,
163                                         bool &Overflow) {
164   APInt Result = LeftOperand.getAPIntValue().sadd_ov(
165       RightOperand.getAPIntValue(), Overflow);
166   return ExpressionValue(Result);
167 }
168 
169 Expected<ExpressionValue> llvm::exprSub(const ExpressionValue &LeftOperand,
170                                         const ExpressionValue &RightOperand,
171                                         bool &Overflow) {
172   APInt Result = LeftOperand.getAPIntValue().ssub_ov(
173       RightOperand.getAPIntValue(), Overflow);
174   return ExpressionValue(Result);
175 }
176 
177 Expected<ExpressionValue> llvm::exprMul(const ExpressionValue &LeftOperand,
178                                         const ExpressionValue &RightOperand,
179                                         bool &Overflow) {
180   APInt Result = LeftOperand.getAPIntValue().smul_ov(
181       RightOperand.getAPIntValue(), Overflow);
182   return ExpressionValue(Result);
183 }
184 
185 Expected<ExpressionValue> llvm::exprDiv(const ExpressionValue &LeftOperand,
186                                         const ExpressionValue &RightOperand,
187                                         bool &Overflow) {
188   // Check for division by zero.
189   if (RightOperand.getAPIntValue().isZero())
190     return make_error<OverflowError>();
191 
192   APInt Result = LeftOperand.getAPIntValue().sdiv_ov(
193       RightOperand.getAPIntValue(), Overflow);
194   return ExpressionValue(Result);
195 }
196 
197 Expected<ExpressionValue> llvm::exprMax(const ExpressionValue &LeftOperand,
198                                         const ExpressionValue &RightOperand,
199                                         bool &Overflow) {
200   Overflow = false;
201   return LeftOperand.getAPIntValue().slt(RightOperand.getAPIntValue())
202              ? RightOperand
203              : LeftOperand;
204 }
205 
206 Expected<ExpressionValue> llvm::exprMin(const ExpressionValue &LeftOperand,
207                                         const ExpressionValue &RightOperand,
208                                         bool &Overflow) {
209   Overflow = false;
210   if (cantFail(exprMax(LeftOperand, RightOperand, Overflow)).getAPIntValue() ==
211       LeftOperand.getAPIntValue())
212     return RightOperand;
213 
214   return LeftOperand;
215 }
216 
217 Expected<ExpressionValue> NumericVariableUse::eval() const {
218   std::optional<ExpressionValue> Value = Variable->getValue();
219   if (Value)
220     return *Value;
221 
222   return make_error<UndefVarError>(getExpressionStr());
223 }
224 
225 Expected<ExpressionValue> BinaryOperation::eval() const {
226   Expected<ExpressionValue> MaybeLeftOp = LeftOperand->eval();
227   Expected<ExpressionValue> MaybeRightOp = RightOperand->eval();
228 
229   // Bubble up any error (e.g. undefined variables) in the recursive
230   // evaluation.
231   if (!MaybeLeftOp || !MaybeRightOp) {
232     Error Err = Error::success();
233     if (!MaybeLeftOp)
234       Err = joinErrors(std::move(Err), MaybeLeftOp.takeError());
235     if (!MaybeRightOp)
236       Err = joinErrors(std::move(Err), MaybeRightOp.takeError());
237     return std::move(Err);
238   }
239 
240   APInt LeftOp = MaybeLeftOp->getAPIntValue();
241   APInt RightOp = MaybeRightOp->getAPIntValue();
242   bool Overflow;
243   // Ensure both operands have the same bitwidth.
244   unsigned LeftBitWidth = LeftOp.getBitWidth();
245   unsigned RightBitWidth = RightOp.getBitWidth();
246   unsigned NewBitWidth = std::max(LeftBitWidth, RightBitWidth);
247   LeftOp = LeftOp.sext(NewBitWidth);
248   RightOp = RightOp.sext(NewBitWidth);
249   do {
250     Expected<ExpressionValue> MaybeResult =
251         EvalBinop(ExpressionValue(LeftOp), ExpressionValue(RightOp), Overflow);
252     if (!MaybeResult)
253       return MaybeResult.takeError();
254 
255     if (!Overflow)
256       return MaybeResult;
257 
258     NewBitWidth = nextAPIntBitWidth(NewBitWidth);
259     LeftOp = LeftOp.sext(NewBitWidth);
260     RightOp = RightOp.sext(NewBitWidth);
261   } while (true);
262 }
263 
264 Expected<ExpressionFormat>
265 BinaryOperation::getImplicitFormat(const SourceMgr &SM) const {
266   Expected<ExpressionFormat> LeftFormat = LeftOperand->getImplicitFormat(SM);
267   Expected<ExpressionFormat> RightFormat = RightOperand->getImplicitFormat(SM);
268   if (!LeftFormat || !RightFormat) {
269     Error Err = Error::success();
270     if (!LeftFormat)
271       Err = joinErrors(std::move(Err), LeftFormat.takeError());
272     if (!RightFormat)
273       Err = joinErrors(std::move(Err), RightFormat.takeError());
274     return std::move(Err);
275   }
276 
277   if (*LeftFormat != ExpressionFormat::Kind::NoFormat &&
278       *RightFormat != ExpressionFormat::Kind::NoFormat &&
279       *LeftFormat != *RightFormat)
280     return ErrorDiagnostic::get(
281         SM, getExpressionStr(),
282         "implicit format conflict between '" + LeftOperand->getExpressionStr() +
283             "' (" + LeftFormat->toString() + ") and '" +
284             RightOperand->getExpressionStr() + "' (" + RightFormat->toString() +
285             "), need an explicit format specifier");
286 
287   return *LeftFormat != ExpressionFormat::Kind::NoFormat ? *LeftFormat
288                                                          : *RightFormat;
289 }
290 
291 Expected<std::string> NumericSubstitution::getResult() const {
292   assert(ExpressionPointer->getAST() != nullptr &&
293          "Substituting empty expression");
294   Expected<ExpressionValue> EvaluatedValue =
295       ExpressionPointer->getAST()->eval();
296   if (!EvaluatedValue)
297     return EvaluatedValue.takeError();
298   ExpressionFormat Format = ExpressionPointer->getFormat();
299   return Format.getMatchingString(*EvaluatedValue);
300 }
301 
302 Expected<std::string> StringSubstitution::getResult() const {
303   // Look up the value and escape it so that we can put it into the regex.
304   Expected<StringRef> VarVal = Context->getPatternVarValue(FromStr);
305   if (!VarVal)
306     return VarVal.takeError();
307   return Regex::escape(*VarVal);
308 }
309 
310 bool Pattern::isValidVarNameStart(char C) { return C == '_' || isAlpha(C); }
311 
312 Expected<Pattern::VariableProperties>
313 Pattern::parseVariable(StringRef &Str, const SourceMgr &SM) {
314   if (Str.empty())
315     return ErrorDiagnostic::get(SM, Str, "empty variable name");
316 
317   size_t I = 0;
318   bool IsPseudo = Str[0] == '@';
319 
320   // Global vars start with '$'.
321   if (Str[0] == '$' || IsPseudo)
322     ++I;
323 
324   if (!isValidVarNameStart(Str[I++]))
325     return ErrorDiagnostic::get(SM, Str, "invalid variable name");
326 
327   for (size_t E = Str.size(); I != E; ++I)
328     // Variable names are composed of alphanumeric characters and underscores.
329     if (Str[I] != '_' && !isAlnum(Str[I]))
330       break;
331 
332   StringRef Name = Str.take_front(I);
333   Str = Str.substr(I);
334   return VariableProperties {Name, IsPseudo};
335 }
336 
337 // StringRef holding all characters considered as horizontal whitespaces by
338 // FileCheck input canonicalization.
339 constexpr StringLiteral SpaceChars = " \t";
340 
341 // Parsing helper function that strips the first character in S and returns it.
342 static char popFront(StringRef &S) {
343   char C = S.front();
344   S = S.drop_front();
345   return C;
346 }
347 
348 char OverflowError::ID = 0;
349 char UndefVarError::ID = 0;
350 char ErrorDiagnostic::ID = 0;
351 char NotFoundError::ID = 0;
352 char ErrorReported::ID = 0;
353 
354 Expected<NumericVariable *> Pattern::parseNumericVariableDefinition(
355     StringRef &Expr, FileCheckPatternContext *Context,
356     std::optional<size_t> LineNumber, ExpressionFormat ImplicitFormat,
357     const SourceMgr &SM) {
358   Expected<VariableProperties> ParseVarResult = parseVariable(Expr, SM);
359   if (!ParseVarResult)
360     return ParseVarResult.takeError();
361   StringRef Name = ParseVarResult->Name;
362 
363   if (ParseVarResult->IsPseudo)
364     return ErrorDiagnostic::get(
365         SM, Name, "definition of pseudo numeric variable unsupported");
366 
367   // Detect collisions between string and numeric variables when the latter
368   // is created later than the former.
369   if (Context->DefinedVariableTable.contains(Name))
370     return ErrorDiagnostic::get(
371         SM, Name, "string variable with name '" + Name + "' already exists");
372 
373   Expr = Expr.ltrim(SpaceChars);
374   if (!Expr.empty())
375     return ErrorDiagnostic::get(
376         SM, Expr, "unexpected characters after numeric variable name");
377 
378   NumericVariable *DefinedNumericVariable;
379   auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
380   if (VarTableIter != Context->GlobalNumericVariableTable.end()) {
381     DefinedNumericVariable = VarTableIter->second;
382     if (DefinedNumericVariable->getImplicitFormat() != ImplicitFormat)
383       return ErrorDiagnostic::get(
384           SM, Expr, "format different from previous variable definition");
385   } else
386     DefinedNumericVariable =
387         Context->makeNumericVariable(Name, ImplicitFormat, LineNumber);
388 
389   return DefinedNumericVariable;
390 }
391 
392 Expected<std::unique_ptr<NumericVariableUse>> Pattern::parseNumericVariableUse(
393     StringRef Name, bool IsPseudo, std::optional<size_t> LineNumber,
394     FileCheckPatternContext *Context, const SourceMgr &SM) {
395   if (IsPseudo && !Name.equals("@LINE"))
396     return ErrorDiagnostic::get(
397         SM, Name, "invalid pseudo numeric variable '" + Name + "'");
398 
399   // Numeric variable definitions and uses are parsed in the order in which
400   // they appear in the CHECK patterns. For each definition, the pointer to the
401   // class instance of the corresponding numeric variable definition is stored
402   // in GlobalNumericVariableTable in parsePattern. Therefore, if the pointer
403   // we get below is null, it means no such variable was defined before. When
404   // that happens, we create a dummy variable so that parsing can continue. All
405   // uses of undefined variables, whether string or numeric, are then diagnosed
406   // in printNoMatch() after failing to match.
407   auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
408   NumericVariable *NumericVariable;
409   if (VarTableIter != Context->GlobalNumericVariableTable.end())
410     NumericVariable = VarTableIter->second;
411   else {
412     NumericVariable = Context->makeNumericVariable(
413         Name, ExpressionFormat(ExpressionFormat::Kind::Unsigned));
414     Context->GlobalNumericVariableTable[Name] = NumericVariable;
415   }
416 
417   std::optional<size_t> DefLineNumber = NumericVariable->getDefLineNumber();
418   if (DefLineNumber && LineNumber && *DefLineNumber == *LineNumber)
419     return ErrorDiagnostic::get(
420         SM, Name,
421         "numeric variable '" + Name +
422             "' defined earlier in the same CHECK directive");
423 
424   return std::make_unique<NumericVariableUse>(Name, NumericVariable);
425 }
426 
427 Expected<std::unique_ptr<ExpressionAST>> Pattern::parseNumericOperand(
428     StringRef &Expr, AllowedOperand AO, bool MaybeInvalidConstraint,
429     std::optional<size_t> LineNumber, FileCheckPatternContext *Context,
430     const SourceMgr &SM) {
431   if (Expr.startswith("(")) {
432     if (AO != AllowedOperand::Any)
433       return ErrorDiagnostic::get(
434           SM, Expr, "parenthesized expression not permitted here");
435     return parseParenExpr(Expr, LineNumber, Context, SM);
436   }
437 
438   if (AO == AllowedOperand::LineVar || AO == AllowedOperand::Any) {
439     // Try to parse as a numeric variable use.
440     Expected<Pattern::VariableProperties> ParseVarResult =
441         parseVariable(Expr, SM);
442     if (ParseVarResult) {
443       // Try to parse a function call.
444       if (Expr.ltrim(SpaceChars).startswith("(")) {
445         if (AO != AllowedOperand::Any)
446           return ErrorDiagnostic::get(SM, ParseVarResult->Name,
447                                       "unexpected function call");
448 
449         return parseCallExpr(Expr, ParseVarResult->Name, LineNumber, Context,
450                              SM);
451       }
452 
453       return parseNumericVariableUse(ParseVarResult->Name,
454                                      ParseVarResult->IsPseudo, LineNumber,
455                                      Context, SM);
456     }
457 
458     if (AO == AllowedOperand::LineVar)
459       return ParseVarResult.takeError();
460     // Ignore the error and retry parsing as a literal.
461     consumeError(ParseVarResult.takeError());
462   }
463 
464   // Otherwise, parse it as a literal.
465   APInt LiteralValue;
466   StringRef SaveExpr = Expr;
467   bool Negative = Expr.consume_front("-");
468   if (!Expr.consumeInteger((AO == AllowedOperand::LegacyLiteral) ? 10 : 0,
469                            LiteralValue)) {
470     LiteralValue = toSigned(LiteralValue, Negative);
471     return std::make_unique<ExpressionLiteral>(SaveExpr.drop_back(Expr.size()),
472                                                LiteralValue);
473   }
474   return ErrorDiagnostic::get(
475       SM, SaveExpr,
476       Twine("invalid ") +
477           (MaybeInvalidConstraint ? "matching constraint or " : "") +
478           "operand format");
479 }
480 
481 Expected<std::unique_ptr<ExpressionAST>>
482 Pattern::parseParenExpr(StringRef &Expr, std::optional<size_t> LineNumber,
483                         FileCheckPatternContext *Context, const SourceMgr &SM) {
484   Expr = Expr.ltrim(SpaceChars);
485   assert(Expr.startswith("("));
486 
487   // Parse right operand.
488   Expr.consume_front("(");
489   Expr = Expr.ltrim(SpaceChars);
490   if (Expr.empty())
491     return ErrorDiagnostic::get(SM, Expr, "missing operand in expression");
492 
493   // Note: parseNumericOperand handles nested opening parentheses.
494   Expected<std::unique_ptr<ExpressionAST>> SubExprResult = parseNumericOperand(
495       Expr, AllowedOperand::Any, /*MaybeInvalidConstraint=*/false, LineNumber,
496       Context, SM);
497   Expr = Expr.ltrim(SpaceChars);
498   while (SubExprResult && !Expr.empty() && !Expr.startswith(")")) {
499     StringRef OrigExpr = Expr;
500     SubExprResult = parseBinop(OrigExpr, Expr, std::move(*SubExprResult), false,
501                                LineNumber, Context, SM);
502     Expr = Expr.ltrim(SpaceChars);
503   }
504   if (!SubExprResult)
505     return SubExprResult;
506 
507   if (!Expr.consume_front(")")) {
508     return ErrorDiagnostic::get(SM, Expr,
509                                 "missing ')' at end of nested expression");
510   }
511   return SubExprResult;
512 }
513 
514 Expected<std::unique_ptr<ExpressionAST>>
515 Pattern::parseBinop(StringRef Expr, StringRef &RemainingExpr,
516                     std::unique_ptr<ExpressionAST> LeftOp,
517                     bool IsLegacyLineExpr, std::optional<size_t> LineNumber,
518                     FileCheckPatternContext *Context, const SourceMgr &SM) {
519   RemainingExpr = RemainingExpr.ltrim(SpaceChars);
520   if (RemainingExpr.empty())
521     return std::move(LeftOp);
522 
523   // Check if this is a supported operation and select a function to perform
524   // it.
525   SMLoc OpLoc = SMLoc::getFromPointer(RemainingExpr.data());
526   char Operator = popFront(RemainingExpr);
527   binop_eval_t EvalBinop;
528   switch (Operator) {
529   case '+':
530     EvalBinop = exprAdd;
531     break;
532   case '-':
533     EvalBinop = exprSub;
534     break;
535   default:
536     return ErrorDiagnostic::get(
537         SM, OpLoc, Twine("unsupported operation '") + Twine(Operator) + "'");
538   }
539 
540   // Parse right operand.
541   RemainingExpr = RemainingExpr.ltrim(SpaceChars);
542   if (RemainingExpr.empty())
543     return ErrorDiagnostic::get(SM, RemainingExpr,
544                                 "missing operand in expression");
545   // The second operand in a legacy @LINE expression is always a literal.
546   AllowedOperand AO =
547       IsLegacyLineExpr ? AllowedOperand::LegacyLiteral : AllowedOperand::Any;
548   Expected<std::unique_ptr<ExpressionAST>> RightOpResult =
549       parseNumericOperand(RemainingExpr, AO, /*MaybeInvalidConstraint=*/false,
550                           LineNumber, Context, SM);
551   if (!RightOpResult)
552     return RightOpResult;
553 
554   Expr = Expr.drop_back(RemainingExpr.size());
555   return std::make_unique<BinaryOperation>(Expr, EvalBinop, std::move(LeftOp),
556                                            std::move(*RightOpResult));
557 }
558 
559 Expected<std::unique_ptr<ExpressionAST>>
560 Pattern::parseCallExpr(StringRef &Expr, StringRef FuncName,
561                        std::optional<size_t> LineNumber,
562                        FileCheckPatternContext *Context, const SourceMgr &SM) {
563   Expr = Expr.ltrim(SpaceChars);
564   assert(Expr.startswith("("));
565 
566   auto OptFunc = StringSwitch<binop_eval_t>(FuncName)
567                      .Case("add", exprAdd)
568                      .Case("div", exprDiv)
569                      .Case("max", exprMax)
570                      .Case("min", exprMin)
571                      .Case("mul", exprMul)
572                      .Case("sub", exprSub)
573                      .Default(nullptr);
574 
575   if (!OptFunc)
576     return ErrorDiagnostic::get(
577         SM, FuncName, Twine("call to undefined function '") + FuncName + "'");
578 
579   Expr.consume_front("(");
580   Expr = Expr.ltrim(SpaceChars);
581 
582   // Parse call arguments, which are comma separated.
583   SmallVector<std::unique_ptr<ExpressionAST>, 4> Args;
584   while (!Expr.empty() && !Expr.startswith(")")) {
585     if (Expr.startswith(","))
586       return ErrorDiagnostic::get(SM, Expr, "missing argument");
587 
588     // Parse the argument, which is an arbitary expression.
589     StringRef OuterBinOpExpr = Expr;
590     Expected<std::unique_ptr<ExpressionAST>> Arg = parseNumericOperand(
591         Expr, AllowedOperand::Any, /*MaybeInvalidConstraint=*/false, LineNumber,
592         Context, SM);
593     while (Arg && !Expr.empty()) {
594       Expr = Expr.ltrim(SpaceChars);
595       // Have we reached an argument terminator?
596       if (Expr.startswith(",") || Expr.startswith(")"))
597         break;
598 
599       // Arg = Arg <op> <expr>
600       Arg = parseBinop(OuterBinOpExpr, Expr, std::move(*Arg), false, LineNumber,
601                        Context, SM);
602     }
603 
604     // Prefer an expression error over a generic invalid argument message.
605     if (!Arg)
606       return Arg.takeError();
607     Args.push_back(std::move(*Arg));
608 
609     // Have we parsed all available arguments?
610     Expr = Expr.ltrim(SpaceChars);
611     if (!Expr.consume_front(","))
612       break;
613 
614     Expr = Expr.ltrim(SpaceChars);
615     if (Expr.startswith(")"))
616       return ErrorDiagnostic::get(SM, Expr, "missing argument");
617   }
618 
619   if (!Expr.consume_front(")"))
620     return ErrorDiagnostic::get(SM, Expr,
621                                 "missing ')' at end of call expression");
622 
623   const unsigned NumArgs = Args.size();
624   if (NumArgs == 2)
625     return std::make_unique<BinaryOperation>(Expr, *OptFunc, std::move(Args[0]),
626                                              std::move(Args[1]));
627 
628   // TODO: Support more than binop_eval_t.
629   return ErrorDiagnostic::get(SM, FuncName,
630                               Twine("function '") + FuncName +
631                                   Twine("' takes 2 arguments but ") +
632                                   Twine(NumArgs) + " given");
633 }
634 
635 Expected<std::unique_ptr<Expression>> Pattern::parseNumericSubstitutionBlock(
636     StringRef Expr, std::optional<NumericVariable *> &DefinedNumericVariable,
637     bool IsLegacyLineExpr, std::optional<size_t> LineNumber,
638     FileCheckPatternContext *Context, const SourceMgr &SM) {
639   std::unique_ptr<ExpressionAST> ExpressionASTPointer = nullptr;
640   StringRef DefExpr = StringRef();
641   DefinedNumericVariable = std::nullopt;
642   ExpressionFormat ExplicitFormat = ExpressionFormat();
643   unsigned Precision = 0;
644 
645   // Parse format specifier (NOTE: ',' is also an argument seperator).
646   size_t FormatSpecEnd = Expr.find(',');
647   size_t FunctionStart = Expr.find('(');
648   if (FormatSpecEnd != StringRef::npos && FormatSpecEnd < FunctionStart) {
649     StringRef FormatExpr = Expr.take_front(FormatSpecEnd);
650     Expr = Expr.drop_front(FormatSpecEnd + 1);
651     FormatExpr = FormatExpr.trim(SpaceChars);
652     if (!FormatExpr.consume_front("%"))
653       return ErrorDiagnostic::get(
654           SM, FormatExpr,
655           "invalid matching format specification in expression");
656 
657     // Parse alternate form flag.
658     SMLoc AlternateFormFlagLoc = SMLoc::getFromPointer(FormatExpr.data());
659     bool AlternateForm = FormatExpr.consume_front("#");
660 
661     // Parse precision.
662     if (FormatExpr.consume_front(".")) {
663       if (FormatExpr.consumeInteger(10, Precision))
664         return ErrorDiagnostic::get(SM, FormatExpr,
665                                     "invalid precision in format specifier");
666     }
667 
668     if (!FormatExpr.empty()) {
669       // Check for unknown matching format specifier and set matching format in
670       // class instance representing this expression.
671       SMLoc FmtLoc = SMLoc::getFromPointer(FormatExpr.data());
672       switch (popFront(FormatExpr)) {
673       case 'u':
674         ExplicitFormat =
675             ExpressionFormat(ExpressionFormat::Kind::Unsigned, Precision);
676         break;
677       case 'd':
678         ExplicitFormat =
679             ExpressionFormat(ExpressionFormat::Kind::Signed, Precision);
680         break;
681       case 'x':
682         ExplicitFormat = ExpressionFormat(ExpressionFormat::Kind::HexLower,
683                                           Precision, AlternateForm);
684         break;
685       case 'X':
686         ExplicitFormat = ExpressionFormat(ExpressionFormat::Kind::HexUpper,
687                                           Precision, AlternateForm);
688         break;
689       default:
690         return ErrorDiagnostic::get(SM, FmtLoc,
691                                     "invalid format specifier in expression");
692       }
693     }
694 
695     if (AlternateForm && ExplicitFormat != ExpressionFormat::Kind::HexLower &&
696         ExplicitFormat != ExpressionFormat::Kind::HexUpper)
697       return ErrorDiagnostic::get(
698           SM, AlternateFormFlagLoc,
699           "alternate form only supported for hex values");
700 
701     FormatExpr = FormatExpr.ltrim(SpaceChars);
702     if (!FormatExpr.empty())
703       return ErrorDiagnostic::get(
704           SM, FormatExpr,
705           "invalid matching format specification in expression");
706   }
707 
708   // Save variable definition expression if any.
709   size_t DefEnd = Expr.find(':');
710   if (DefEnd != StringRef::npos) {
711     DefExpr = Expr.substr(0, DefEnd);
712     Expr = Expr.substr(DefEnd + 1);
713   }
714 
715   // Parse matching constraint.
716   Expr = Expr.ltrim(SpaceChars);
717   bool HasParsedValidConstraint = false;
718   if (Expr.consume_front("=="))
719     HasParsedValidConstraint = true;
720 
721   // Parse the expression itself.
722   Expr = Expr.ltrim(SpaceChars);
723   if (Expr.empty()) {
724     if (HasParsedValidConstraint)
725       return ErrorDiagnostic::get(
726           SM, Expr, "empty numeric expression should not have a constraint");
727   } else {
728     Expr = Expr.rtrim(SpaceChars);
729     StringRef OuterBinOpExpr = Expr;
730     // The first operand in a legacy @LINE expression is always the @LINE
731     // pseudo variable.
732     AllowedOperand AO =
733         IsLegacyLineExpr ? AllowedOperand::LineVar : AllowedOperand::Any;
734     Expected<std::unique_ptr<ExpressionAST>> ParseResult = parseNumericOperand(
735         Expr, AO, !HasParsedValidConstraint, LineNumber, Context, SM);
736     while (ParseResult && !Expr.empty()) {
737       ParseResult = parseBinop(OuterBinOpExpr, Expr, std::move(*ParseResult),
738                                IsLegacyLineExpr, LineNumber, Context, SM);
739       // Legacy @LINE expressions only allow 2 operands.
740       if (ParseResult && IsLegacyLineExpr && !Expr.empty())
741         return ErrorDiagnostic::get(
742             SM, Expr,
743             "unexpected characters at end of expression '" + Expr + "'");
744     }
745     if (!ParseResult)
746       return ParseResult.takeError();
747     ExpressionASTPointer = std::move(*ParseResult);
748   }
749 
750   // Select format of the expression, i.e. (i) its explicit format, if any,
751   // otherwise (ii) its implicit format, if any, otherwise (iii) the default
752   // format (unsigned). Error out in case of conflicting implicit format
753   // without explicit format.
754   ExpressionFormat Format;
755   if (ExplicitFormat)
756     Format = ExplicitFormat;
757   else if (ExpressionASTPointer) {
758     Expected<ExpressionFormat> ImplicitFormat =
759         ExpressionASTPointer->getImplicitFormat(SM);
760     if (!ImplicitFormat)
761       return ImplicitFormat.takeError();
762     Format = *ImplicitFormat;
763   }
764   if (!Format)
765     Format = ExpressionFormat(ExpressionFormat::Kind::Unsigned, Precision);
766 
767   std::unique_ptr<Expression> ExpressionPointer =
768       std::make_unique<Expression>(std::move(ExpressionASTPointer), Format);
769 
770   // Parse the numeric variable definition.
771   if (DefEnd != StringRef::npos) {
772     DefExpr = DefExpr.ltrim(SpaceChars);
773     Expected<NumericVariable *> ParseResult = parseNumericVariableDefinition(
774         DefExpr, Context, LineNumber, ExpressionPointer->getFormat(), SM);
775 
776     if (!ParseResult)
777       return ParseResult.takeError();
778     DefinedNumericVariable = *ParseResult;
779   }
780 
781   return std::move(ExpressionPointer);
782 }
783 
784 bool Pattern::parsePattern(StringRef PatternStr, StringRef Prefix,
785                            SourceMgr &SM, const FileCheckRequest &Req) {
786   bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
787   IgnoreCase = Req.IgnoreCase;
788 
789   PatternLoc = SMLoc::getFromPointer(PatternStr.data());
790 
791   if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
792     // Ignore trailing whitespace.
793     while (!PatternStr.empty() &&
794            (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
795       PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
796 
797   // Check that there is something on the line.
798   if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
799     SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
800                     "found empty check string with prefix '" + Prefix + ":'");
801     return true;
802   }
803 
804   if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
805     SM.PrintMessage(
806         PatternLoc, SourceMgr::DK_Error,
807         "found non-empty check string for empty check with prefix '" + Prefix +
808             ":'");
809     return true;
810   }
811 
812   if (CheckTy == Check::CheckEmpty) {
813     RegExStr = "(\n$)";
814     return false;
815   }
816 
817   // If literal check, set fixed string.
818   if (CheckTy.isLiteralMatch()) {
819     FixedStr = PatternStr;
820     return false;
821   }
822 
823   // Check to see if this is a fixed string, or if it has regex pieces.
824   if (!MatchFullLinesHere &&
825       (PatternStr.size() < 2 ||
826        (!PatternStr.contains("{{") && !PatternStr.contains("[[")))) {
827     FixedStr = PatternStr;
828     return false;
829   }
830 
831   if (MatchFullLinesHere) {
832     RegExStr += '^';
833     if (!Req.NoCanonicalizeWhiteSpace)
834       RegExStr += " *";
835   }
836 
837   // Paren value #0 is for the fully matched string.  Any new parenthesized
838   // values add from there.
839   unsigned CurParen = 1;
840 
841   // Otherwise, there is at least one regex piece.  Build up the regex pattern
842   // by escaping scary characters in fixed strings, building up one big regex.
843   while (!PatternStr.empty()) {
844     // RegEx matches.
845     if (PatternStr.startswith("{{")) {
846       // This is the start of a regex match.  Scan for the }}.
847       size_t End = PatternStr.find("}}");
848       if (End == StringRef::npos) {
849         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
850                         SourceMgr::DK_Error,
851                         "found start of regex string with no end '}}'");
852         return true;
853       }
854 
855       // Enclose {{}} patterns in parens just like [[]] even though we're not
856       // capturing the result for any purpose.  This is required in case the
857       // expression contains an alternation like: CHECK:  abc{{x|z}}def.  We
858       // want this to turn into: "abc(x|z)def" not "abcx|zdef".
859       RegExStr += '(';
860       ++CurParen;
861 
862       if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
863         return true;
864       RegExStr += ')';
865 
866       PatternStr = PatternStr.substr(End + 2);
867       continue;
868     }
869 
870     // String and numeric substitution blocks. Pattern substitution blocks come
871     // in two forms: [[foo:.*]] and [[foo]]. The former matches .* (or some
872     // other regex) and assigns it to the string variable 'foo'. The latter
873     // substitutes foo's value. Numeric substitution blocks recognize the same
874     // form as string ones, but start with a '#' sign after the double
875     // brackets. They also accept a combined form which sets a numeric variable
876     // to the evaluation of an expression. Both string and numeric variable
877     // names must satisfy the regular expression "[a-zA-Z_][0-9a-zA-Z_]*" to be
878     // valid, as this helps catch some common errors. If there are extra '['s
879     // before the "[[", treat them literally.
880     if (PatternStr.startswith("[[") && !PatternStr.startswith("[[[")) {
881       StringRef UnparsedPatternStr = PatternStr.substr(2);
882       // Find the closing bracket pair ending the match.  End is going to be an
883       // offset relative to the beginning of the match string.
884       size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
885       StringRef MatchStr = UnparsedPatternStr.substr(0, End);
886       bool IsNumBlock = MatchStr.consume_front("#");
887 
888       if (End == StringRef::npos) {
889         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
890                         SourceMgr::DK_Error,
891                         "Invalid substitution block, no ]] found");
892         return true;
893       }
894       // Strip the substitution block we are parsing. End points to the start
895       // of the "]]" closing the expression so account for it in computing the
896       // index of the first unparsed character.
897       PatternStr = UnparsedPatternStr.substr(End + 2);
898 
899       bool IsDefinition = false;
900       bool SubstNeeded = false;
901       // Whether the substitution block is a legacy use of @LINE with string
902       // substitution block syntax.
903       bool IsLegacyLineExpr = false;
904       StringRef DefName;
905       StringRef SubstStr;
906       StringRef MatchRegexp;
907       std::string WildcardRegexp;
908       size_t SubstInsertIdx = RegExStr.size();
909 
910       // Parse string variable or legacy @LINE expression.
911       if (!IsNumBlock) {
912         size_t VarEndIdx = MatchStr.find(':');
913         size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
914         if (SpacePos != StringRef::npos) {
915           SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
916                           SourceMgr::DK_Error, "unexpected whitespace");
917           return true;
918         }
919 
920         // Get the name (e.g. "foo") and verify it is well formed.
921         StringRef OrigMatchStr = MatchStr;
922         Expected<Pattern::VariableProperties> ParseVarResult =
923             parseVariable(MatchStr, SM);
924         if (!ParseVarResult) {
925           logAllUnhandledErrors(ParseVarResult.takeError(), errs());
926           return true;
927         }
928         StringRef Name = ParseVarResult->Name;
929         bool IsPseudo = ParseVarResult->IsPseudo;
930 
931         IsDefinition = (VarEndIdx != StringRef::npos);
932         SubstNeeded = !IsDefinition;
933         if (IsDefinition) {
934           if ((IsPseudo || !MatchStr.consume_front(":"))) {
935             SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
936                             SourceMgr::DK_Error,
937                             "invalid name in string variable definition");
938             return true;
939           }
940 
941           // Detect collisions between string and numeric variables when the
942           // former is created later than the latter.
943           if (Context->GlobalNumericVariableTable.contains(Name)) {
944             SM.PrintMessage(
945                 SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
946                 "numeric variable with name '" + Name + "' already exists");
947             return true;
948           }
949           DefName = Name;
950           MatchRegexp = MatchStr;
951         } else {
952           if (IsPseudo) {
953             MatchStr = OrigMatchStr;
954             IsLegacyLineExpr = IsNumBlock = true;
955           } else {
956             if (!MatchStr.empty()) {
957               SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
958                               SourceMgr::DK_Error,
959                               "invalid name in string variable use");
960               return true;
961             }
962             SubstStr = Name;
963           }
964         }
965       }
966 
967       // Parse numeric substitution block.
968       std::unique_ptr<Expression> ExpressionPointer;
969       std::optional<NumericVariable *> DefinedNumericVariable;
970       if (IsNumBlock) {
971         Expected<std::unique_ptr<Expression>> ParseResult =
972             parseNumericSubstitutionBlock(MatchStr, DefinedNumericVariable,
973                                           IsLegacyLineExpr, LineNumber, Context,
974                                           SM);
975         if (!ParseResult) {
976           logAllUnhandledErrors(ParseResult.takeError(), errs());
977           return true;
978         }
979         ExpressionPointer = std::move(*ParseResult);
980         SubstNeeded = ExpressionPointer->getAST() != nullptr;
981         if (DefinedNumericVariable) {
982           IsDefinition = true;
983           DefName = (*DefinedNumericVariable)->getName();
984         }
985         if (SubstNeeded)
986           SubstStr = MatchStr;
987         else {
988           ExpressionFormat Format = ExpressionPointer->getFormat();
989           WildcardRegexp = cantFail(Format.getWildcardRegex());
990           MatchRegexp = WildcardRegexp;
991         }
992       }
993 
994       // Handle variable definition: [[<def>:(...)]] and [[#(...)<def>:(...)]].
995       if (IsDefinition) {
996         RegExStr += '(';
997         ++SubstInsertIdx;
998 
999         if (IsNumBlock) {
1000           NumericVariableMatch NumericVariableDefinition = {
1001               *DefinedNumericVariable, CurParen};
1002           NumericVariableDefs[DefName] = NumericVariableDefinition;
1003           // This store is done here rather than in match() to allow
1004           // parseNumericVariableUse() to get the pointer to the class instance
1005           // of the right variable definition corresponding to a given numeric
1006           // variable use.
1007           Context->GlobalNumericVariableTable[DefName] =
1008               *DefinedNumericVariable;
1009         } else {
1010           VariableDefs[DefName] = CurParen;
1011           // Mark string variable as defined to detect collisions between
1012           // string and numeric variables in parseNumericVariableUse() and
1013           // defineCmdlineVariables() when the latter is created later than the
1014           // former. We cannot reuse GlobalVariableTable for this by populating
1015           // it with an empty string since we would then lose the ability to
1016           // detect the use of an undefined variable in match().
1017           Context->DefinedVariableTable[DefName] = true;
1018         }
1019 
1020         ++CurParen;
1021       }
1022 
1023       if (!MatchRegexp.empty() && AddRegExToRegEx(MatchRegexp, CurParen, SM))
1024         return true;
1025 
1026       if (IsDefinition)
1027         RegExStr += ')';
1028 
1029       // Handle substitutions: [[foo]] and [[#<foo expr>]].
1030       if (SubstNeeded) {
1031         // Handle substitution of string variables that were defined earlier on
1032         // the same line by emitting a backreference. Expressions do not
1033         // support substituting a numeric variable defined on the same line.
1034         if (!IsNumBlock && VariableDefs.find(SubstStr) != VariableDefs.end()) {
1035           unsigned CaptureParenGroup = VariableDefs[SubstStr];
1036           if (CaptureParenGroup < 1 || CaptureParenGroup > 9) {
1037             SM.PrintMessage(SMLoc::getFromPointer(SubstStr.data()),
1038                             SourceMgr::DK_Error,
1039                             "Can't back-reference more than 9 variables");
1040             return true;
1041           }
1042           AddBackrefToRegEx(CaptureParenGroup);
1043         } else {
1044           // Handle substitution of string variables ([[<var>]]) defined in
1045           // previous CHECK patterns, and substitution of expressions.
1046           Substitution *Substitution =
1047               IsNumBlock
1048                   ? Context->makeNumericSubstitution(
1049                         SubstStr, std::move(ExpressionPointer), SubstInsertIdx)
1050                   : Context->makeStringSubstitution(SubstStr, SubstInsertIdx);
1051           Substitutions.push_back(Substitution);
1052         }
1053       }
1054 
1055       continue;
1056     }
1057 
1058     // Handle fixed string matches.
1059     // Find the end, which is the start of the next regex.
1060     size_t FixedMatchEnd =
1061         std::min(PatternStr.find("{{", 1), PatternStr.find("[[", 1));
1062     RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
1063     PatternStr = PatternStr.substr(FixedMatchEnd);
1064   }
1065 
1066   if (MatchFullLinesHere) {
1067     if (!Req.NoCanonicalizeWhiteSpace)
1068       RegExStr += " *";
1069     RegExStr += '$';
1070   }
1071 
1072   return false;
1073 }
1074 
1075 bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
1076   Regex R(RS);
1077   std::string Error;
1078   if (!R.isValid(Error)) {
1079     SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
1080                     "invalid regex: " + Error);
1081     return true;
1082   }
1083 
1084   RegExStr += RS.str();
1085   CurParen += R.getNumMatches();
1086   return false;
1087 }
1088 
1089 void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
1090   assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
1091   std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
1092   RegExStr += Backref;
1093 }
1094 
1095 Pattern::MatchResult Pattern::match(StringRef Buffer,
1096                                     const SourceMgr &SM) const {
1097   // If this is the EOF pattern, match it immediately.
1098   if (CheckTy == Check::CheckEOF)
1099     return MatchResult(Buffer.size(), 0, Error::success());
1100 
1101   // If this is a fixed string pattern, just match it now.
1102   if (!FixedStr.empty()) {
1103     size_t Pos =
1104         IgnoreCase ? Buffer.find_insensitive(FixedStr) : Buffer.find(FixedStr);
1105     if (Pos == StringRef::npos)
1106       return make_error<NotFoundError>();
1107     return MatchResult(Pos, /*MatchLen=*/FixedStr.size(), Error::success());
1108   }
1109 
1110   // Regex match.
1111 
1112   // If there are substitutions, we need to create a temporary string with the
1113   // actual value.
1114   StringRef RegExToMatch = RegExStr;
1115   std::string TmpStr;
1116   if (!Substitutions.empty()) {
1117     TmpStr = RegExStr;
1118     if (LineNumber)
1119       Context->LineVariable->setValue(
1120           ExpressionValue(APInt(sizeof(*LineNumber) * 8, *LineNumber)));
1121 
1122     size_t InsertOffset = 0;
1123     // Substitute all string variables and expressions whose values are only
1124     // now known. Use of string variables defined on the same line are handled
1125     // by back-references.
1126     Error Errs = Error::success();
1127     for (const auto &Substitution : Substitutions) {
1128       // Substitute and check for failure (e.g. use of undefined variable).
1129       Expected<std::string> Value = Substitution->getResult();
1130       if (!Value) {
1131         // Convert to an ErrorDiagnostic to get location information. This is
1132         // done here rather than printMatch/printNoMatch since now we know which
1133         // substitution block caused the overflow.
1134         Errs = joinErrors(std::move(Errs),
1135                           handleErrors(
1136                               Value.takeError(),
1137                               [&](const OverflowError &E) {
1138                                 return ErrorDiagnostic::get(
1139                                     SM, Substitution->getFromString(),
1140                                     "unable to substitute variable or "
1141                                     "numeric expression: overflow error");
1142                               },
1143                               [&SM](const UndefVarError &E) {
1144                                 return ErrorDiagnostic::get(SM, E.getVarName(),
1145                                                             E.message());
1146                               }));
1147         continue;
1148       }
1149 
1150       // Plop it into the regex at the adjusted offset.
1151       TmpStr.insert(TmpStr.begin() + Substitution->getIndex() + InsertOffset,
1152                     Value->begin(), Value->end());
1153       InsertOffset += Value->size();
1154     }
1155     if (Errs)
1156       return std::move(Errs);
1157 
1158     // Match the newly constructed regex.
1159     RegExToMatch = TmpStr;
1160   }
1161 
1162   SmallVector<StringRef, 4> MatchInfo;
1163   unsigned int Flags = Regex::Newline;
1164   if (IgnoreCase)
1165     Flags |= Regex::IgnoreCase;
1166   if (!Regex(RegExToMatch, Flags).match(Buffer, &MatchInfo))
1167     return make_error<NotFoundError>();
1168 
1169   // Successful regex match.
1170   assert(!MatchInfo.empty() && "Didn't get any match");
1171   StringRef FullMatch = MatchInfo[0];
1172 
1173   // If this defines any string variables, remember their values.
1174   for (const auto &VariableDef : VariableDefs) {
1175     assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
1176     Context->GlobalVariableTable[VariableDef.first] =
1177         MatchInfo[VariableDef.second];
1178   }
1179 
1180   // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
1181   // the required preceding newline, which is consumed by the pattern in the
1182   // case of CHECK-EMPTY but not CHECK-NEXT.
1183   size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
1184   Match TheMatch;
1185   TheMatch.Pos = FullMatch.data() - Buffer.data() + MatchStartSkip;
1186   TheMatch.Len = FullMatch.size() - MatchStartSkip;
1187 
1188   // If this defines any numeric variables, remember their values.
1189   for (const auto &NumericVariableDef : NumericVariableDefs) {
1190     const NumericVariableMatch &NumericVariableMatch =
1191         NumericVariableDef.getValue();
1192     unsigned CaptureParenGroup = NumericVariableMatch.CaptureParenGroup;
1193     assert(CaptureParenGroup < MatchInfo.size() && "Internal paren error");
1194     NumericVariable *DefinedNumericVariable =
1195         NumericVariableMatch.DefinedNumericVariable;
1196 
1197     StringRef MatchedValue = MatchInfo[CaptureParenGroup];
1198     ExpressionFormat Format = DefinedNumericVariable->getImplicitFormat();
1199     Expected<ExpressionValue> Value =
1200         Format.valueFromStringRepr(MatchedValue, SM);
1201     if (!Value)
1202       return MatchResult(TheMatch, Value.takeError());
1203     DefinedNumericVariable->setValue(*Value, MatchedValue);
1204   }
1205 
1206   return MatchResult(TheMatch, Error::success());
1207 }
1208 
1209 unsigned Pattern::computeMatchDistance(StringRef Buffer) const {
1210   // Just compute the number of matching characters. For regular expressions, we
1211   // just compare against the regex itself and hope for the best.
1212   //
1213   // FIXME: One easy improvement here is have the regex lib generate a single
1214   // example regular expression which matches, and use that as the example
1215   // string.
1216   StringRef ExampleString(FixedStr);
1217   if (ExampleString.empty())
1218     ExampleString = RegExStr;
1219 
1220   // Only compare up to the first line in the buffer, or the string size.
1221   StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
1222   BufferPrefix = BufferPrefix.split('\n').first;
1223   return BufferPrefix.edit_distance(ExampleString);
1224 }
1225 
1226 void Pattern::printSubstitutions(const SourceMgr &SM, StringRef Buffer,
1227                                  SMRange Range,
1228                                  FileCheckDiag::MatchType MatchTy,
1229                                  std::vector<FileCheckDiag> *Diags) const {
1230   // Print what we know about substitutions.
1231   if (!Substitutions.empty()) {
1232     for (const auto &Substitution : Substitutions) {
1233       SmallString<256> Msg;
1234       raw_svector_ostream OS(Msg);
1235 
1236       Expected<std::string> MatchedValue = Substitution->getResult();
1237       // Substitution failures are handled in printNoMatch().
1238       if (!MatchedValue) {
1239         consumeError(MatchedValue.takeError());
1240         continue;
1241       }
1242 
1243       OS << "with \"";
1244       OS.write_escaped(Substitution->getFromString()) << "\" equal to \"";
1245       OS.write_escaped(*MatchedValue) << "\"";
1246 
1247       // We report only the start of the match/search range to suggest we are
1248       // reporting the substitutions as set at the start of the match/search.
1249       // Indicating a non-zero-length range might instead seem to imply that the
1250       // substitution matches or was captured from exactly that range.
1251       if (Diags)
1252         Diags->emplace_back(SM, CheckTy, getLoc(), MatchTy,
1253                             SMRange(Range.Start, Range.Start), OS.str());
1254       else
1255         SM.PrintMessage(Range.Start, SourceMgr::DK_Note, OS.str());
1256     }
1257   }
1258 }
1259 
1260 void Pattern::printVariableDefs(const SourceMgr &SM,
1261                                 FileCheckDiag::MatchType MatchTy,
1262                                 std::vector<FileCheckDiag> *Diags) const {
1263   if (VariableDefs.empty() && NumericVariableDefs.empty())
1264     return;
1265   // Build list of variable captures.
1266   struct VarCapture {
1267     StringRef Name;
1268     SMRange Range;
1269   };
1270   SmallVector<VarCapture, 2> VarCaptures;
1271   for (const auto &VariableDef : VariableDefs) {
1272     VarCapture VC;
1273     VC.Name = VariableDef.first;
1274     StringRef Value = Context->GlobalVariableTable[VC.Name];
1275     SMLoc Start = SMLoc::getFromPointer(Value.data());
1276     SMLoc End = SMLoc::getFromPointer(Value.data() + Value.size());
1277     VC.Range = SMRange(Start, End);
1278     VarCaptures.push_back(VC);
1279   }
1280   for (const auto &VariableDef : NumericVariableDefs) {
1281     VarCapture VC;
1282     VC.Name = VariableDef.getKey();
1283     std::optional<StringRef> StrValue =
1284         VariableDef.getValue().DefinedNumericVariable->getStringValue();
1285     if (!StrValue)
1286       continue;
1287     SMLoc Start = SMLoc::getFromPointer(StrValue->data());
1288     SMLoc End = SMLoc::getFromPointer(StrValue->data() + StrValue->size());
1289     VC.Range = SMRange(Start, End);
1290     VarCaptures.push_back(VC);
1291   }
1292   // Sort variable captures by the order in which they matched the input.
1293   // Ranges shouldn't be overlapping, so we can just compare the start.
1294   llvm::sort(VarCaptures, [](const VarCapture &A, const VarCapture &B) {
1295     if (&A == &B)
1296       return false;
1297     assert(A.Range.Start != B.Range.Start &&
1298            "unexpected overlapping variable captures");
1299     return A.Range.Start.getPointer() < B.Range.Start.getPointer();
1300   });
1301   // Create notes for the sorted captures.
1302   for (const VarCapture &VC : VarCaptures) {
1303     SmallString<256> Msg;
1304     raw_svector_ostream OS(Msg);
1305     OS << "captured var \"" << VC.Name << "\"";
1306     if (Diags)
1307       Diags->emplace_back(SM, CheckTy, getLoc(), MatchTy, VC.Range, OS.str());
1308     else
1309       SM.PrintMessage(VC.Range.Start, SourceMgr::DK_Note, OS.str(), VC.Range);
1310   }
1311 }
1312 
1313 static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
1314                                   const SourceMgr &SM, SMLoc Loc,
1315                                   Check::FileCheckType CheckTy,
1316                                   StringRef Buffer, size_t Pos, size_t Len,
1317                                   std::vector<FileCheckDiag> *Diags,
1318                                   bool AdjustPrevDiags = false) {
1319   SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
1320   SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
1321   SMRange Range(Start, End);
1322   if (Diags) {
1323     if (AdjustPrevDiags) {
1324       SMLoc CheckLoc = Diags->rbegin()->CheckLoc;
1325       for (auto I = Diags->rbegin(), E = Diags->rend();
1326            I != E && I->CheckLoc == CheckLoc; ++I)
1327         I->MatchTy = MatchTy;
1328     } else
1329       Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
1330   }
1331   return Range;
1332 }
1333 
1334 void Pattern::printFuzzyMatch(const SourceMgr &SM, StringRef Buffer,
1335                               std::vector<FileCheckDiag> *Diags) const {
1336   // Attempt to find the closest/best fuzzy match.  Usually an error happens
1337   // because some string in the output didn't exactly match. In these cases, we
1338   // would like to show the user a best guess at what "should have" matched, to
1339   // save them having to actually check the input manually.
1340   size_t NumLinesForward = 0;
1341   size_t Best = StringRef::npos;
1342   double BestQuality = 0;
1343 
1344   // Use an arbitrary 4k limit on how far we will search.
1345   for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
1346     if (Buffer[i] == '\n')
1347       ++NumLinesForward;
1348 
1349     // Patterns have leading whitespace stripped, so skip whitespace when
1350     // looking for something which looks like a pattern.
1351     if (Buffer[i] == ' ' || Buffer[i] == '\t')
1352       continue;
1353 
1354     // Compute the "quality" of this match as an arbitrary combination of the
1355     // match distance and the number of lines skipped to get to this match.
1356     unsigned Distance = computeMatchDistance(Buffer.substr(i));
1357     double Quality = Distance + (NumLinesForward / 100.);
1358 
1359     if (Quality < BestQuality || Best == StringRef::npos) {
1360       Best = i;
1361       BestQuality = Quality;
1362     }
1363   }
1364 
1365   // Print the "possible intended match here" line if we found something
1366   // reasonable and not equal to what we showed in the "scanning from here"
1367   // line.
1368   if (Best && Best != StringRef::npos && BestQuality < 50) {
1369     SMRange MatchRange =
1370         ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
1371                            getCheckTy(), Buffer, Best, 0, Diags);
1372     SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
1373                     "possible intended match here");
1374 
1375     // FIXME: If we wanted to be really friendly we would show why the match
1376     // failed, as it can be hard to spot simple one character differences.
1377   }
1378 }
1379 
1380 Expected<StringRef>
1381 FileCheckPatternContext::getPatternVarValue(StringRef VarName) {
1382   auto VarIter = GlobalVariableTable.find(VarName);
1383   if (VarIter == GlobalVariableTable.end())
1384     return make_error<UndefVarError>(VarName);
1385 
1386   return VarIter->second;
1387 }
1388 
1389 template <class... Types>
1390 NumericVariable *FileCheckPatternContext::makeNumericVariable(Types... args) {
1391   NumericVariables.push_back(std::make_unique<NumericVariable>(args...));
1392   return NumericVariables.back().get();
1393 }
1394 
1395 Substitution *
1396 FileCheckPatternContext::makeStringSubstitution(StringRef VarName,
1397                                                 size_t InsertIdx) {
1398   Substitutions.push_back(
1399       std::make_unique<StringSubstitution>(this, VarName, InsertIdx));
1400   return Substitutions.back().get();
1401 }
1402 
1403 Substitution *FileCheckPatternContext::makeNumericSubstitution(
1404     StringRef ExpressionStr, std::unique_ptr<Expression> Expression,
1405     size_t InsertIdx) {
1406   Substitutions.push_back(std::make_unique<NumericSubstitution>(
1407       this, ExpressionStr, std::move(Expression), InsertIdx));
1408   return Substitutions.back().get();
1409 }
1410 
1411 size_t Pattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
1412   // Offset keeps track of the current offset within the input Str
1413   size_t Offset = 0;
1414   // [...] Nesting depth
1415   size_t BracketDepth = 0;
1416 
1417   while (!Str.empty()) {
1418     if (Str.startswith("]]") && BracketDepth == 0)
1419       return Offset;
1420     if (Str[0] == '\\') {
1421       // Backslash escapes the next char within regexes, so skip them both.
1422       Str = Str.substr(2);
1423       Offset += 2;
1424     } else {
1425       switch (Str[0]) {
1426       default:
1427         break;
1428       case '[':
1429         BracketDepth++;
1430         break;
1431       case ']':
1432         if (BracketDepth == 0) {
1433           SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
1434                           SourceMgr::DK_Error,
1435                           "missing closing \"]\" for regex variable");
1436           exit(1);
1437         }
1438         BracketDepth--;
1439         break;
1440       }
1441       Str = Str.substr(1);
1442       Offset++;
1443     }
1444   }
1445 
1446   return StringRef::npos;
1447 }
1448 
1449 StringRef FileCheck::CanonicalizeFile(MemoryBuffer &MB,
1450                                       SmallVectorImpl<char> &OutputBuffer) {
1451   OutputBuffer.reserve(MB.getBufferSize());
1452 
1453   for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
1454        Ptr != End; ++Ptr) {
1455     // Eliminate trailing dosish \r.
1456     if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
1457       continue;
1458     }
1459 
1460     // If current char is not a horizontal whitespace or if horizontal
1461     // whitespace canonicalization is disabled, dump it to output as is.
1462     if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
1463       OutputBuffer.push_back(*Ptr);
1464       continue;
1465     }
1466 
1467     // Otherwise, add one space and advance over neighboring space.
1468     OutputBuffer.push_back(' ');
1469     while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
1470       ++Ptr;
1471   }
1472 
1473   // Add a null byte and then return all but that byte.
1474   OutputBuffer.push_back('\0');
1475   return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
1476 }
1477 
1478 FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
1479                              const Check::FileCheckType &CheckTy,
1480                              SMLoc CheckLoc, MatchType MatchTy,
1481                              SMRange InputRange, StringRef Note)
1482     : CheckTy(CheckTy), CheckLoc(CheckLoc), MatchTy(MatchTy), Note(Note) {
1483   auto Start = SM.getLineAndColumn(InputRange.Start);
1484   auto End = SM.getLineAndColumn(InputRange.End);
1485   InputStartLine = Start.first;
1486   InputStartCol = Start.second;
1487   InputEndLine = End.first;
1488   InputEndCol = End.second;
1489 }
1490 
1491 static bool IsPartOfWord(char c) {
1492   return (isAlnum(c) || c == '-' || c == '_');
1493 }
1494 
1495 Check::FileCheckType &Check::FileCheckType::setCount(int C) {
1496   assert(Count > 0 && "zero and negative counts are not supported");
1497   assert((C == 1 || Kind == CheckPlain) &&
1498          "count supported only for plain CHECK directives");
1499   Count = C;
1500   return *this;
1501 }
1502 
1503 std::string Check::FileCheckType::getModifiersDescription() const {
1504   if (Modifiers.none())
1505     return "";
1506   std::string Ret;
1507   raw_string_ostream OS(Ret);
1508   OS << '{';
1509   if (isLiteralMatch())
1510     OS << "LITERAL";
1511   OS << '}';
1512   return OS.str();
1513 }
1514 
1515 std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
1516   // Append directive modifiers.
1517   auto WithModifiers = [this, Prefix](StringRef Str) -> std::string {
1518     return (Prefix + Str + getModifiersDescription()).str();
1519   };
1520 
1521   switch (Kind) {
1522   case Check::CheckNone:
1523     return "invalid";
1524   case Check::CheckMisspelled:
1525     return "misspelled";
1526   case Check::CheckPlain:
1527     if (Count > 1)
1528       return WithModifiers("-COUNT");
1529     return WithModifiers("");
1530   case Check::CheckNext:
1531     return WithModifiers("-NEXT");
1532   case Check::CheckSame:
1533     return WithModifiers("-SAME");
1534   case Check::CheckNot:
1535     return WithModifiers("-NOT");
1536   case Check::CheckDAG:
1537     return WithModifiers("-DAG");
1538   case Check::CheckLabel:
1539     return WithModifiers("-LABEL");
1540   case Check::CheckEmpty:
1541     return WithModifiers("-EMPTY");
1542   case Check::CheckComment:
1543     return std::string(Prefix);
1544   case Check::CheckEOF:
1545     return "implicit EOF";
1546   case Check::CheckBadNot:
1547     return "bad NOT";
1548   case Check::CheckBadCount:
1549     return "bad COUNT";
1550   }
1551   llvm_unreachable("unknown FileCheckType");
1552 }
1553 
1554 static std::pair<Check::FileCheckType, StringRef>
1555 FindCheckType(const FileCheckRequest &Req, StringRef Buffer, StringRef Prefix,
1556               bool &Misspelled) {
1557   if (Buffer.size() <= Prefix.size())
1558     return {Check::CheckNone, StringRef()};
1559 
1560   StringRef Rest = Buffer.drop_front(Prefix.size());
1561   // Check for comment.
1562   if (llvm::is_contained(Req.CommentPrefixes, Prefix)) {
1563     if (Rest.consume_front(":"))
1564       return {Check::CheckComment, Rest};
1565     // Ignore a comment prefix if it has a suffix like "-NOT".
1566     return {Check::CheckNone, StringRef()};
1567   }
1568 
1569   auto ConsumeModifiers = [&](Check::FileCheckType Ret)
1570       -> std::pair<Check::FileCheckType, StringRef> {
1571     if (Rest.consume_front(":"))
1572       return {Ret, Rest};
1573     if (!Rest.consume_front("{"))
1574       return {Check::CheckNone, StringRef()};
1575 
1576     // Parse the modifiers, speparated by commas.
1577     do {
1578       // Allow whitespace in modifiers list.
1579       Rest = Rest.ltrim();
1580       if (Rest.consume_front("LITERAL"))
1581         Ret.setLiteralMatch();
1582       else
1583         return {Check::CheckNone, Rest};
1584       // Allow whitespace in modifiers list.
1585       Rest = Rest.ltrim();
1586     } while (Rest.consume_front(","));
1587     if (!Rest.consume_front("}:"))
1588       return {Check::CheckNone, Rest};
1589     return {Ret, Rest};
1590   };
1591 
1592   // Verify that the prefix is followed by directive modifiers or a colon.
1593   if (Rest.consume_front(":"))
1594     return {Check::CheckPlain, Rest};
1595   if (Rest.front() == '{')
1596     return ConsumeModifiers(Check::CheckPlain);
1597 
1598   if (Rest.consume_front("_"))
1599     Misspelled = true;
1600   else if (!Rest.consume_front("-"))
1601     return {Check::CheckNone, StringRef()};
1602 
1603   if (Rest.consume_front("COUNT-")) {
1604     int64_t Count;
1605     if (Rest.consumeInteger(10, Count))
1606       // Error happened in parsing integer.
1607       return {Check::CheckBadCount, Rest};
1608     if (Count <= 0 || Count > INT32_MAX)
1609       return {Check::CheckBadCount, Rest};
1610     if (Rest.front() != ':' && Rest.front() != '{')
1611       return {Check::CheckBadCount, Rest};
1612     return ConsumeModifiers(
1613         Check::FileCheckType(Check::CheckPlain).setCount(Count));
1614   }
1615 
1616   // You can't combine -NOT with another suffix.
1617   if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
1618       Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
1619       Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
1620       Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
1621     return {Check::CheckBadNot, Rest};
1622 
1623   if (Rest.consume_front("NEXT"))
1624     return ConsumeModifiers(Check::CheckNext);
1625 
1626   if (Rest.consume_front("SAME"))
1627     return ConsumeModifiers(Check::CheckSame);
1628 
1629   if (Rest.consume_front("NOT"))
1630     return ConsumeModifiers(Check::CheckNot);
1631 
1632   if (Rest.consume_front("DAG"))
1633     return ConsumeModifiers(Check::CheckDAG);
1634 
1635   if (Rest.consume_front("LABEL"))
1636     return ConsumeModifiers(Check::CheckLabel);
1637 
1638   if (Rest.consume_front("EMPTY"))
1639     return ConsumeModifiers(Check::CheckEmpty);
1640 
1641   return {Check::CheckNone, Rest};
1642 }
1643 
1644 static std::pair<Check::FileCheckType, StringRef>
1645 FindCheckType(const FileCheckRequest &Req, StringRef Buffer, StringRef Prefix) {
1646   bool Misspelled = false;
1647   auto Res = FindCheckType(Req, Buffer, Prefix, Misspelled);
1648   if (Res.first != Check::CheckNone && Misspelled)
1649     return {Check::CheckMisspelled, Res.second};
1650   return Res;
1651 }
1652 
1653 // From the given position, find the next character after the word.
1654 static size_t SkipWord(StringRef Str, size_t Loc) {
1655   while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
1656     ++Loc;
1657   return Loc;
1658 }
1659 
1660 /// Searches the buffer for the first prefix in the prefix regular expression.
1661 ///
1662 /// This searches the buffer using the provided regular expression, however it
1663 /// enforces constraints beyond that:
1664 /// 1) The found prefix must not be a suffix of something that looks like
1665 ///    a valid prefix.
1666 /// 2) The found prefix must be followed by a valid check type suffix using \c
1667 ///    FindCheckType above.
1668 ///
1669 /// \returns a pair of StringRefs into the Buffer, which combines:
1670 ///   - the first match of the regular expression to satisfy these two is
1671 ///   returned,
1672 ///     otherwise an empty StringRef is returned to indicate failure.
1673 ///   - buffer rewound to the location right after parsed suffix, for parsing
1674 ///     to continue from
1675 ///
1676 /// If this routine returns a valid prefix, it will also shrink \p Buffer to
1677 /// start at the beginning of the returned prefix, increment \p LineNumber for
1678 /// each new line consumed from \p Buffer, and set \p CheckTy to the type of
1679 /// check found by examining the suffix.
1680 ///
1681 /// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
1682 /// is unspecified.
1683 static std::pair<StringRef, StringRef>
1684 FindFirstMatchingPrefix(const FileCheckRequest &Req, Regex &PrefixRE,
1685                         StringRef &Buffer, unsigned &LineNumber,
1686                         Check::FileCheckType &CheckTy) {
1687   SmallVector<StringRef, 2> Matches;
1688 
1689   while (!Buffer.empty()) {
1690     // Find the first (longest) match using the RE.
1691     if (!PrefixRE.match(Buffer, &Matches))
1692       // No match at all, bail.
1693       return {StringRef(), StringRef()};
1694 
1695     StringRef Prefix = Matches[0];
1696     Matches.clear();
1697 
1698     assert(Prefix.data() >= Buffer.data() &&
1699            Prefix.data() < Buffer.data() + Buffer.size() &&
1700            "Prefix doesn't start inside of buffer!");
1701     size_t Loc = Prefix.data() - Buffer.data();
1702     StringRef Skipped = Buffer.substr(0, Loc);
1703     Buffer = Buffer.drop_front(Loc);
1704     LineNumber += Skipped.count('\n');
1705 
1706     // Check that the matched prefix isn't a suffix of some other check-like
1707     // word.
1708     // FIXME: This is a very ad-hoc check. it would be better handled in some
1709     // other way. Among other things it seems hard to distinguish between
1710     // intentional and unintentional uses of this feature.
1711     if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
1712       // Now extract the type.
1713       StringRef AfterSuffix;
1714       std::tie(CheckTy, AfterSuffix) = FindCheckType(Req, Buffer, Prefix);
1715 
1716       // If we've found a valid check type for this prefix, we're done.
1717       if (CheckTy != Check::CheckNone)
1718         return {Prefix, AfterSuffix};
1719     }
1720 
1721     // If we didn't successfully find a prefix, we need to skip this invalid
1722     // prefix and continue scanning. We directly skip the prefix that was
1723     // matched and any additional parts of that check-like word.
1724     Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
1725   }
1726 
1727   // We ran out of buffer while skipping partial matches so give up.
1728   return {StringRef(), StringRef()};
1729 }
1730 
1731 void FileCheckPatternContext::createLineVariable() {
1732   assert(!LineVariable && "@LINE pseudo numeric variable already created");
1733   StringRef LineName = "@LINE";
1734   LineVariable = makeNumericVariable(
1735       LineName, ExpressionFormat(ExpressionFormat::Kind::Unsigned));
1736   GlobalNumericVariableTable[LineName] = LineVariable;
1737 }
1738 
1739 FileCheck::FileCheck(FileCheckRequest Req)
1740     : Req(Req), PatternContext(std::make_unique<FileCheckPatternContext>()),
1741       CheckStrings(std::make_unique<std::vector<FileCheckString>>()) {}
1742 
1743 FileCheck::~FileCheck() = default;
1744 
1745 bool FileCheck::readCheckFile(
1746     SourceMgr &SM, StringRef Buffer, Regex &PrefixRE,
1747     std::pair<unsigned, unsigned> *ImpPatBufferIDRange) {
1748   if (ImpPatBufferIDRange)
1749     ImpPatBufferIDRange->first = ImpPatBufferIDRange->second = 0;
1750 
1751   Error DefineError =
1752       PatternContext->defineCmdlineVariables(Req.GlobalDefines, SM);
1753   if (DefineError) {
1754     logAllUnhandledErrors(std::move(DefineError), errs());
1755     return true;
1756   }
1757 
1758   PatternContext->createLineVariable();
1759 
1760   std::vector<Pattern> ImplicitNegativeChecks;
1761   for (StringRef PatternString : Req.ImplicitCheckNot) {
1762     // Create a buffer with fake command line content in order to display the
1763     // command line option responsible for the specific implicit CHECK-NOT.
1764     std::string Prefix = "-implicit-check-not='";
1765     std::string Suffix = "'";
1766     std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
1767         (Prefix + PatternString + Suffix).str(), "command line");
1768 
1769     StringRef PatternInBuffer =
1770         CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
1771     unsigned BufferID = SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
1772     if (ImpPatBufferIDRange) {
1773       if (ImpPatBufferIDRange->first == ImpPatBufferIDRange->second) {
1774         ImpPatBufferIDRange->first = BufferID;
1775         ImpPatBufferIDRange->second = BufferID + 1;
1776       } else {
1777         assert(BufferID == ImpPatBufferIDRange->second &&
1778                "expected consecutive source buffer IDs");
1779         ++ImpPatBufferIDRange->second;
1780       }
1781     }
1782 
1783     ImplicitNegativeChecks.push_back(
1784         Pattern(Check::CheckNot, PatternContext.get()));
1785     ImplicitNegativeChecks.back().parsePattern(PatternInBuffer,
1786                                                "IMPLICIT-CHECK", SM, Req);
1787   }
1788 
1789   std::vector<Pattern> DagNotMatches = ImplicitNegativeChecks;
1790 
1791   // LineNumber keeps track of the line on which CheckPrefix instances are
1792   // found.
1793   unsigned LineNumber = 1;
1794 
1795   std::set<StringRef> PrefixesNotFound(Req.CheckPrefixes.begin(),
1796                                        Req.CheckPrefixes.end());
1797   const size_t DistinctPrefixes = PrefixesNotFound.size();
1798   while (true) {
1799     Check::FileCheckType CheckTy;
1800 
1801     // See if a prefix occurs in the memory buffer.
1802     StringRef UsedPrefix;
1803     StringRef AfterSuffix;
1804     std::tie(UsedPrefix, AfterSuffix) =
1805         FindFirstMatchingPrefix(Req, PrefixRE, Buffer, LineNumber, CheckTy);
1806     if (UsedPrefix.empty())
1807       break;
1808     if (CheckTy != Check::CheckComment)
1809       PrefixesNotFound.erase(UsedPrefix);
1810 
1811     assert(UsedPrefix.data() == Buffer.data() &&
1812            "Failed to move Buffer's start forward, or pointed prefix outside "
1813            "of the buffer!");
1814     assert(AfterSuffix.data() >= Buffer.data() &&
1815            AfterSuffix.data() < Buffer.data() + Buffer.size() &&
1816            "Parsing after suffix doesn't start inside of buffer!");
1817 
1818     // Location to use for error messages.
1819     const char *UsedPrefixStart = UsedPrefix.data();
1820 
1821     // Skip the buffer to the end of parsed suffix (or just prefix, if no good
1822     // suffix was processed).
1823     Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
1824                                  : AfterSuffix;
1825 
1826     // Complain about misspelled directives.
1827     if (CheckTy == Check::CheckMisspelled) {
1828       StringRef UsedDirective(UsedPrefix.data(),
1829                               AfterSuffix.data() - UsedPrefix.data());
1830       SM.PrintMessage(SMLoc::getFromPointer(UsedDirective.data()),
1831                       SourceMgr::DK_Error,
1832                       "misspelled directive '" + UsedDirective + "'");
1833       return true;
1834     }
1835 
1836     // Complain about useful-looking but unsupported suffixes.
1837     if (CheckTy == Check::CheckBadNot) {
1838       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
1839                       "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
1840       return true;
1841     }
1842 
1843     // Complain about invalid count specification.
1844     if (CheckTy == Check::CheckBadCount) {
1845       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
1846                       "invalid count in -COUNT specification on prefix '" +
1847                           UsedPrefix + "'");
1848       return true;
1849     }
1850 
1851     // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
1852     // leading whitespace.
1853     if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
1854       Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
1855 
1856     // Scan ahead to the end of line.
1857     size_t EOL = Buffer.find_first_of("\n\r");
1858 
1859     // Remember the location of the start of the pattern, for diagnostics.
1860     SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
1861 
1862     // Extract the pattern from the buffer.
1863     StringRef PatternBuffer = Buffer.substr(0, EOL);
1864     Buffer = Buffer.substr(EOL);
1865 
1866     // If this is a comment, we're done.
1867     if (CheckTy == Check::CheckComment)
1868       continue;
1869 
1870     // Parse the pattern.
1871     Pattern P(CheckTy, PatternContext.get(), LineNumber);
1872     if (P.parsePattern(PatternBuffer, UsedPrefix, SM, Req))
1873       return true;
1874 
1875     // Verify that CHECK-LABEL lines do not define or use variables
1876     if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
1877       SM.PrintMessage(
1878           SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
1879           "found '" + UsedPrefix + "-LABEL:'"
1880                                    " with variable definition or use");
1881       return true;
1882     }
1883 
1884     // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
1885     if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
1886          CheckTy == Check::CheckEmpty) &&
1887         CheckStrings->empty()) {
1888       StringRef Type = CheckTy == Check::CheckNext
1889                            ? "NEXT"
1890                            : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
1891       SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
1892                       SourceMgr::DK_Error,
1893                       "found '" + UsedPrefix + "-" + Type +
1894                           "' without previous '" + UsedPrefix + ": line");
1895       return true;
1896     }
1897 
1898     // Handle CHECK-DAG/-NOT.
1899     if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
1900       DagNotMatches.push_back(P);
1901       continue;
1902     }
1903 
1904     // Okay, add the string we captured to the output vector and move on.
1905     CheckStrings->emplace_back(P, UsedPrefix, PatternLoc);
1906     std::swap(DagNotMatches, CheckStrings->back().DagNotStrings);
1907     DagNotMatches = ImplicitNegativeChecks;
1908   }
1909 
1910   // When there are no used prefixes we report an error except in the case that
1911   // no prefix is specified explicitly but -implicit-check-not is specified.
1912   const bool NoPrefixesFound = PrefixesNotFound.size() == DistinctPrefixes;
1913   const bool SomePrefixesUnexpectedlyNotUsed =
1914       !Req.AllowUnusedPrefixes && !PrefixesNotFound.empty();
1915   if ((NoPrefixesFound || SomePrefixesUnexpectedlyNotUsed) &&
1916       (ImplicitNegativeChecks.empty() || !Req.IsDefaultCheckPrefix)) {
1917     errs() << "error: no check strings found with prefix"
1918            << (PrefixesNotFound.size() > 1 ? "es " : " ");
1919     bool First = true;
1920     for (StringRef MissingPrefix : PrefixesNotFound) {
1921       if (!First)
1922         errs() << ", ";
1923       errs() << "\'" << MissingPrefix << ":'";
1924       First = false;
1925     }
1926     errs() << '\n';
1927     return true;
1928   }
1929 
1930   // Add an EOF pattern for any trailing --implicit-check-not/CHECK-DAG/-NOTs,
1931   // and use the first prefix as a filler for the error message.
1932   if (!DagNotMatches.empty()) {
1933     CheckStrings->emplace_back(
1934         Pattern(Check::CheckEOF, PatternContext.get(), LineNumber + 1),
1935         *Req.CheckPrefixes.begin(), SMLoc::getFromPointer(Buffer.data()));
1936     std::swap(DagNotMatches, CheckStrings->back().DagNotStrings);
1937   }
1938 
1939   return false;
1940 }
1941 
1942 /// Returns either (1) \c ErrorSuccess if there was no error or (2)
1943 /// \c ErrorReported if an error was reported, such as an unexpected match.
1944 static Error printMatch(bool ExpectedMatch, const SourceMgr &SM,
1945                         StringRef Prefix, SMLoc Loc, const Pattern &Pat,
1946                         int MatchedCount, StringRef Buffer,
1947                         Pattern::MatchResult MatchResult,
1948                         const FileCheckRequest &Req,
1949                         std::vector<FileCheckDiag> *Diags) {
1950   // Suppress some verbosity if there's no error.
1951   bool HasError = !ExpectedMatch || MatchResult.TheError;
1952   bool PrintDiag = true;
1953   if (!HasError) {
1954     if (!Req.Verbose)
1955       return ErrorReported::reportedOrSuccess(HasError);
1956     if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
1957       return ErrorReported::reportedOrSuccess(HasError);
1958     // Due to their verbosity, we don't print verbose diagnostics here if we're
1959     // gathering them for Diags to be rendered elsewhere, but we always print
1960     // other diagnostics.
1961     PrintDiag = !Diags;
1962   }
1963 
1964   // Add "found" diagnostic, substitutions, and variable definitions to Diags.
1965   FileCheckDiag::MatchType MatchTy = ExpectedMatch
1966                                          ? FileCheckDiag::MatchFoundAndExpected
1967                                          : FileCheckDiag::MatchFoundButExcluded;
1968   SMRange MatchRange = ProcessMatchResult(MatchTy, SM, Loc, Pat.getCheckTy(),
1969                                           Buffer, MatchResult.TheMatch->Pos,
1970                                           MatchResult.TheMatch->Len, Diags);
1971   if (Diags) {
1972     Pat.printSubstitutions(SM, Buffer, MatchRange, MatchTy, Diags);
1973     Pat.printVariableDefs(SM, MatchTy, Diags);
1974   }
1975   if (!PrintDiag) {
1976     assert(!HasError && "expected to report more diagnostics for error");
1977     return ErrorReported::reportedOrSuccess(HasError);
1978   }
1979 
1980   // Print the match.
1981   std::string Message = formatv("{0}: {1} string found in input",
1982                                 Pat.getCheckTy().getDescription(Prefix),
1983                                 (ExpectedMatch ? "expected" : "excluded"))
1984                             .str();
1985   if (Pat.getCount() > 1)
1986     Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
1987   SM.PrintMessage(
1988       Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
1989   SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
1990                   {MatchRange});
1991 
1992   // Print additional information, which can be useful even if there are errors.
1993   Pat.printSubstitutions(SM, Buffer, MatchRange, MatchTy, nullptr);
1994   Pat.printVariableDefs(SM, MatchTy, nullptr);
1995 
1996   // Print errors and add them to Diags.  We report these errors after the match
1997   // itself because we found them after the match.  If we had found them before
1998   // the match, we'd be in printNoMatch.
1999   handleAllErrors(std::move(MatchResult.TheError),
2000                   [&](const ErrorDiagnostic &E) {
2001                     E.log(errs());
2002                     if (Diags) {
2003                       Diags->emplace_back(SM, Pat.getCheckTy(), Loc,
2004                                           FileCheckDiag::MatchFoundErrorNote,
2005                                           E.getRange(), E.getMessage().str());
2006                     }
2007                   });
2008   return ErrorReported::reportedOrSuccess(HasError);
2009 }
2010 
2011 /// Returns either (1) \c ErrorSuccess if there was no error, or (2)
2012 /// \c ErrorReported if an error was reported, such as an expected match not
2013 /// found.
2014 static Error printNoMatch(bool ExpectedMatch, const SourceMgr &SM,
2015                           StringRef Prefix, SMLoc Loc, const Pattern &Pat,
2016                           int MatchedCount, StringRef Buffer, Error MatchError,
2017                           bool VerboseVerbose,
2018                           std::vector<FileCheckDiag> *Diags) {
2019   // Print any pattern errors, and record them to be added to Diags later.
2020   bool HasError = ExpectedMatch;
2021   bool HasPatternError = false;
2022   FileCheckDiag::MatchType MatchTy = ExpectedMatch
2023                                          ? FileCheckDiag::MatchNoneButExpected
2024                                          : FileCheckDiag::MatchNoneAndExcluded;
2025   SmallVector<std::string, 4> ErrorMsgs;
2026   handleAllErrors(
2027       std::move(MatchError),
2028       [&](const ErrorDiagnostic &E) {
2029         HasError = HasPatternError = true;
2030         MatchTy = FileCheckDiag::MatchNoneForInvalidPattern;
2031         E.log(errs());
2032         if (Diags)
2033           ErrorMsgs.push_back(E.getMessage().str());
2034       },
2035       // NotFoundError is why printNoMatch was invoked.
2036       [](const NotFoundError &E) {});
2037 
2038   // Suppress some verbosity if there's no error.
2039   bool PrintDiag = true;
2040   if (!HasError) {
2041     if (!VerboseVerbose)
2042       return ErrorReported::reportedOrSuccess(HasError);
2043     // Due to their verbosity, we don't print verbose diagnostics here if we're
2044     // gathering them for Diags to be rendered elsewhere, but we always print
2045     // other diagnostics.
2046     PrintDiag = !Diags;
2047   }
2048 
2049   // Add "not found" diagnostic, substitutions, and pattern errors to Diags.
2050   //
2051   // We handle Diags a little differently than the errors we print directly:
2052   // we add the "not found" diagnostic to Diags even if there are pattern
2053   // errors.  The reason is that we need to attach pattern errors as notes
2054   // somewhere in the input, and the input search range from the "not found"
2055   // diagnostic is all we have to anchor them.
2056   SMRange SearchRange = ProcessMatchResult(MatchTy, SM, Loc, Pat.getCheckTy(),
2057                                            Buffer, 0, Buffer.size(), Diags);
2058   if (Diags) {
2059     SMRange NoteRange = SMRange(SearchRange.Start, SearchRange.Start);
2060     for (StringRef ErrorMsg : ErrorMsgs)
2061       Diags->emplace_back(SM, Pat.getCheckTy(), Loc, MatchTy, NoteRange,
2062                           ErrorMsg);
2063     Pat.printSubstitutions(SM, Buffer, SearchRange, MatchTy, Diags);
2064   }
2065   if (!PrintDiag) {
2066     assert(!HasError && "expected to report more diagnostics for error");
2067     return ErrorReported::reportedOrSuccess(HasError);
2068   }
2069 
2070   // Print "not found" diagnostic, except that's implied if we already printed a
2071   // pattern error.
2072   if (!HasPatternError) {
2073     std::string Message = formatv("{0}: {1} string not found in input",
2074                                   Pat.getCheckTy().getDescription(Prefix),
2075                                   (ExpectedMatch ? "expected" : "excluded"))
2076                               .str();
2077     if (Pat.getCount() > 1)
2078       Message +=
2079           formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
2080     SM.PrintMessage(Loc,
2081                     ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark,
2082                     Message);
2083     SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note,
2084                     "scanning from here");
2085   }
2086 
2087   // Print additional information, which can be useful even after a pattern
2088   // error.
2089   Pat.printSubstitutions(SM, Buffer, SearchRange, MatchTy, nullptr);
2090   if (ExpectedMatch)
2091     Pat.printFuzzyMatch(SM, Buffer, Diags);
2092   return ErrorReported::reportedOrSuccess(HasError);
2093 }
2094 
2095 /// Returns either (1) \c ErrorSuccess if there was no error, or (2)
2096 /// \c ErrorReported if an error was reported.
2097 static Error reportMatchResult(bool ExpectedMatch, const SourceMgr &SM,
2098                                StringRef Prefix, SMLoc Loc, const Pattern &Pat,
2099                                int MatchedCount, StringRef Buffer,
2100                                Pattern::MatchResult MatchResult,
2101                                const FileCheckRequest &Req,
2102                                std::vector<FileCheckDiag> *Diags) {
2103   if (MatchResult.TheMatch)
2104     return printMatch(ExpectedMatch, SM, Prefix, Loc, Pat, MatchedCount, Buffer,
2105                       std::move(MatchResult), Req, Diags);
2106   return printNoMatch(ExpectedMatch, SM, Prefix, Loc, Pat, MatchedCount, Buffer,
2107                       std::move(MatchResult.TheError), Req.VerboseVerbose,
2108                       Diags);
2109 }
2110 
2111 /// Counts the number of newlines in the specified range.
2112 static unsigned CountNumNewlinesBetween(StringRef Range,
2113                                         const char *&FirstNewLine) {
2114   unsigned NumNewLines = 0;
2115   while (true) {
2116     // Scan for newline.
2117     Range = Range.substr(Range.find_first_of("\n\r"));
2118     if (Range.empty())
2119       return NumNewLines;
2120 
2121     ++NumNewLines;
2122 
2123     // Handle \n\r and \r\n as a single newline.
2124     if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
2125         (Range[0] != Range[1]))
2126       Range = Range.substr(1);
2127     Range = Range.substr(1);
2128 
2129     if (NumNewLines == 1)
2130       FirstNewLine = Range.begin();
2131   }
2132 }
2133 
2134 size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
2135                               bool IsLabelScanMode, size_t &MatchLen,
2136                               FileCheckRequest &Req,
2137                               std::vector<FileCheckDiag> *Diags) const {
2138   size_t LastPos = 0;
2139   std::vector<const Pattern *> NotStrings;
2140 
2141   // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
2142   // bounds; we have not processed variable definitions within the bounded block
2143   // yet so cannot handle any final CHECK-DAG yet; this is handled when going
2144   // over the block again (including the last CHECK-LABEL) in normal mode.
2145   if (!IsLabelScanMode) {
2146     // Match "dag strings" (with mixed "not strings" if any).
2147     LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
2148     if (LastPos == StringRef::npos)
2149       return StringRef::npos;
2150   }
2151 
2152   // Match itself from the last position after matching CHECK-DAG.
2153   size_t LastMatchEnd = LastPos;
2154   size_t FirstMatchPos = 0;
2155   // Go match the pattern Count times. Majority of patterns only match with
2156   // count 1 though.
2157   assert(Pat.getCount() != 0 && "pattern count can not be zero");
2158   for (int i = 1; i <= Pat.getCount(); i++) {
2159     StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
2160     // get a match at current start point
2161     Pattern::MatchResult MatchResult = Pat.match(MatchBuffer, SM);
2162 
2163     // report
2164     if (Error Err = reportMatchResult(/*ExpectedMatch=*/true, SM, Prefix, Loc,
2165                                       Pat, i, MatchBuffer,
2166                                       std::move(MatchResult), Req, Diags)) {
2167       cantFail(handleErrors(std::move(Err), [&](const ErrorReported &E) {}));
2168       return StringRef::npos;
2169     }
2170 
2171     size_t MatchPos = MatchResult.TheMatch->Pos;
2172     if (i == 1)
2173       FirstMatchPos = LastPos + MatchPos;
2174 
2175     // move start point after the match
2176     LastMatchEnd += MatchPos + MatchResult.TheMatch->Len;
2177   }
2178   // Full match len counts from first match pos.
2179   MatchLen = LastMatchEnd - FirstMatchPos;
2180 
2181   // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
2182   // or CHECK-NOT
2183   if (!IsLabelScanMode) {
2184     size_t MatchPos = FirstMatchPos - LastPos;
2185     StringRef MatchBuffer = Buffer.substr(LastPos);
2186     StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
2187 
2188     // If this check is a "CHECK-NEXT", verify that the previous match was on
2189     // the previous line (i.e. that there is one newline between them).
2190     if (CheckNext(SM, SkippedRegion)) {
2191       ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
2192                          Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
2193                          Diags, Req.Verbose);
2194       return StringRef::npos;
2195     }
2196 
2197     // If this check is a "CHECK-SAME", verify that the previous match was on
2198     // the same line (i.e. that there is no newline between them).
2199     if (CheckSame(SM, SkippedRegion)) {
2200       ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
2201                          Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
2202                          Diags, Req.Verbose);
2203       return StringRef::npos;
2204     }
2205 
2206     // If this match had "not strings", verify that they don't exist in the
2207     // skipped region.
2208     if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
2209       return StringRef::npos;
2210   }
2211 
2212   return FirstMatchPos;
2213 }
2214 
2215 bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
2216   if (Pat.getCheckTy() != Check::CheckNext &&
2217       Pat.getCheckTy() != Check::CheckEmpty)
2218     return false;
2219 
2220   Twine CheckName =
2221       Prefix +
2222       Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
2223 
2224   // Count the number of newlines between the previous match and this one.
2225   const char *FirstNewLine = nullptr;
2226   unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
2227 
2228   if (NumNewLines == 0) {
2229     SM.PrintMessage(Loc, SourceMgr::DK_Error,
2230                     CheckName + ": is on the same line as previous match");
2231     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
2232                     "'next' match was here");
2233     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
2234                     "previous match ended here");
2235     return true;
2236   }
2237 
2238   if (NumNewLines != 1) {
2239     SM.PrintMessage(Loc, SourceMgr::DK_Error,
2240                     CheckName +
2241                         ": is not on the line after the previous match");
2242     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
2243                     "'next' match was here");
2244     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
2245                     "previous match ended here");
2246     SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
2247                     "non-matching line after previous match is here");
2248     return true;
2249   }
2250 
2251   return false;
2252 }
2253 
2254 bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
2255   if (Pat.getCheckTy() != Check::CheckSame)
2256     return false;
2257 
2258   // Count the number of newlines between the previous match and this one.
2259   const char *FirstNewLine = nullptr;
2260   unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
2261 
2262   if (NumNewLines != 0) {
2263     SM.PrintMessage(Loc, SourceMgr::DK_Error,
2264                     Prefix +
2265                         "-SAME: is not on the same line as the previous match");
2266     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
2267                     "'next' match was here");
2268     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
2269                     "previous match ended here");
2270     return true;
2271   }
2272 
2273   return false;
2274 }
2275 
2276 bool FileCheckString::CheckNot(const SourceMgr &SM, StringRef Buffer,
2277                                const std::vector<const Pattern *> &NotStrings,
2278                                const FileCheckRequest &Req,
2279                                std::vector<FileCheckDiag> *Diags) const {
2280   bool DirectiveFail = false;
2281   for (const Pattern *Pat : NotStrings) {
2282     assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
2283     Pattern::MatchResult MatchResult = Pat->match(Buffer, SM);
2284     if (Error Err = reportMatchResult(/*ExpectedMatch=*/false, SM, Prefix,
2285                                       Pat->getLoc(), *Pat, 1, Buffer,
2286                                       std::move(MatchResult), Req, Diags)) {
2287       cantFail(handleErrors(std::move(Err), [&](const ErrorReported &E) {}));
2288       DirectiveFail = true;
2289       continue;
2290     }
2291   }
2292   return DirectiveFail;
2293 }
2294 
2295 size_t FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
2296                                  std::vector<const Pattern *> &NotStrings,
2297                                  const FileCheckRequest &Req,
2298                                  std::vector<FileCheckDiag> *Diags) const {
2299   if (DagNotStrings.empty())
2300     return 0;
2301 
2302   // The start of the search range.
2303   size_t StartPos = 0;
2304 
2305   struct MatchRange {
2306     size_t Pos;
2307     size_t End;
2308   };
2309   // A sorted list of ranges for non-overlapping CHECK-DAG matches.  Match
2310   // ranges are erased from this list once they are no longer in the search
2311   // range.
2312   std::list<MatchRange> MatchRanges;
2313 
2314   // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
2315   // group, so we don't use a range-based for loop here.
2316   for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
2317        PatItr != PatEnd; ++PatItr) {
2318     const Pattern &Pat = *PatItr;
2319     assert((Pat.getCheckTy() == Check::CheckDAG ||
2320             Pat.getCheckTy() == Check::CheckNot) &&
2321            "Invalid CHECK-DAG or CHECK-NOT!");
2322 
2323     if (Pat.getCheckTy() == Check::CheckNot) {
2324       NotStrings.push_back(&Pat);
2325       continue;
2326     }
2327 
2328     assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
2329 
2330     // CHECK-DAG always matches from the start.
2331     size_t MatchLen = 0, MatchPos = StartPos;
2332 
2333     // Search for a match that doesn't overlap a previous match in this
2334     // CHECK-DAG group.
2335     for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
2336       StringRef MatchBuffer = Buffer.substr(MatchPos);
2337       Pattern::MatchResult MatchResult = Pat.match(MatchBuffer, SM);
2338       // With a group of CHECK-DAGs, a single mismatching means the match on
2339       // that group of CHECK-DAGs fails immediately.
2340       if (MatchResult.TheError || Req.VerboseVerbose) {
2341         if (Error Err = reportMatchResult(/*ExpectedMatch=*/true, SM, Prefix,
2342                                           Pat.getLoc(), Pat, 1, MatchBuffer,
2343                                           std::move(MatchResult), Req, Diags)) {
2344           cantFail(
2345               handleErrors(std::move(Err), [&](const ErrorReported &E) {}));
2346           return StringRef::npos;
2347         }
2348       }
2349       MatchLen = MatchResult.TheMatch->Len;
2350       // Re-calc it as the offset relative to the start of the original
2351       // string.
2352       MatchPos += MatchResult.TheMatch->Pos;
2353       MatchRange M{MatchPos, MatchPos + MatchLen};
2354       if (Req.AllowDeprecatedDagOverlap) {
2355         // We don't need to track all matches in this mode, so we just maintain
2356         // one match range that encompasses the current CHECK-DAG group's
2357         // matches.
2358         if (MatchRanges.empty())
2359           MatchRanges.insert(MatchRanges.end(), M);
2360         else {
2361           auto Block = MatchRanges.begin();
2362           Block->Pos = std::min(Block->Pos, M.Pos);
2363           Block->End = std::max(Block->End, M.End);
2364         }
2365         break;
2366       }
2367       // Iterate previous matches until overlapping match or insertion point.
2368       bool Overlap = false;
2369       for (; MI != ME; ++MI) {
2370         if (M.Pos < MI->End) {
2371           // !Overlap => New match has no overlap and is before this old match.
2372           // Overlap => New match overlaps this old match.
2373           Overlap = MI->Pos < M.End;
2374           break;
2375         }
2376       }
2377       if (!Overlap) {
2378         // Insert non-overlapping match into list.
2379         MatchRanges.insert(MI, M);
2380         break;
2381       }
2382       if (Req.VerboseVerbose) {
2383         // Due to their verbosity, we don't print verbose diagnostics here if
2384         // we're gathering them for a different rendering, but we always print
2385         // other diagnostics.
2386         if (!Diags) {
2387           SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
2388           SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
2389           SMRange OldRange(OldStart, OldEnd);
2390           SM.PrintMessage(OldStart, SourceMgr::DK_Note,
2391                           "match discarded, overlaps earlier DAG match here",
2392                           {OldRange});
2393         } else {
2394           SMLoc CheckLoc = Diags->rbegin()->CheckLoc;
2395           for (auto I = Diags->rbegin(), E = Diags->rend();
2396                I != E && I->CheckLoc == CheckLoc; ++I)
2397             I->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
2398         }
2399       }
2400       MatchPos = MI->End;
2401     }
2402     if (!Req.VerboseVerbose)
2403       cantFail(printMatch(
2404           /*ExpectedMatch=*/true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer,
2405           Pattern::MatchResult(MatchPos, MatchLen, Error::success()), Req,
2406           Diags));
2407 
2408     // Handle the end of a CHECK-DAG group.
2409     if (std::next(PatItr) == PatEnd ||
2410         std::next(PatItr)->getCheckTy() == Check::CheckNot) {
2411       if (!NotStrings.empty()) {
2412         // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
2413         // CHECK-DAG, verify that there are no 'not' strings occurred in that
2414         // region.
2415         StringRef SkippedRegion =
2416             Buffer.slice(StartPos, MatchRanges.begin()->Pos);
2417         if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
2418           return StringRef::npos;
2419         // Clear "not strings".
2420         NotStrings.clear();
2421       }
2422       // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
2423       // end of this CHECK-DAG group's match range.
2424       StartPos = MatchRanges.rbegin()->End;
2425       // Don't waste time checking for (impossible) overlaps before that.
2426       MatchRanges.clear();
2427     }
2428   }
2429 
2430   return StartPos;
2431 }
2432 
2433 static bool ValidatePrefixes(StringRef Kind, StringSet<> &UniquePrefixes,
2434                              ArrayRef<StringRef> SuppliedPrefixes) {
2435   for (StringRef Prefix : SuppliedPrefixes) {
2436     if (Prefix.empty()) {
2437       errs() << "error: supplied " << Kind << " prefix must not be the empty "
2438              << "string\n";
2439       return false;
2440     }
2441     static const Regex Validator("^[a-zA-Z0-9_-]*$");
2442     if (!Validator.match(Prefix)) {
2443       errs() << "error: supplied " << Kind << " prefix must start with a "
2444              << "letter and contain only alphanumeric characters, hyphens, and "
2445              << "underscores: '" << Prefix << "'\n";
2446       return false;
2447     }
2448     if (!UniquePrefixes.insert(Prefix).second) {
2449       errs() << "error: supplied " << Kind << " prefix must be unique among "
2450              << "check and comment prefixes: '" << Prefix << "'\n";
2451       return false;
2452     }
2453   }
2454   return true;
2455 }
2456 
2457 static const char *DefaultCheckPrefixes[] = {"CHECK"};
2458 static const char *DefaultCommentPrefixes[] = {"COM", "RUN"};
2459 
2460 bool FileCheck::ValidateCheckPrefixes() {
2461   StringSet<> UniquePrefixes;
2462   // Add default prefixes to catch user-supplied duplicates of them below.
2463   if (Req.CheckPrefixes.empty()) {
2464     for (const char *Prefix : DefaultCheckPrefixes)
2465       UniquePrefixes.insert(Prefix);
2466   }
2467   if (Req.CommentPrefixes.empty()) {
2468     for (const char *Prefix : DefaultCommentPrefixes)
2469       UniquePrefixes.insert(Prefix);
2470   }
2471   // Do not validate the default prefixes, or diagnostics about duplicates might
2472   // incorrectly indicate that they were supplied by the user.
2473   if (!ValidatePrefixes("check", UniquePrefixes, Req.CheckPrefixes))
2474     return false;
2475   if (!ValidatePrefixes("comment", UniquePrefixes, Req.CommentPrefixes))
2476     return false;
2477   return true;
2478 }
2479 
2480 Regex FileCheck::buildCheckPrefixRegex() {
2481   if (Req.CheckPrefixes.empty()) {
2482     for (const char *Prefix : DefaultCheckPrefixes)
2483       Req.CheckPrefixes.push_back(Prefix);
2484     Req.IsDefaultCheckPrefix = true;
2485   }
2486   if (Req.CommentPrefixes.empty()) {
2487     for (const char *Prefix : DefaultCommentPrefixes)
2488       Req.CommentPrefixes.push_back(Prefix);
2489   }
2490 
2491   // We already validated the contents of CheckPrefixes and CommentPrefixes so
2492   // just concatenate them as alternatives.
2493   SmallString<32> PrefixRegexStr;
2494   for (size_t I = 0, E = Req.CheckPrefixes.size(); I != E; ++I) {
2495     if (I != 0)
2496       PrefixRegexStr.push_back('|');
2497     PrefixRegexStr.append(Req.CheckPrefixes[I]);
2498   }
2499   for (StringRef Prefix : Req.CommentPrefixes) {
2500     PrefixRegexStr.push_back('|');
2501     PrefixRegexStr.append(Prefix);
2502   }
2503 
2504   return Regex(PrefixRegexStr);
2505 }
2506 
2507 Error FileCheckPatternContext::defineCmdlineVariables(
2508     ArrayRef<StringRef> CmdlineDefines, SourceMgr &SM) {
2509   assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
2510          "Overriding defined variable with command-line variable definitions");
2511 
2512   if (CmdlineDefines.empty())
2513     return Error::success();
2514 
2515   // Create a string representing the vector of command-line definitions. Each
2516   // definition is on its own line and prefixed with a definition number to
2517   // clarify which definition a given diagnostic corresponds to.
2518   unsigned I = 0;
2519   Error Errs = Error::success();
2520   std::string CmdlineDefsDiag;
2521   SmallVector<std::pair<size_t, size_t>, 4> CmdlineDefsIndices;
2522   for (StringRef CmdlineDef : CmdlineDefines) {
2523     std::string DefPrefix = ("Global define #" + Twine(++I) + ": ").str();
2524     size_t EqIdx = CmdlineDef.find('=');
2525     if (EqIdx == StringRef::npos) {
2526       CmdlineDefsIndices.push_back(std::make_pair(CmdlineDefsDiag.size(), 0));
2527       continue;
2528     }
2529     // Numeric variable definition.
2530     if (CmdlineDef[0] == '#') {
2531       // Append a copy of the command-line definition adapted to use the same
2532       // format as in the input file to be able to reuse
2533       // parseNumericSubstitutionBlock.
2534       CmdlineDefsDiag += (DefPrefix + CmdlineDef + " (parsed as: [[").str();
2535       std::string SubstitutionStr = std::string(CmdlineDef);
2536       SubstitutionStr[EqIdx] = ':';
2537       CmdlineDefsIndices.push_back(
2538           std::make_pair(CmdlineDefsDiag.size(), SubstitutionStr.size()));
2539       CmdlineDefsDiag += (SubstitutionStr + Twine("]])\n")).str();
2540     } else {
2541       CmdlineDefsDiag += DefPrefix;
2542       CmdlineDefsIndices.push_back(
2543           std::make_pair(CmdlineDefsDiag.size(), CmdlineDef.size()));
2544       CmdlineDefsDiag += (CmdlineDef + "\n").str();
2545     }
2546   }
2547 
2548   // Create a buffer with fake command line content in order to display
2549   // parsing diagnostic with location information and point to the
2550   // global definition with invalid syntax.
2551   std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
2552       MemoryBuffer::getMemBufferCopy(CmdlineDefsDiag, "Global defines");
2553   StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
2554   SM.AddNewSourceBuffer(std::move(CmdLineDefsDiagBuffer), SMLoc());
2555 
2556   for (std::pair<size_t, size_t> CmdlineDefIndices : CmdlineDefsIndices) {
2557     StringRef CmdlineDef = CmdlineDefsDiagRef.substr(CmdlineDefIndices.first,
2558                                                      CmdlineDefIndices.second);
2559     if (CmdlineDef.empty()) {
2560       Errs = joinErrors(
2561           std::move(Errs),
2562           ErrorDiagnostic::get(SM, CmdlineDef,
2563                                "missing equal sign in global definition"));
2564       continue;
2565     }
2566 
2567     // Numeric variable definition.
2568     if (CmdlineDef[0] == '#') {
2569       // Now parse the definition both to check that the syntax is correct and
2570       // to create the necessary class instance.
2571       StringRef CmdlineDefExpr = CmdlineDef.substr(1);
2572       std::optional<NumericVariable *> DefinedNumericVariable;
2573       Expected<std::unique_ptr<Expression>> ExpressionResult =
2574           Pattern::parseNumericSubstitutionBlock(CmdlineDefExpr,
2575                                                  DefinedNumericVariable, false,
2576                                                  std::nullopt, this, SM);
2577       if (!ExpressionResult) {
2578         Errs = joinErrors(std::move(Errs), ExpressionResult.takeError());
2579         continue;
2580       }
2581       std::unique_ptr<Expression> Expression = std::move(*ExpressionResult);
2582       // Now evaluate the expression whose value this variable should be set
2583       // to, since the expression of a command-line variable definition should
2584       // only use variables defined earlier on the command-line. If not, this
2585       // is an error and we report it.
2586       Expected<ExpressionValue> Value = Expression->getAST()->eval();
2587       if (!Value) {
2588         Errs = joinErrors(std::move(Errs), Value.takeError());
2589         continue;
2590       }
2591 
2592       assert(DefinedNumericVariable && "No variable defined");
2593       (*DefinedNumericVariable)->setValue(*Value);
2594 
2595       // Record this variable definition.
2596       GlobalNumericVariableTable[(*DefinedNumericVariable)->getName()] =
2597           *DefinedNumericVariable;
2598     } else {
2599       // String variable definition.
2600       std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.split('=');
2601       StringRef CmdlineName = CmdlineNameVal.first;
2602       StringRef OrigCmdlineName = CmdlineName;
2603       Expected<Pattern::VariableProperties> ParseVarResult =
2604           Pattern::parseVariable(CmdlineName, SM);
2605       if (!ParseVarResult) {
2606         Errs = joinErrors(std::move(Errs), ParseVarResult.takeError());
2607         continue;
2608       }
2609       // Check that CmdlineName does not denote a pseudo variable is only
2610       // composed of the parsed numeric variable. This catches cases like
2611       // "FOO+2" in a "FOO+2=10" definition.
2612       if (ParseVarResult->IsPseudo || !CmdlineName.empty()) {
2613         Errs = joinErrors(std::move(Errs),
2614                           ErrorDiagnostic::get(
2615                               SM, OrigCmdlineName,
2616                               "invalid name in string variable definition '" +
2617                                   OrigCmdlineName + "'"));
2618         continue;
2619       }
2620       StringRef Name = ParseVarResult->Name;
2621 
2622       // Detect collisions between string and numeric variables when the former
2623       // is created later than the latter.
2624       if (GlobalNumericVariableTable.contains(Name)) {
2625         Errs = joinErrors(std::move(Errs),
2626                           ErrorDiagnostic::get(SM, Name,
2627                                                "numeric variable with name '" +
2628                                                    Name + "' already exists"));
2629         continue;
2630       }
2631       GlobalVariableTable.insert(CmdlineNameVal);
2632       // Mark the string variable as defined to detect collisions between
2633       // string and numeric variables in defineCmdlineVariables when the latter
2634       // is created later than the former. We cannot reuse GlobalVariableTable
2635       // for this by populating it with an empty string since we would then
2636       // lose the ability to detect the use of an undefined variable in
2637       // match().
2638       DefinedVariableTable[Name] = true;
2639     }
2640   }
2641 
2642   return Errs;
2643 }
2644 
2645 void FileCheckPatternContext::clearLocalVars() {
2646   SmallVector<StringRef, 16> LocalPatternVars, LocalNumericVars;
2647   for (const StringMapEntry<StringRef> &Var : GlobalVariableTable)
2648     if (Var.first()[0] != '$')
2649       LocalPatternVars.push_back(Var.first());
2650 
2651   // Numeric substitution reads the value of a variable directly, not via
2652   // GlobalNumericVariableTable. Therefore, we clear local variables by
2653   // clearing their value which will lead to a numeric substitution failure. We
2654   // also mark the variable for removal from GlobalNumericVariableTable since
2655   // this is what defineCmdlineVariables checks to decide that no global
2656   // variable has been defined.
2657   for (const auto &Var : GlobalNumericVariableTable)
2658     if (Var.first()[0] != '$') {
2659       Var.getValue()->clearValue();
2660       LocalNumericVars.push_back(Var.first());
2661     }
2662 
2663   for (const auto &Var : LocalPatternVars)
2664     GlobalVariableTable.erase(Var);
2665   for (const auto &Var : LocalNumericVars)
2666     GlobalNumericVariableTable.erase(Var);
2667 }
2668 
2669 bool FileCheck::checkInput(SourceMgr &SM, StringRef Buffer,
2670                            std::vector<FileCheckDiag> *Diags) {
2671   bool ChecksFailed = false;
2672 
2673   unsigned i = 0, j = 0, e = CheckStrings->size();
2674   while (true) {
2675     StringRef CheckRegion;
2676     if (j == e) {
2677       CheckRegion = Buffer;
2678     } else {
2679       const FileCheckString &CheckLabelStr = (*CheckStrings)[j];
2680       if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
2681         ++j;
2682         continue;
2683       }
2684 
2685       // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
2686       size_t MatchLabelLen = 0;
2687       size_t MatchLabelPos =
2688           CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, Req, Diags);
2689       if (MatchLabelPos == StringRef::npos)
2690         // Immediately bail if CHECK-LABEL fails, nothing else we can do.
2691         return false;
2692 
2693       CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
2694       Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
2695       ++j;
2696     }
2697 
2698     // Do not clear the first region as it's the one before the first
2699     // CHECK-LABEL and it would clear variables defined on the command-line
2700     // before they get used.
2701     if (i != 0 && Req.EnableVarScope)
2702       PatternContext->clearLocalVars();
2703 
2704     for (; i != j; ++i) {
2705       const FileCheckString &CheckStr = (*CheckStrings)[i];
2706 
2707       // Check each string within the scanned region, including a second check
2708       // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
2709       size_t MatchLen = 0;
2710       size_t MatchPos =
2711           CheckStr.Check(SM, CheckRegion, false, MatchLen, Req, Diags);
2712 
2713       if (MatchPos == StringRef::npos) {
2714         ChecksFailed = true;
2715         i = j;
2716         break;
2717       }
2718 
2719       CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
2720     }
2721 
2722     if (j == e)
2723       break;
2724   }
2725 
2726   // Success if no checks failed.
2727   return !ChecksFailed;
2728 }
2729