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