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