]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/include/llvm/Support/FileCheck.h
MFC r355940:
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / include / llvm / Support / FileCheck.h
1 //==-- llvm/Support/FileCheck.h ---------------------------*- C++ -*-==//
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 /// \file This file has some utilities to use FileCheck as an API
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_SUPPORT_FILECHECK_H
14 #define LLVM_SUPPORT_FILECHECK_H
15
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/Regex.h"
19 #include "llvm/Support/SourceMgr.h"
20 #include <vector>
21 #include <map>
22
23 namespace llvm {
24
25 /// Contains info about various FileCheck options.
26 struct FileCheckRequest {
27   std::vector<std::string> CheckPrefixes;
28   bool NoCanonicalizeWhiteSpace = false;
29   std::vector<std::string> ImplicitCheckNot;
30   std::vector<std::string> GlobalDefines;
31   bool AllowEmptyInput = false;
32   bool MatchFullLines = false;
33   bool EnableVarScope = false;
34   bool AllowDeprecatedDagOverlap = false;
35   bool Verbose = false;
36   bool VerboseVerbose = false;
37 };
38
39 //===----------------------------------------------------------------------===//
40 // Numeric substitution handling code.
41 //===----------------------------------------------------------------------===//
42
43 /// Base class representing the AST of a given expression.
44 class FileCheckExpressionAST {
45 public:
46   virtual ~FileCheckExpressionAST() = default;
47
48   /// Evaluates and \returns the value of the expression represented by this
49   /// AST or an error if evaluation fails.
50   virtual Expected<uint64_t> eval() const = 0;
51 };
52
53 /// Class representing an unsigned literal in the AST of an expression.
54 class FileCheckExpressionLiteral : public FileCheckExpressionAST {
55 private:
56   /// Actual value of the literal.
57   uint64_t Value;
58
59 public:
60   /// Constructs a literal with the specified value.
61   FileCheckExpressionLiteral(uint64_t Val) : Value(Val) {}
62
63   /// \returns the literal's value.
64   Expected<uint64_t> eval() const { return Value; }
65 };
66
67 /// Class to represent an undefined variable error, which quotes that
68 /// variable's name when printed.
69 class FileCheckUndefVarError : public ErrorInfo<FileCheckUndefVarError> {
70 private:
71   StringRef VarName;
72
73 public:
74   static char ID;
75
76   FileCheckUndefVarError(StringRef VarName) : VarName(VarName) {}
77
78   StringRef getVarName() const { return VarName; }
79
80   std::error_code convertToErrorCode() const override {
81     return inconvertibleErrorCode();
82   }
83
84   /// Print name of variable associated with this error.
85   void log(raw_ostream &OS) const override {
86     OS << "\"";
87     OS.write_escaped(VarName) << "\"";
88   }
89 };
90
91 /// Class representing a numeric variable and its associated current value.
92 class FileCheckNumericVariable {
93 private:
94   /// Name of the numeric variable.
95   StringRef Name;
96
97   /// Value of numeric variable, if defined, or None otherwise.
98   Optional<uint64_t> Value;
99
100   /// Line number where this variable is defined, or None if defined before
101   /// input is parsed. Used to determine whether a variable is defined on the
102   /// same line as a given use.
103   Optional<size_t> DefLineNumber;
104
105 public:
106   /// Constructor for a variable \p Name defined at line \p DefLineNumber or
107   /// defined before input is parsed if DefLineNumber is None.
108   FileCheckNumericVariable(StringRef Name,
109                            Optional<size_t> DefLineNumber = None)
110       : Name(Name), DefLineNumber(DefLineNumber) {}
111
112   /// \returns name of this numeric variable.
113   StringRef getName() const { return Name; }
114
115   /// \returns this variable's value.
116   Optional<uint64_t> getValue() const { return Value; }
117
118   /// Sets value of this numeric variable, if undefined. Triggers an assertion
119   /// failure if the variable is actually defined.
120   void setValue(uint64_t Value);
121
122   /// Clears value of this numeric variable, regardless of whether it is
123   /// currently defined or not.
124   void clearValue();
125
126   /// \returns the line number where this variable is defined, if any, or None
127   /// if defined before input is parsed.
128   Optional<size_t> getDefLineNumber() { return DefLineNumber; }
129 };
130
131 /// Class representing the use of a numeric variable in the AST of an
132 /// expression.
133 class FileCheckNumericVariableUse : public FileCheckExpressionAST {
134 private:
135   /// Name of the numeric variable.
136   StringRef Name;
137
138   /// Pointer to the class instance for the variable this use is about.
139   FileCheckNumericVariable *NumericVariable;
140
141 public:
142   FileCheckNumericVariableUse(StringRef Name,
143                               FileCheckNumericVariable *NumericVariable)
144       : Name(Name), NumericVariable(NumericVariable) {}
145
146   /// \returns the value of the variable referenced by this instance.
147   Expected<uint64_t> eval() const;
148 };
149
150 /// Type of functions evaluating a given binary operation.
151 using binop_eval_t = uint64_t (*)(uint64_t, uint64_t);
152
153 /// Class representing a single binary operation in the AST of an expression.
154 class FileCheckASTBinop : public FileCheckExpressionAST {
155 private:
156   /// Left operand.
157   std::unique_ptr<FileCheckExpressionAST> LeftOperand;
158
159   /// Right operand.
160   std::unique_ptr<FileCheckExpressionAST> RightOperand;
161
162   /// Pointer to function that can evaluate this binary operation.
163   binop_eval_t EvalBinop;
164
165 public:
166   FileCheckASTBinop(binop_eval_t EvalBinop,
167                     std::unique_ptr<FileCheckExpressionAST> LeftOp,
168                     std::unique_ptr<FileCheckExpressionAST> RightOp)
169       : EvalBinop(EvalBinop) {
170     LeftOperand = std::move(LeftOp);
171     RightOperand = std::move(RightOp);
172   }
173
174   /// Evaluates the value of the binary operation represented by this AST,
175   /// using EvalBinop on the result of recursively evaluating the operands.
176   /// \returns the expression value or an error if an undefined numeric
177   /// variable is used in one of the operands.
178   Expected<uint64_t> eval() const;
179 };
180
181 class FileCheckPatternContext;
182
183 /// Class representing a substitution to perform in the RegExStr string.
184 class FileCheckSubstitution {
185 protected:
186   /// Pointer to a class instance holding, among other things, the table with
187   /// the values of live string variables at the start of any given CHECK line.
188   /// Used for substituting string variables with the text they were defined
189   /// as. Expressions are linked to the numeric variables they use at
190   /// parse time and directly access the value of the numeric variable to
191   /// evaluate their value.
192   FileCheckPatternContext *Context;
193
194   /// The string that needs to be substituted for something else. For a
195   /// string variable this is its name, otherwise this is the whole expression.
196   StringRef FromStr;
197
198   // Index in RegExStr of where to do the substitution.
199   size_t InsertIdx;
200
201 public:
202   FileCheckSubstitution(FileCheckPatternContext *Context, StringRef VarName,
203                         size_t InsertIdx)
204       : Context(Context), FromStr(VarName), InsertIdx(InsertIdx) {}
205
206   virtual ~FileCheckSubstitution() = default;
207
208   /// \returns the string to be substituted for something else.
209   StringRef getFromString() const { return FromStr; }
210
211   /// \returns the index where the substitution is to be performed in RegExStr.
212   size_t getIndex() const { return InsertIdx; }
213
214   /// \returns a string containing the result of the substitution represented
215   /// by this class instance or an error if substitution failed.
216   virtual Expected<std::string> getResult() const = 0;
217 };
218
219 class FileCheckStringSubstitution : public FileCheckSubstitution {
220 public:
221   FileCheckStringSubstitution(FileCheckPatternContext *Context,
222                               StringRef VarName, size_t InsertIdx)
223       : FileCheckSubstitution(Context, VarName, InsertIdx) {}
224
225   /// \returns the text that the string variable in this substitution matched
226   /// when defined, or an error if the variable is undefined.
227   Expected<std::string> getResult() const override;
228 };
229
230 class FileCheckNumericSubstitution : public FileCheckSubstitution {
231 private:
232   /// Pointer to the class representing the expression whose value is to be
233   /// substituted.
234   std::unique_ptr<FileCheckExpressionAST> ExpressionAST;
235
236 public:
237   FileCheckNumericSubstitution(FileCheckPatternContext *Context, StringRef Expr,
238                                std::unique_ptr<FileCheckExpressionAST> ExprAST,
239                                size_t InsertIdx)
240       : FileCheckSubstitution(Context, Expr, InsertIdx) {
241     ExpressionAST = std::move(ExprAST);
242   }
243
244   /// \returns a string containing the result of evaluating the expression in
245   /// this substitution, or an error if evaluation failed.
246   Expected<std::string> getResult() const override;
247 };
248
249 //===----------------------------------------------------------------------===//
250 // Pattern handling code.
251 //===----------------------------------------------------------------------===//
252
253 namespace Check {
254
255 enum FileCheckKind {
256   CheckNone = 0,
257   CheckPlain,
258   CheckNext,
259   CheckSame,
260   CheckNot,
261   CheckDAG,
262   CheckLabel,
263   CheckEmpty,
264
265   /// Indicates the pattern only matches the end of file. This is used for
266   /// trailing CHECK-NOTs.
267   CheckEOF,
268
269   /// Marks when parsing found a -NOT check combined with another CHECK suffix.
270   CheckBadNot,
271
272   /// Marks when parsing found a -COUNT directive with invalid count value.
273   CheckBadCount
274 };
275
276 class FileCheckType {
277   FileCheckKind Kind;
278   int Count; ///< optional Count for some checks
279
280 public:
281   FileCheckType(FileCheckKind Kind = CheckNone) : Kind(Kind), Count(1) {}
282   FileCheckType(const FileCheckType &) = default;
283
284   operator FileCheckKind() const { return Kind; }
285
286   int getCount() const { return Count; }
287   FileCheckType &setCount(int C);
288
289   // \returns a description of \p Prefix.
290   std::string getDescription(StringRef Prefix) const;
291 };
292 } // namespace Check
293
294 struct FileCheckDiag;
295
296 /// Class holding the FileCheckPattern global state, shared by all patterns:
297 /// tables holding values of variables and whether they are defined or not at
298 /// any given time in the matching process.
299 class FileCheckPatternContext {
300   friend class FileCheckPattern;
301
302 private:
303   /// When matching a given pattern, this holds the value of all the string
304   /// variables defined in previous patterns. In a pattern, only the last
305   /// definition for a given variable is recorded in this table.
306   /// Back-references are used for uses after any the other definition.
307   StringMap<StringRef> GlobalVariableTable;
308
309   /// Map of all string variables defined so far. Used at parse time to detect
310   /// a name conflict between a numeric variable and a string variable when
311   /// the former is defined on a later line than the latter.
312   StringMap<bool> DefinedVariableTable;
313
314   /// When matching a given pattern, this holds the pointers to the classes
315   /// representing the numeric variables defined in previous patterns. When
316   /// matching a pattern all definitions for that pattern are recorded in the
317   /// NumericVariableDefs table in the FileCheckPattern instance of that
318   /// pattern.
319   StringMap<FileCheckNumericVariable *> GlobalNumericVariableTable;
320
321   /// Pointer to the class instance representing the @LINE pseudo variable for
322   /// easily updating its value.
323   FileCheckNumericVariable *LineVariable = nullptr;
324
325   /// Vector holding pointers to all parsed numeric variables. Used to
326   /// automatically free them once they are guaranteed to no longer be used.
327   std::vector<std::unique_ptr<FileCheckNumericVariable>> NumericVariables;
328
329   /// Vector holding pointers to all substitutions. Used to automatically free
330   /// them once they are guaranteed to no longer be used.
331   std::vector<std::unique_ptr<FileCheckSubstitution>> Substitutions;
332
333 public:
334   /// \returns the value of string variable \p VarName or an error if no such
335   /// variable has been defined.
336   Expected<StringRef> getPatternVarValue(StringRef VarName);
337
338   /// Defines string and numeric variables from definitions given on the
339   /// command line, passed as a vector of [#]VAR=VAL strings in
340   /// \p CmdlineDefines. \returns an error list containing diagnostics against
341   /// \p SM for all definition parsing failures, if any, or Success otherwise.
342   Error defineCmdlineVariables(std::vector<std::string> &CmdlineDefines,
343                                SourceMgr &SM);
344
345   /// Create @LINE pseudo variable. Value is set when pattern are being
346   /// matched.
347   void createLineVariable();
348
349   /// Undefines local variables (variables whose name does not start with a '$'
350   /// sign), i.e. removes them from GlobalVariableTable and from
351   /// GlobalNumericVariableTable and also clears the value of numeric
352   /// variables.
353   void clearLocalVars();
354
355 private:
356   /// Makes a new numeric variable and registers it for destruction when the
357   /// context is destroyed.
358   template <class... Types>
359   FileCheckNumericVariable *makeNumericVariable(Types... args);
360
361   /// Makes a new string substitution and registers it for destruction when the
362   /// context is destroyed.
363   FileCheckSubstitution *makeStringSubstitution(StringRef VarName,
364                                                 size_t InsertIdx);
365
366   /// Makes a new numeric substitution and registers it for destruction when
367   /// the context is destroyed.
368   FileCheckSubstitution *
369   makeNumericSubstitution(StringRef ExpressionStr,
370                           std::unique_ptr<FileCheckExpressionAST> ExpressionAST,
371                           size_t InsertIdx);
372 };
373
374 /// Class to represent an error holding a diagnostic with location information
375 /// used when printing it.
376 class FileCheckErrorDiagnostic : public ErrorInfo<FileCheckErrorDiagnostic> {
377 private:
378   SMDiagnostic Diagnostic;
379
380 public:
381   static char ID;
382
383   FileCheckErrorDiagnostic(SMDiagnostic &&Diag) : Diagnostic(Diag) {}
384
385   std::error_code convertToErrorCode() const override {
386     return inconvertibleErrorCode();
387   }
388
389   /// Print diagnostic associated with this error when printing the error.
390   void log(raw_ostream &OS) const override { Diagnostic.print(nullptr, OS); }
391
392   static Error get(const SourceMgr &SM, SMLoc Loc, const Twine &ErrMsg) {
393     return make_error<FileCheckErrorDiagnostic>(
394         SM.GetMessage(Loc, SourceMgr::DK_Error, ErrMsg));
395   }
396
397   static Error get(const SourceMgr &SM, StringRef Buffer, const Twine &ErrMsg) {
398     return get(SM, SMLoc::getFromPointer(Buffer.data()), ErrMsg);
399   }
400 };
401
402 class FileCheckNotFoundError : public ErrorInfo<FileCheckNotFoundError> {
403 public:
404   static char ID;
405
406   std::error_code convertToErrorCode() const override {
407     return inconvertibleErrorCode();
408   }
409
410   /// Print diagnostic associated with this error when printing the error.
411   void log(raw_ostream &OS) const override {
412     OS << "String not found in input";
413   }
414 };
415
416 class FileCheckPattern {
417   SMLoc PatternLoc;
418
419   /// A fixed string to match as the pattern or empty if this pattern requires
420   /// a regex match.
421   StringRef FixedStr;
422
423   /// A regex string to match as the pattern or empty if this pattern requires
424   /// a fixed string to match.
425   std::string RegExStr;
426
427   /// Entries in this vector represent a substitution of a string variable or
428   /// an expression in the RegExStr regex at match time. For example, in the
429   /// case of a CHECK directive with the pattern "foo[[bar]]baz[[#N+1]]",
430   /// RegExStr will contain "foobaz" and we'll get two entries in this vector
431   /// that tells us to insert the value of string variable "bar" at offset 3
432   /// and the value of expression "N+1" at offset 6.
433   std::vector<FileCheckSubstitution *> Substitutions;
434
435   /// Maps names of string variables defined in a pattern to the number of
436   /// their parenthesis group in RegExStr capturing their last definition.
437   ///
438   /// E.g. for the pattern "foo[[bar:.*]]baz([[bar]][[QUUX]][[bar:.*]])",
439   /// RegExStr will be "foo(.*)baz(\1<quux value>(.*))" where <quux value> is
440   /// the value captured for QUUX on the earlier line where it was defined, and
441   /// VariableDefs will map "bar" to the third parenthesis group which captures
442   /// the second definition of "bar".
443   ///
444   /// Note: uses std::map rather than StringMap to be able to get the key when
445   /// iterating over values.
446   std::map<StringRef, unsigned> VariableDefs;
447
448   /// Structure representing the definition of a numeric variable in a pattern.
449   /// It holds the pointer to the class representing the numeric variable whose
450   /// value is being defined and the number of the parenthesis group in
451   /// RegExStr to capture that value.
452   struct FileCheckNumericVariableMatch {
453     /// Pointer to class representing the numeric variable whose value is being
454     /// defined.
455     FileCheckNumericVariable *DefinedNumericVariable;
456
457     /// Number of the parenthesis group in RegExStr that captures the value of
458     /// this numeric variable definition.
459     unsigned CaptureParenGroup;
460   };
461
462   /// Holds the number of the parenthesis group in RegExStr and pointer to the
463   /// corresponding FileCheckNumericVariable class instance of all numeric
464   /// variable definitions. Used to set the matched value of all those
465   /// variables.
466   StringMap<FileCheckNumericVariableMatch> NumericVariableDefs;
467
468   /// Pointer to a class instance holding the global state shared by all
469   /// patterns:
470   /// - separate tables with the values of live string and numeric variables
471   ///   respectively at the start of any given CHECK line;
472   /// - table holding whether a string variable has been defined at any given
473   ///   point during the parsing phase.
474   FileCheckPatternContext *Context;
475
476   Check::FileCheckType CheckTy;
477
478   /// Line number for this CHECK pattern or None if it is an implicit pattern.
479   /// Used to determine whether a variable definition is made on an earlier
480   /// line to the one with this CHECK.
481   Optional<size_t> LineNumber;
482
483 public:
484   FileCheckPattern(Check::FileCheckType Ty, FileCheckPatternContext *Context,
485                    Optional<size_t> Line = None)
486       : Context(Context), CheckTy(Ty), LineNumber(Line) {}
487
488   /// \returns the location in source code.
489   SMLoc getLoc() const { return PatternLoc; }
490
491   /// \returns the pointer to the global state for all patterns in this
492   /// FileCheck instance.
493   FileCheckPatternContext *getContext() const { return Context; }
494
495   /// \returns whether \p C is a valid first character for a variable name.
496   static bool isValidVarNameStart(char C);
497
498   /// Parsing information about a variable.
499   struct VariableProperties {
500     StringRef Name;
501     bool IsPseudo;
502   };
503
504   /// Parses the string at the start of \p Str for a variable name. \returns
505   /// a VariableProperties structure holding the variable name and whether it
506   /// is the name of a pseudo variable, or an error holding a diagnostic
507   /// against \p SM if parsing fail. If parsing was successful, also strips
508   /// \p Str from the variable name.
509   static Expected<VariableProperties> parseVariable(StringRef &Str,
510                                                     const SourceMgr &SM);
511   /// Parses \p Expr for the name of a numeric variable to be defined at line
512   /// \p LineNumber or before input is parsed if \p LineNumber is None.
513   /// \returns a pointer to the class instance representing that variable,
514   /// creating it if needed, or an error holding a diagnostic against \p SM
515   /// should defining such a variable be invalid.
516   static Expected<FileCheckNumericVariable *> parseNumericVariableDefinition(
517       StringRef &Expr, FileCheckPatternContext *Context,
518       Optional<size_t> LineNumber, const SourceMgr &SM);
519   /// Parses \p Expr for a numeric substitution block. Parameter
520   /// \p IsLegacyLineExpr indicates whether \p Expr should be a legacy @LINE
521   /// expression. \returns a pointer to the class instance representing the AST
522   /// of the expression whose value must be substituted, or an error holding a
523   /// diagnostic against \p SM if parsing fails. If substitution was
524   /// successful, sets \p DefinedNumericVariable to point to the class
525   /// representing the numeric variable being defined in this numeric
526   /// substitution block, or None if this block does not define any variable.
527   Expected<std::unique_ptr<FileCheckExpressionAST>>
528   parseNumericSubstitutionBlock(
529       StringRef Expr,
530       Optional<FileCheckNumericVariable *> &DefinedNumericVariable,
531       bool IsLegacyLineExpr, const SourceMgr &SM) const;
532   /// Parses the pattern in \p PatternStr and initializes this FileCheckPattern
533   /// instance accordingly.
534   ///
535   /// \p Prefix provides which prefix is being matched, \p Req describes the
536   /// global options that influence the parsing such as whitespace
537   /// canonicalization, \p SM provides the SourceMgr used for error reports.
538   /// \returns true in case of an error, false otherwise.
539   bool parsePattern(StringRef PatternStr, StringRef Prefix, SourceMgr &SM,
540                     const FileCheckRequest &Req);
541   /// Matches the pattern string against the input buffer \p Buffer
542   ///
543   /// \returns the position that is matched or an error indicating why matching
544   /// failed. If there is a match, updates \p MatchLen with the size of the
545   /// matched string.
546   ///
547   /// The GlobalVariableTable StringMap in the FileCheckPatternContext class
548   /// instance provides the current values of FileCheck string variables and
549   /// is updated if this match defines new values. Likewise, the
550   /// GlobalNumericVariableTable StringMap in the same class provides the
551   /// current values of FileCheck numeric variables and is updated if this
552   /// match defines new numeric values.
553   Expected<size_t> match(StringRef Buffer, size_t &MatchLen,
554                          const SourceMgr &SM) const;
555   /// Prints the value of successful substitutions or the name of the undefined
556   /// string or numeric variables preventing a successful substitution.
557   void printSubstitutions(const SourceMgr &SM, StringRef Buffer,
558                           SMRange MatchRange = None) const;
559   void printFuzzyMatch(const SourceMgr &SM, StringRef Buffer,
560                        std::vector<FileCheckDiag> *Diags) const;
561
562   bool hasVariable() const {
563     return !(Substitutions.empty() && VariableDefs.empty());
564   }
565
566   Check::FileCheckType getCheckTy() const { return CheckTy; }
567
568   int getCount() const { return CheckTy.getCount(); }
569
570 private:
571   bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
572   void AddBackrefToRegEx(unsigned BackrefNum);
573   /// Computes an arbitrary estimate for the quality of matching this pattern
574   /// at the start of \p Buffer; a distance of zero should correspond to a
575   /// perfect match.
576   unsigned computeMatchDistance(StringRef Buffer) const;
577   /// Finds the closing sequence of a regex variable usage or definition.
578   ///
579   /// \p Str has to point in the beginning of the definition (right after the
580   /// opening sequence). \p SM holds the SourceMgr used for error repporting.
581   ///  \returns the offset of the closing sequence within Str, or npos if it
582   /// was not found.
583   size_t FindRegexVarEnd(StringRef Str, SourceMgr &SM);
584
585   /// Parses \p Name as a (pseudo if \p IsPseudo is true) numeric variable use.
586   /// \returns the pointer to the class instance representing that variable if
587   /// successful, or an error holding a diagnostic against \p SM otherwise.
588   Expected<std::unique_ptr<FileCheckNumericVariableUse>>
589   parseNumericVariableUse(StringRef Name, bool IsPseudo,
590                           const SourceMgr &SM) const;
591   enum class AllowedOperand { LineVar, Literal, Any };
592   /// Parses \p Expr for use of a numeric operand. Accepts both literal values
593   /// and numeric variables, depending on the value of \p AO. \returns the
594   /// class representing that operand in the AST of the expression or an error
595   /// holding a diagnostic against \p SM otherwise.
596   Expected<std::unique_ptr<FileCheckExpressionAST>>
597   parseNumericOperand(StringRef &Expr, AllowedOperand AO,
598                       const SourceMgr &SM) const;
599   /// Parses \p Expr for a binary operation. The left operand of this binary
600   /// operation is given in \p LeftOp and \p IsLegacyLineExpr indicates whether
601   /// we are parsing a legacy @LINE expression. \returns the class representing
602   /// the binary operation in the AST of the expression, or an error holding a
603   /// diagnostic against \p SM otherwise.
604   Expected<std::unique_ptr<FileCheckExpressionAST>>
605   parseBinop(StringRef &Expr, std::unique_ptr<FileCheckExpressionAST> LeftOp,
606              bool IsLegacyLineExpr, const SourceMgr &SM) const;
607 };
608
609 //===----------------------------------------------------------------------===//
610 /// Summary of a FileCheck diagnostic.
611 //===----------------------------------------------------------------------===//
612
613 struct FileCheckDiag {
614   /// What is the FileCheck directive for this diagnostic?
615   Check::FileCheckType CheckTy;
616   /// Where is the FileCheck directive for this diagnostic?
617   unsigned CheckLine, CheckCol;
618   /// What type of match result does this diagnostic describe?
619   ///
620   /// A directive's supplied pattern is said to be either expected or excluded
621   /// depending on whether the pattern must have or must not have a match in
622   /// order for the directive to succeed.  For example, a CHECK directive's
623   /// pattern is expected, and a CHECK-NOT directive's pattern is excluded.
624   /// All match result types whose names end with "Excluded" are for excluded
625   /// patterns, and all others are for expected patterns.
626   ///
627   /// There might be more than one match result for a single pattern.  For
628   /// example, there might be several discarded matches
629   /// (MatchFoundButDiscarded) before either a good match
630   /// (MatchFoundAndExpected) or a failure to match (MatchNoneButExpected),
631   /// and there might be a fuzzy match (MatchFuzzy) after the latter.
632   enum MatchType {
633     /// Indicates a good match for an expected pattern.
634     MatchFoundAndExpected,
635     /// Indicates a match for an excluded pattern.
636     MatchFoundButExcluded,
637     /// Indicates a match for an expected pattern, but the match is on the
638     /// wrong line.
639     MatchFoundButWrongLine,
640     /// Indicates a discarded match for an expected pattern.
641     MatchFoundButDiscarded,
642     /// Indicates no match for an excluded pattern.
643     MatchNoneAndExcluded,
644     /// Indicates no match for an expected pattern, but this might follow good
645     /// matches when multiple matches are expected for the pattern, or it might
646     /// follow discarded matches for the pattern.
647     MatchNoneButExpected,
648     /// Indicates a fuzzy match that serves as a suggestion for the next
649     /// intended match for an expected pattern with too few or no good matches.
650     MatchFuzzy,
651   } MatchTy;
652   /// The search range if MatchTy is MatchNoneAndExcluded or
653   /// MatchNoneButExpected, or the match range otherwise.
654   unsigned InputStartLine;
655   unsigned InputStartCol;
656   unsigned InputEndLine;
657   unsigned InputEndCol;
658   FileCheckDiag(const SourceMgr &SM, const Check::FileCheckType &CheckTy,
659                 SMLoc CheckLoc, MatchType MatchTy, SMRange InputRange);
660 };
661
662 //===----------------------------------------------------------------------===//
663 // Check Strings.
664 //===----------------------------------------------------------------------===//
665
666 /// A check that we found in the input file.
667 struct FileCheckString {
668   /// The pattern to match.
669   FileCheckPattern Pat;
670
671   /// Which prefix name this check matched.
672   StringRef Prefix;
673
674   /// The location in the match file that the check string was specified.
675   SMLoc Loc;
676
677   /// All of the strings that are disallowed from occurring between this match
678   /// string and the previous one (or start of file).
679   std::vector<FileCheckPattern> DagNotStrings;
680
681   FileCheckString(const FileCheckPattern &P, StringRef S, SMLoc L)
682       : Pat(P), Prefix(S), Loc(L) {}
683
684   /// Matches check string and its "not strings" and/or "dag strings".
685   size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode,
686                size_t &MatchLen, FileCheckRequest &Req,
687                std::vector<FileCheckDiag> *Diags) const;
688
689   /// Verifies that there is a single line in the given \p Buffer. Errors are
690   /// reported against \p SM.
691   bool CheckNext(const SourceMgr &SM, StringRef Buffer) const;
692   /// Verifies that there is no newline in the given \p Buffer. Errors are
693   /// reported against \p SM.
694   bool CheckSame(const SourceMgr &SM, StringRef Buffer) const;
695   /// Verifies that none of the strings in \p NotStrings are found in the given
696   /// \p Buffer. Errors are reported against \p SM and diagnostics recorded in
697   /// \p Diags according to the verbosity level set in \p Req.
698   bool CheckNot(const SourceMgr &SM, StringRef Buffer,
699                 const std::vector<const FileCheckPattern *> &NotStrings,
700                 const FileCheckRequest &Req,
701                 std::vector<FileCheckDiag> *Diags) const;
702   /// Matches "dag strings" and their mixed "not strings".
703   size_t CheckDag(const SourceMgr &SM, StringRef Buffer,
704                   std::vector<const FileCheckPattern *> &NotStrings,
705                   const FileCheckRequest &Req,
706                   std::vector<FileCheckDiag> *Diags) const;
707 };
708
709 /// FileCheck class takes the request and exposes various methods that
710 /// use information from the request.
711 class FileCheck {
712   FileCheckRequest Req;
713   FileCheckPatternContext PatternContext;
714
715 public:
716   FileCheck(FileCheckRequest Req) : Req(Req) {}
717
718   // Combines the check prefixes into a single regex so that we can efficiently
719   // scan for any of the set.
720   //
721   // The semantics are that the longest-match wins which matches our regex
722   // library.
723   Regex buildCheckPrefixRegex();
724
725   /// Reads the check file from \p Buffer and records the expected strings it
726   /// contains in the \p CheckStrings vector. Errors are reported against
727   /// \p SM.
728   ///
729   /// Only expected strings whose prefix is one of those listed in \p PrefixRE
730   /// are recorded. \returns true in case of an error, false otherwise.
731   bool ReadCheckFile(SourceMgr &SM, StringRef Buffer, Regex &PrefixRE,
732                      std::vector<FileCheckString> &CheckStrings);
733
734   bool ValidateCheckPrefixes();
735
736   /// Canonicalizes whitespaces in the file. Line endings are replaced with
737   /// UNIX-style '\n'.
738   StringRef CanonicalizeFile(MemoryBuffer &MB,
739                              SmallVectorImpl<char> &OutputBuffer);
740
741   /// Checks the input to FileCheck provided in the \p Buffer against the
742   /// \p CheckStrings read from the check file and record diagnostics emitted
743   /// in \p Diags. Errors are recorded against \p SM.
744   ///
745   /// \returns false if the input fails to satisfy the checks.
746   bool CheckInput(SourceMgr &SM, StringRef Buffer,
747                   ArrayRef<FileCheckString> CheckStrings,
748                   std::vector<FileCheckDiag> *Diags = nullptr);
749 };
750 } // namespace llvm
751 #endif