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