1 //==-- llvm/Support/FileCheck.h ---------------------------*- C++ -*-==//
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
7 //===----------------------------------------------------------------------===//
9 /// \file This file has some utilities to use FileCheck as an API
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_SUPPORT_FILECHECK_H
14 #define LLVM_SUPPORT_FILECHECK_H
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Support/Error.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Regex.h"
22 #include "llvm/Support/SourceMgr.h"
29 /// Contains info about various FileCheck options.
30 struct FileCheckRequest
{
31 std::vector
<std::string
> CheckPrefixes
;
32 bool NoCanonicalizeWhiteSpace
= false;
33 std::vector
<std::string
> ImplicitCheckNot
;
34 std::vector
<std::string
> GlobalDefines
;
35 bool AllowEmptyInput
= false;
36 bool MatchFullLines
= false;
37 bool EnableVarScope
= false;
38 bool AllowDeprecatedDagOverlap
= false;
40 bool VerboseVerbose
= false;
43 //===----------------------------------------------------------------------===//
44 // Numeric substitution handling code.
45 //===----------------------------------------------------------------------===//
47 /// Base class representing the AST of a given expression.
48 class FileCheckExpressionAST
{
50 virtual ~FileCheckExpressionAST() = default;
52 /// Evaluates and \returns the value of the expression represented by this
53 /// AST or an error if evaluation fails.
54 virtual Expected
<uint64_t> eval() const = 0;
57 /// Class representing an unsigned literal in the AST of an expression.
58 class FileCheckExpressionLiteral
: public FileCheckExpressionAST
{
60 /// Actual value of the literal.
64 /// Constructs a literal with the specified value.
65 FileCheckExpressionLiteral(uint64_t Val
) : Value(Val
) {}
67 /// \returns the literal's value.
68 Expected
<uint64_t> eval() const { return Value
; }
71 /// Class to represent an undefined variable error, which quotes that
72 /// variable's name when printed.
73 class FileCheckUndefVarError
: public ErrorInfo
<FileCheckUndefVarError
> {
80 FileCheckUndefVarError(StringRef VarName
) : VarName(VarName
) {}
82 StringRef
getVarName() const { return VarName
; }
84 std::error_code
convertToErrorCode() const override
{
85 return inconvertibleErrorCode();
88 /// Print name of variable associated with this error.
89 void log(raw_ostream
&OS
) const override
{
91 OS
.write_escaped(VarName
) << "\"";
95 /// Class representing a numeric variable and its associated current value.
96 class FileCheckNumericVariable
{
98 /// Name of the numeric variable.
101 /// Value of numeric variable, if defined, or None otherwise.
102 Optional
<uint64_t> Value
;
104 /// Line number where this variable is defined, or None if defined before
105 /// input is parsed. Used to determine whether a variable is defined on the
106 /// same line as a given use.
107 Optional
<size_t> DefLineNumber
;
110 /// Constructor for a variable \p Name defined at line \p DefLineNumber or
111 /// defined before input is parsed if \p DefLineNumber is None.
112 explicit FileCheckNumericVariable(StringRef Name
,
113 Optional
<size_t> DefLineNumber
= None
)
114 : Name(Name
), DefLineNumber(DefLineNumber
) {}
116 /// \returns name of this numeric variable.
117 StringRef
getName() const { return Name
; }
119 /// \returns this variable's value.
120 Optional
<uint64_t> getValue() const { return Value
; }
122 /// Sets value of this numeric variable to \p NewValue.
123 void setValue(uint64_t NewValue
) { Value
= NewValue
; }
125 /// Clears value of this numeric variable, regardless of whether it is
126 /// currently defined or not.
127 void clearValue() { Value
= None
; }
129 /// \returns the line number where this variable is defined, if any, or None
130 /// if defined before input is parsed.
131 Optional
<size_t> getDefLineNumber() { return DefLineNumber
; }
134 /// Class representing the use of a numeric variable in the AST of an
136 class FileCheckNumericVariableUse
: public FileCheckExpressionAST
{
138 /// Name of the numeric variable.
141 /// Pointer to the class instance for the variable this use is about.
142 FileCheckNumericVariable
*NumericVariable
;
145 FileCheckNumericVariableUse(StringRef Name
,
146 FileCheckNumericVariable
*NumericVariable
)
147 : Name(Name
), NumericVariable(NumericVariable
) {}
149 /// \returns the value of the variable referenced by this instance.
150 Expected
<uint64_t> eval() const;
153 /// Type of functions evaluating a given binary operation.
154 using binop_eval_t
= uint64_t (*)(uint64_t, uint64_t);
156 /// Class representing a single binary operation in the AST of an expression.
157 class FileCheckASTBinop
: public FileCheckExpressionAST
{
160 std::unique_ptr
<FileCheckExpressionAST
> LeftOperand
;
163 std::unique_ptr
<FileCheckExpressionAST
> RightOperand
;
165 /// Pointer to function that can evaluate this binary operation.
166 binop_eval_t EvalBinop
;
169 FileCheckASTBinop(binop_eval_t EvalBinop
,
170 std::unique_ptr
<FileCheckExpressionAST
> LeftOp
,
171 std::unique_ptr
<FileCheckExpressionAST
> RightOp
)
172 : EvalBinop(EvalBinop
) {
173 LeftOperand
= std::move(LeftOp
);
174 RightOperand
= std::move(RightOp
);
177 /// Evaluates the value of the binary operation represented by this AST,
178 /// using EvalBinop on the result of recursively evaluating the operands.
179 /// \returns the expression value or an error if an undefined numeric
180 /// variable is used in one of the operands.
181 Expected
<uint64_t> eval() const;
184 class FileCheckPatternContext
;
186 /// Class representing a substitution to perform in the RegExStr string.
187 class FileCheckSubstitution
{
189 /// Pointer to a class instance holding, among other things, the table with
190 /// the values of live string variables at the start of any given CHECK line.
191 /// Used for substituting string variables with the text they were defined
192 /// as. Expressions are linked to the numeric variables they use at
193 /// parse time and directly access the value of the numeric variable to
194 /// evaluate their value.
195 FileCheckPatternContext
*Context
;
197 /// The string that needs to be substituted for something else. For a
198 /// string variable this is its name, otherwise this is the whole expression.
201 // Index in RegExStr of where to do the substitution.
205 FileCheckSubstitution(FileCheckPatternContext
*Context
, StringRef VarName
,
207 : Context(Context
), FromStr(VarName
), InsertIdx(InsertIdx
) {}
209 virtual ~FileCheckSubstitution() = default;
211 /// \returns the string to be substituted for something else.
212 StringRef
getFromString() const { return FromStr
; }
214 /// \returns the index where the substitution is to be performed in RegExStr.
215 size_t getIndex() const { return InsertIdx
; }
217 /// \returns a string containing the result of the substitution represented
218 /// by this class instance or an error if substitution failed.
219 virtual Expected
<std::string
> getResult() const = 0;
222 class FileCheckStringSubstitution
: public FileCheckSubstitution
{
224 FileCheckStringSubstitution(FileCheckPatternContext
*Context
,
225 StringRef VarName
, size_t InsertIdx
)
226 : FileCheckSubstitution(Context
, VarName
, InsertIdx
) {}
228 /// \returns the text that the string variable in this substitution matched
229 /// when defined, or an error if the variable is undefined.
230 Expected
<std::string
> getResult() const override
;
233 class FileCheckNumericSubstitution
: public FileCheckSubstitution
{
235 /// Pointer to the class representing the expression whose value is to be
237 std::unique_ptr
<FileCheckExpressionAST
> ExpressionAST
;
240 FileCheckNumericSubstitution(FileCheckPatternContext
*Context
, StringRef Expr
,
241 std::unique_ptr
<FileCheckExpressionAST
> ExprAST
,
243 : FileCheckSubstitution(Context
, Expr
, InsertIdx
) {
244 ExpressionAST
= std::move(ExprAST
);
247 /// \returns a string containing the result of evaluating the expression in
248 /// this substitution, or an error if evaluation failed.
249 Expected
<std::string
> getResult() const override
;
252 //===----------------------------------------------------------------------===//
253 // Pattern handling code.
254 //===----------------------------------------------------------------------===//
268 /// Indicates the pattern only matches the end of file. This is used for
269 /// trailing CHECK-NOTs.
272 /// Marks when parsing found a -NOT check combined with another CHECK suffix.
275 /// Marks when parsing found a -COUNT directive with invalid count value.
279 class FileCheckType
{
281 int Count
; ///< optional Count for some checks
284 FileCheckType(FileCheckKind Kind
= CheckNone
) : Kind(Kind
), Count(1) {}
285 FileCheckType(const FileCheckType
&) = default;
287 operator FileCheckKind() const { return Kind
; }
289 int getCount() const { return Count
; }
290 FileCheckType
&setCount(int C
);
292 // \returns a description of \p Prefix.
293 std::string
getDescription(StringRef Prefix
) const;
297 struct FileCheckDiag
;
299 /// Class holding the FileCheckPattern global state, shared by all patterns:
300 /// tables holding values of variables and whether they are defined or not at
301 /// any given time in the matching process.
302 class FileCheckPatternContext
{
303 friend class FileCheckPattern
;
306 /// When matching a given pattern, this holds the value of all the string
307 /// variables defined in previous patterns. In a pattern, only the last
308 /// definition for a given variable is recorded in this table.
309 /// Back-references are used for uses after any the other definition.
310 StringMap
<StringRef
> GlobalVariableTable
;
312 /// Map of all string variables defined so far. Used at parse time to detect
313 /// a name conflict between a numeric variable and a string variable when
314 /// the former is defined on a later line than the latter.
315 StringMap
<bool> DefinedVariableTable
;
317 /// When matching a given pattern, this holds the pointers to the classes
318 /// representing the numeric variables defined in previous patterns. When
319 /// matching a pattern all definitions for that pattern are recorded in the
320 /// NumericVariableDefs table in the FileCheckPattern instance of that
322 StringMap
<FileCheckNumericVariable
*> GlobalNumericVariableTable
;
324 /// Pointer to the class instance representing the @LINE pseudo variable for
325 /// easily updating its value.
326 FileCheckNumericVariable
*LineVariable
= nullptr;
328 /// Vector holding pointers to all parsed numeric variables. Used to
329 /// automatically free them once they are guaranteed to no longer be used.
330 std::vector
<std::unique_ptr
<FileCheckNumericVariable
>> NumericVariables
;
332 /// Vector holding pointers to all substitutions. Used to automatically free
333 /// them once they are guaranteed to no longer be used.
334 std::vector
<std::unique_ptr
<FileCheckSubstitution
>> Substitutions
;
337 /// \returns the value of string variable \p VarName or an error if no such
338 /// variable has been defined.
339 Expected
<StringRef
> getPatternVarValue(StringRef VarName
);
341 /// Defines string and numeric variables from definitions given on the
342 /// command line, passed as a vector of [#]VAR=VAL strings in
343 /// \p CmdlineDefines. \returns an error list containing diagnostics against
344 /// \p SM for all definition parsing failures, if any, or Success otherwise.
345 Error
defineCmdlineVariables(std::vector
<std::string
> &CmdlineDefines
,
348 /// Create @LINE pseudo variable. Value is set when pattern are being
350 void createLineVariable();
352 /// Undefines local variables (variables whose name does not start with a '$'
353 /// sign), i.e. removes them from GlobalVariableTable and from
354 /// GlobalNumericVariableTable and also clears the value of numeric
356 void clearLocalVars();
359 /// Makes a new numeric variable and registers it for destruction when the
360 /// context is destroyed.
361 template <class... Types
>
362 FileCheckNumericVariable
*makeNumericVariable(Types
... args
);
364 /// Makes a new string substitution and registers it for destruction when the
365 /// context is destroyed.
366 FileCheckSubstitution
*makeStringSubstitution(StringRef VarName
,
369 /// Makes a new numeric substitution and registers it for destruction when
370 /// the context is destroyed.
371 FileCheckSubstitution
*
372 makeNumericSubstitution(StringRef ExpressionStr
,
373 std::unique_ptr
<FileCheckExpressionAST
> ExpressionAST
,
377 /// Class to represent an error holding a diagnostic with location information
378 /// used when printing it.
379 class FileCheckErrorDiagnostic
: public ErrorInfo
<FileCheckErrorDiagnostic
> {
381 SMDiagnostic Diagnostic
;
386 FileCheckErrorDiagnostic(SMDiagnostic
&&Diag
) : Diagnostic(Diag
) {}
388 std::error_code
convertToErrorCode() const override
{
389 return inconvertibleErrorCode();
392 /// Print diagnostic associated with this error when printing the error.
393 void log(raw_ostream
&OS
) const override
{ Diagnostic
.print(nullptr, OS
); }
395 static Error
get(const SourceMgr
&SM
, SMLoc Loc
, const Twine
&ErrMsg
) {
396 return make_error
<FileCheckErrorDiagnostic
>(
397 SM
.GetMessage(Loc
, SourceMgr::DK_Error
, ErrMsg
));
400 static Error
get(const SourceMgr
&SM
, StringRef Buffer
, const Twine
&ErrMsg
) {
401 return get(SM
, SMLoc::getFromPointer(Buffer
.data()), ErrMsg
);
405 class FileCheckNotFoundError
: public ErrorInfo
<FileCheckNotFoundError
> {
409 std::error_code
convertToErrorCode() const override
{
410 return inconvertibleErrorCode();
413 /// Print diagnostic associated with this error when printing the error.
414 void log(raw_ostream
&OS
) const override
{
415 OS
<< "String not found in input";
419 class FileCheckPattern
{
422 /// A fixed string to match as the pattern or empty if this pattern requires
426 /// A regex string to match as the pattern or empty if this pattern requires
427 /// a fixed string to match.
428 std::string RegExStr
;
430 /// Entries in this vector represent a substitution of a string variable or
431 /// an expression in the RegExStr regex at match time. For example, in the
432 /// case of a CHECK directive with the pattern "foo[[bar]]baz[[#N+1]]",
433 /// RegExStr will contain "foobaz" and we'll get two entries in this vector
434 /// that tells us to insert the value of string variable "bar" at offset 3
435 /// and the value of expression "N+1" at offset 6.
436 std::vector
<FileCheckSubstitution
*> Substitutions
;
438 /// Maps names of string variables defined in a pattern to the number of
439 /// their parenthesis group in RegExStr capturing their last definition.
441 /// E.g. for the pattern "foo[[bar:.*]]baz([[bar]][[QUUX]][[bar:.*]])",
442 /// RegExStr will be "foo(.*)baz(\1<quux value>(.*))" where <quux value> is
443 /// the value captured for QUUX on the earlier line where it was defined, and
444 /// VariableDefs will map "bar" to the third parenthesis group which captures
445 /// the second definition of "bar".
447 /// Note: uses std::map rather than StringMap to be able to get the key when
448 /// iterating over values.
449 std::map
<StringRef
, unsigned> VariableDefs
;
451 /// Structure representing the definition of a numeric variable in a pattern.
452 /// It holds the pointer to the class representing the numeric variable whose
453 /// value is being defined and the number of the parenthesis group in
454 /// RegExStr to capture that value.
455 struct FileCheckNumericVariableMatch
{
456 /// Pointer to class representing the numeric variable whose value is being
458 FileCheckNumericVariable
*DefinedNumericVariable
;
460 /// Number of the parenthesis group in RegExStr that captures the value of
461 /// this numeric variable definition.
462 unsigned CaptureParenGroup
;
465 /// Holds the number of the parenthesis group in RegExStr and pointer to the
466 /// corresponding FileCheckNumericVariable class instance of all numeric
467 /// variable definitions. Used to set the matched value of all those
469 StringMap
<FileCheckNumericVariableMatch
> NumericVariableDefs
;
471 /// Pointer to a class instance holding the global state shared by all
473 /// - separate tables with the values of live string and numeric variables
474 /// respectively at the start of any given CHECK line;
475 /// - table holding whether a string variable has been defined at any given
476 /// point during the parsing phase.
477 FileCheckPatternContext
*Context
;
479 Check::FileCheckType CheckTy
;
481 /// Line number for this CHECK pattern or None if it is an implicit pattern.
482 /// Used to determine whether a variable definition is made on an earlier
483 /// line to the one with this CHECK.
484 Optional
<size_t> LineNumber
;
487 FileCheckPattern(Check::FileCheckType Ty
, FileCheckPatternContext
*Context
,
488 Optional
<size_t> Line
= None
)
489 : Context(Context
), CheckTy(Ty
), LineNumber(Line
) {}
491 /// \returns the location in source code.
492 SMLoc
getLoc() const { return PatternLoc
; }
494 /// \returns the pointer to the global state for all patterns in this
495 /// FileCheck instance.
496 FileCheckPatternContext
*getContext() const { return Context
; }
498 /// \returns whether \p C is a valid first character for a variable name.
499 static bool isValidVarNameStart(char C
);
501 /// Parsing information about a variable.
502 struct VariableProperties
{
507 /// Parses the string at the start of \p Str for a variable name. \returns
508 /// a VariableProperties structure holding the variable name and whether it
509 /// is the name of a pseudo variable, or an error holding a diagnostic
510 /// against \p SM if parsing fail. If parsing was successful, also strips
511 /// \p Str from the variable name.
512 static Expected
<VariableProperties
> parseVariable(StringRef
&Str
,
513 const SourceMgr
&SM
);
514 /// Parses \p Expr for a numeric substitution block at line \p LineNumber,
515 /// or before input is parsed if \p LineNumber is None. Parameter
516 /// \p IsLegacyLineExpr indicates whether \p Expr should be a legacy @LINE
517 /// expression and \p Context points to the class instance holding the live
518 /// string and numeric variables. \returns a pointer to the class instance
519 /// representing the AST of the expression whose value must be substitued, or
520 /// an error holding a diagnostic against \p SM if parsing fails. If
521 /// substitution was successful, sets \p DefinedNumericVariable to point to
522 /// the class representing the numeric variable defined in this numeric
523 /// substitution block, or None if this block does not define any variable.
524 static Expected
<std::unique_ptr
<FileCheckExpressionAST
>>
525 parseNumericSubstitutionBlock(
527 Optional
<FileCheckNumericVariable
*> &DefinedNumericVariable
,
528 bool IsLegacyLineExpr
, Optional
<size_t> LineNumber
,
529 FileCheckPatternContext
*Context
, const SourceMgr
&SM
);
530 /// Parses the pattern in \p PatternStr and initializes this FileCheckPattern
531 /// instance accordingly.
533 /// \p Prefix provides which prefix is being matched, \p Req describes the
534 /// global options that influence the parsing such as whitespace
535 /// canonicalization, \p SM provides the SourceMgr used for error reports.
536 /// \returns true in case of an error, false otherwise.
537 bool parsePattern(StringRef PatternStr
, StringRef Prefix
, SourceMgr
&SM
,
538 const FileCheckRequest
&Req
);
539 /// Matches the pattern string against the input buffer \p Buffer
541 /// \returns the position that is matched or an error indicating why matching
542 /// failed. If there is a match, updates \p MatchLen with the size of the
545 /// The GlobalVariableTable StringMap in the FileCheckPatternContext class
546 /// instance provides the current values of FileCheck string variables and
547 /// is updated if this match defines new values. Likewise, the
548 /// GlobalNumericVariableTable StringMap in the same class provides the
549 /// current values of FileCheck numeric variables and is updated if this
550 /// match defines new numeric values.
551 Expected
<size_t> match(StringRef Buffer
, size_t &MatchLen
,
552 const SourceMgr
&SM
) const;
553 /// Prints the value of successful substitutions or the name of the undefined
554 /// string or numeric variables preventing a successful substitution.
555 void printSubstitutions(const SourceMgr
&SM
, StringRef Buffer
,
556 SMRange MatchRange
= None
) const;
557 void printFuzzyMatch(const SourceMgr
&SM
, StringRef Buffer
,
558 std::vector
<FileCheckDiag
> *Diags
) const;
560 bool hasVariable() const {
561 return !(Substitutions
.empty() && VariableDefs
.empty());
564 Check::FileCheckType
getCheckTy() const { return CheckTy
; }
566 int getCount() const { return CheckTy
.getCount(); }
569 bool AddRegExToRegEx(StringRef RS
, unsigned &CurParen
, SourceMgr
&SM
);
570 void AddBackrefToRegEx(unsigned BackrefNum
);
571 /// Computes an arbitrary estimate for the quality of matching this pattern
572 /// at the start of \p Buffer; a distance of zero should correspond to a
574 unsigned computeMatchDistance(StringRef Buffer
) const;
575 /// Finds the closing sequence of a regex variable usage or definition.
577 /// \p Str has to point in the beginning of the definition (right after the
578 /// opening sequence). \p SM holds the SourceMgr used for error repporting.
579 /// \returns the offset of the closing sequence within Str, or npos if it
581 size_t FindRegexVarEnd(StringRef Str
, SourceMgr
&SM
);
583 /// Parses \p Expr for the name of a numeric variable to be defined at line
584 /// \p LineNumber, or before input is parsed if \p LineNumber is None.
585 /// \returns a pointer to the class instance representing that variable,
586 /// creating it if needed, or an error holding a diagnostic against \p SM
587 /// should defining such a variable be invalid.
588 static Expected
<FileCheckNumericVariable
*> parseNumericVariableDefinition(
589 StringRef
&Expr
, FileCheckPatternContext
*Context
,
590 Optional
<size_t> LineNumber
, const SourceMgr
&SM
);
591 /// Parses \p Name as a (pseudo if \p IsPseudo is true) numeric variable use
592 /// at line \p LineNumber, or before input is parsed if \p LineNumber is
593 /// None. Parameter \p Context points to the class instance holding the live
594 /// string and numeric variables. \returns the pointer to the class instance
595 /// representing that variable if successful, or an error holding a
596 /// diagnostic against \p SM otherwise.
597 static Expected
<std::unique_ptr
<FileCheckNumericVariableUse
>>
598 parseNumericVariableUse(StringRef Name
, bool IsPseudo
,
599 Optional
<size_t> LineNumber
,
600 FileCheckPatternContext
*Context
,
601 const SourceMgr
&SM
);
602 enum class AllowedOperand
{ LineVar
, Literal
, Any
};
603 /// Parses \p Expr for use of a numeric operand at line \p LineNumber, or
604 /// before input is parsed if \p LineNumber is None. Accepts both literal
605 /// values and numeric variables, depending on the value of \p AO. Parameter
606 /// \p Context points to the class instance holding the live string and
607 /// numeric variables. \returns the class representing that operand in the
608 /// AST of the expression or an error holding a diagnostic against \p SM
610 static Expected
<std::unique_ptr
<FileCheckExpressionAST
>>
611 parseNumericOperand(StringRef
&Expr
, AllowedOperand AO
,
612 Optional
<size_t> LineNumber
,
613 FileCheckPatternContext
*Context
, const SourceMgr
&SM
);
614 /// Parses \p Expr for a binary operation at line \p LineNumber, or before
615 /// input is parsed if \p LineNumber is None. The left operand of this binary
616 /// operation is given in \p LeftOp and \p IsLegacyLineExpr indicates whether
617 /// we are parsing a legacy @LINE expression. Parameter \p Context points to
618 /// the class instance holding the live string and numeric variables.
619 /// \returns the class representing the binary operation in the AST of the
620 /// expression, or an error holding a diagnostic against \p SM otherwise.
621 static Expected
<std::unique_ptr
<FileCheckExpressionAST
>>
622 parseBinop(StringRef
&Expr
, std::unique_ptr
<FileCheckExpressionAST
> LeftOp
,
623 bool IsLegacyLineExpr
, Optional
<size_t> LineNumber
,
624 FileCheckPatternContext
*Context
, const SourceMgr
&SM
);
627 //===----------------------------------------------------------------------===//
628 /// Summary of a FileCheck diagnostic.
629 //===----------------------------------------------------------------------===//
631 struct FileCheckDiag
{
632 /// What is the FileCheck directive for this diagnostic?
633 Check::FileCheckType CheckTy
;
634 /// Where is the FileCheck directive for this diagnostic?
635 unsigned CheckLine
, CheckCol
;
636 /// What type of match result does this diagnostic describe?
638 /// A directive's supplied pattern is said to be either expected or excluded
639 /// depending on whether the pattern must have or must not have a match in
640 /// order for the directive to succeed. For example, a CHECK directive's
641 /// pattern is expected, and a CHECK-NOT directive's pattern is excluded.
642 /// All match result types whose names end with "Excluded" are for excluded
643 /// patterns, and all others are for expected patterns.
645 /// There might be more than one match result for a single pattern. For
646 /// example, there might be several discarded matches
647 /// (MatchFoundButDiscarded) before either a good match
648 /// (MatchFoundAndExpected) or a failure to match (MatchNoneButExpected),
649 /// and there might be a fuzzy match (MatchFuzzy) after the latter.
651 /// Indicates a good match for an expected pattern.
652 MatchFoundAndExpected
,
653 /// Indicates a match for an excluded pattern.
654 MatchFoundButExcluded
,
655 /// Indicates a match for an expected pattern, but the match is on the
657 MatchFoundButWrongLine
,
658 /// Indicates a discarded match for an expected pattern.
659 MatchFoundButDiscarded
,
660 /// Indicates no match for an excluded pattern.
661 MatchNoneAndExcluded
,
662 /// Indicates no match for an expected pattern, but this might follow good
663 /// matches when multiple matches are expected for the pattern, or it might
664 /// follow discarded matches for the pattern.
665 MatchNoneButExpected
,
666 /// Indicates a fuzzy match that serves as a suggestion for the next
667 /// intended match for an expected pattern with too few or no good matches.
670 /// The search range if MatchTy is MatchNoneAndExcluded or
671 /// MatchNoneButExpected, or the match range otherwise.
672 unsigned InputStartLine
;
673 unsigned InputStartCol
;
674 unsigned InputEndLine
;
675 unsigned InputEndCol
;
676 FileCheckDiag(const SourceMgr
&SM
, const Check::FileCheckType
&CheckTy
,
677 SMLoc CheckLoc
, MatchType MatchTy
, SMRange InputRange
);
680 //===----------------------------------------------------------------------===//
682 //===----------------------------------------------------------------------===//
684 /// A check that we found in the input file.
685 struct FileCheckString
{
686 /// The pattern to match.
687 FileCheckPattern Pat
;
689 /// Which prefix name this check matched.
692 /// The location in the match file that the check string was specified.
695 /// All of the strings that are disallowed from occurring between this match
696 /// string and the previous one (or start of file).
697 std::vector
<FileCheckPattern
> DagNotStrings
;
699 FileCheckString(const FileCheckPattern
&P
, StringRef S
, SMLoc L
)
700 : Pat(P
), Prefix(S
), Loc(L
) {}
702 /// Matches check string and its "not strings" and/or "dag strings".
703 size_t Check(const SourceMgr
&SM
, StringRef Buffer
, bool IsLabelScanMode
,
704 size_t &MatchLen
, FileCheckRequest
&Req
,
705 std::vector
<FileCheckDiag
> *Diags
) const;
707 /// Verifies that there is a single line in the given \p Buffer. Errors are
708 /// reported against \p SM.
709 bool CheckNext(const SourceMgr
&SM
, StringRef Buffer
) const;
710 /// Verifies that there is no newline in the given \p Buffer. Errors are
711 /// reported against \p SM.
712 bool CheckSame(const SourceMgr
&SM
, StringRef Buffer
) const;
713 /// Verifies that none of the strings in \p NotStrings are found in the given
714 /// \p Buffer. Errors are reported against \p SM and diagnostics recorded in
715 /// \p Diags according to the verbosity level set in \p Req.
716 bool CheckNot(const SourceMgr
&SM
, StringRef Buffer
,
717 const std::vector
<const FileCheckPattern
*> &NotStrings
,
718 const FileCheckRequest
&Req
,
719 std::vector
<FileCheckDiag
> *Diags
) const;
720 /// Matches "dag strings" and their mixed "not strings".
721 size_t CheckDag(const SourceMgr
&SM
, StringRef Buffer
,
722 std::vector
<const FileCheckPattern
*> &NotStrings
,
723 const FileCheckRequest
&Req
,
724 std::vector
<FileCheckDiag
> *Diags
) const;
727 /// FileCheck class takes the request and exposes various methods that
728 /// use information from the request.
730 FileCheckRequest Req
;
731 FileCheckPatternContext PatternContext
;
734 FileCheck(FileCheckRequest Req
) : Req(Req
) {}
736 // Combines the check prefixes into a single regex so that we can efficiently
737 // scan for any of the set.
739 // The semantics are that the longest-match wins which matches our regex
741 Regex
buildCheckPrefixRegex();
743 /// Reads the check file from \p Buffer and records the expected strings it
744 /// contains in the \p CheckStrings vector. Errors are reported against
747 /// Only expected strings whose prefix is one of those listed in \p PrefixRE
748 /// are recorded. \returns true in case of an error, false otherwise.
749 bool ReadCheckFile(SourceMgr
&SM
, StringRef Buffer
, Regex
&PrefixRE
,
750 std::vector
<FileCheckString
> &CheckStrings
);
752 bool ValidateCheckPrefixes();
754 /// Canonicalizes whitespaces in the file. Line endings are replaced with
756 StringRef
CanonicalizeFile(MemoryBuffer
&MB
,
757 SmallVectorImpl
<char> &OutputBuffer
);
759 /// Checks the input to FileCheck provided in the \p Buffer against the
760 /// \p CheckStrings read from the check file and record diagnostics emitted
761 /// in \p Diags. Errors are recorded against \p SM.
763 /// \returns false if the input fails to satisfy the checks.
764 bool CheckInput(SourceMgr
&SM
, StringRef Buffer
,
765 ArrayRef
<FileCheckString
> CheckStrings
,
766 std::vector
<FileCheckDiag
> *Diags
= nullptr);