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