LLVM  10.0.0svn
FileCheck.h
Go to the documentation of this file.
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/Optional.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Support/Error.h"
21 #include "llvm/Support/Regex.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include <map>
24 #include <string>
25 #include <vector>
26 
27 namespace llvm {
28 
29 /// Contains info about various FileCheck options.
31  std::vector<std::string> CheckPrefixes;
33  std::vector<std::string> ImplicitCheckNot;
34  std::vector<std::string> GlobalDefines;
35  bool AllowEmptyInput = false;
36  bool MatchFullLines = false;
37  bool EnableVarScope = false;
39  bool Verbose = false;
40  bool VerboseVerbose = false;
41 };
42 
43 //===----------------------------------------------------------------------===//
44 // Numeric substitution handling code.
45 //===----------------------------------------------------------------------===//
46 
47 /// Base class representing the AST of a given expression.
49 public:
50  virtual ~FileCheckExpressionAST() = default;
51 
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;
55 };
56 
57 /// Class representing an unsigned literal in the AST of an expression.
59 private:
60  /// Actual value of the literal.
61  uint64_t Value;
62 
63 public:
64  /// Constructs a literal with the specified value.
65  FileCheckExpressionLiteral(uint64_t Val) : Value(Val) {}
66 
67  /// \returns the literal's value.
68  Expected<uint64_t> eval() const { return Value; }
69 };
70 
71 /// Class to represent an undefined variable error, which quotes that
72 /// variable's name when printed.
73 class FileCheckUndefVarError : public ErrorInfo<FileCheckUndefVarError> {
74 private:
76 
77 public:
78  static char ID;
79 
80  FileCheckUndefVarError(StringRef VarName) : VarName(VarName) {}
81 
82  StringRef getVarName() const { return VarName; }
83 
84  std::error_code convertToErrorCode() const override {
85  return inconvertibleErrorCode();
86  }
87 
88  /// Print name of variable associated with this error.
89  void log(raw_ostream &OS) const override {
90  OS << "\"";
91  OS.write_escaped(VarName) << "\"";
92  }
93 };
94 
95 /// Class representing a numeric variable and its associated current value.
97 private:
98  /// Name of the numeric variable.
100 
101  /// Value of numeric variable, if defined, or None otherwise.
103 
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;
108 
109 public:
110  /// Constructor for a variable \p Name defined at line \p DefLineNumber or
111  /// defined before input is parsed if \p DefLineNumber is None.
113  Optional<size_t> DefLineNumber = None)
114  : Name(Name), DefLineNumber(DefLineNumber) {}
115 
116  /// \returns name of this numeric variable.
117  StringRef getName() const { return Name; }
118 
119  /// \returns this variable's value.
120  Optional<uint64_t> getValue() const { return Value; }
121 
122  /// Sets value of this numeric variable to \p NewValue.
123  void setValue(uint64_t NewValue) { Value = NewValue; }
124 
125  /// Clears value of this numeric variable, regardless of whether it is
126  /// currently defined or not.
127  void clearValue() { Value = None; }
128 
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; }
132 };
133 
134 /// Class representing the use of a numeric variable in the AST of an
135 /// expression.
137 private:
138  /// Name of the numeric variable.
139  StringRef Name;
140 
141  /// Pointer to the class instance for the variable this use is about.
142  FileCheckNumericVariable *NumericVariable;
143 
144 public:
146  FileCheckNumericVariable *NumericVariable)
147  : Name(Name), NumericVariable(NumericVariable) {}
148 
149  /// \returns the value of the variable referenced by this instance.
150  Expected<uint64_t> eval() const;
151 };
152 
153 /// Type of functions evaluating a given binary operation.
154 using binop_eval_t = uint64_t (*)(uint64_t, uint64_t);
155 
156 /// Class representing a single binary operation in the AST of an expression.
158 private:
159  /// Left operand.
160  std::unique_ptr<FileCheckExpressionAST> LeftOperand;
161 
162  /// Right operand.
163  std::unique_ptr<FileCheckExpressionAST> RightOperand;
164 
165  /// Pointer to function that can evaluate this binary operation.
166  binop_eval_t EvalBinop;
167 
168 public:
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);
175  }
176 
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;
182 };
183 
185 
186 /// Class representing a substitution to perform in the RegExStr string.
188 protected:
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.
196 
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.
200 
201  // Index in RegExStr of where to do the substitution.
202  size_t InsertIdx;
203 
204 public:
206  size_t InsertIdx)
207  : Context(Context), FromStr(VarName), InsertIdx(InsertIdx) {}
208 
209  virtual ~FileCheckSubstitution() = default;
210 
211  /// \returns the string to be substituted for something else.
212  StringRef getFromString() const { return FromStr; }
213 
214  /// \returns the index where the substitution is to be performed in RegExStr.
215  size_t getIndex() const { return InsertIdx; }
216 
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;
220 };
221 
223 public:
225  StringRef VarName, size_t InsertIdx)
226  : FileCheckSubstitution(Context, VarName, InsertIdx) {}
227 
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;
231 };
232 
234 private:
235  /// Pointer to the class representing the expression whose value is to be
236  /// substituted.
237  std::unique_ptr<FileCheckExpressionAST> ExpressionAST;
238 
239 public:
241  std::unique_ptr<FileCheckExpressionAST> ExprAST,
242  size_t InsertIdx)
243  : FileCheckSubstitution(Context, Expr, InsertIdx) {
244  ExpressionAST = std::move(ExprAST);
245  }
246 
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;
250 };
251 
252 //===----------------------------------------------------------------------===//
253 // Pattern handling code.
254 //===----------------------------------------------------------------------===//
255 
256 namespace Check {
257 
267 
268  /// Indicates the pattern only matches the end of file. This is used for
269  /// trailing CHECK-NOTs.
271 
272  /// Marks when parsing found a -NOT check combined with another CHECK suffix.
274 
275  /// Marks when parsing found a -COUNT directive with invalid count value.
277 };
278 
281  int Count; ///< optional Count for some checks
282 
283 public:
284  FileCheckType(FileCheckKind Kind = CheckNone) : Kind(Kind), Count(1) {}
285  FileCheckType(const FileCheckType &) = default;
286 
287  operator FileCheckKind() const { return Kind; }
288 
289  int getCount() const { return Count; }
290  FileCheckType &setCount(int C);
291 
292  // \returns a description of \p Prefix.
293  std::string getDescription(StringRef Prefix) const;
294 };
295 } // namespace Check
296 
297 struct FileCheckDiag;
298 
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.
303  friend class FileCheckPattern;
304 
305 private:
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;
311 
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;
316 
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
321  /// pattern.
322  StringMap<FileCheckNumericVariable *> GlobalNumericVariableTable;
323 
324  /// Pointer to the class instance representing the @LINE pseudo variable for
325  /// easily updating its value.
326  FileCheckNumericVariable *LineVariable = nullptr;
327 
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;
331 
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;
335 
336 public:
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);
340 
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,
346  SourceMgr &SM);
347 
348  /// Create @LINE pseudo variable. Value is set when pattern are being
349  /// matched.
350  void createLineVariable();
351 
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
355  /// variables.
356  void clearLocalVars();
357 
358 private:
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);
363 
364  /// Makes a new string substitution and registers it for destruction when the
365  /// context is destroyed.
366  FileCheckSubstitution *makeStringSubstitution(StringRef VarName,
367  size_t InsertIdx);
368 
369  /// Makes a new numeric substitution and registers it for destruction when
370  /// the context is destroyed.
372  makeNumericSubstitution(StringRef ExpressionStr,
373  std::unique_ptr<FileCheckExpressionAST> ExpressionAST,
374  size_t InsertIdx);
375 };
376 
377 /// Class to represent an error holding a diagnostic with location information
378 /// used when printing it.
379 class FileCheckErrorDiagnostic : public ErrorInfo<FileCheckErrorDiagnostic> {
380 private:
381  SMDiagnostic Diagnostic;
382 
383 public:
384  static char ID;
385 
386  FileCheckErrorDiagnostic(SMDiagnostic &&Diag) : Diagnostic(Diag) {}
387 
388  std::error_code convertToErrorCode() const override {
389  return inconvertibleErrorCode();
390  }
391 
392  /// Print diagnostic associated with this error when printing the error.
393  void log(raw_ostream &OS) const override { Diagnostic.print(nullptr, OS); }
394 
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));
398  }
399 
400  static Error get(const SourceMgr &SM, StringRef Buffer, const Twine &ErrMsg) {
401  return get(SM, SMLoc::getFromPointer(Buffer.data()), ErrMsg);
402  }
403 };
404 
405 class FileCheckNotFoundError : public ErrorInfo<FileCheckNotFoundError> {
406 public:
407  static char ID;
408 
409  std::error_code convertToErrorCode() const override {
410  return inconvertibleErrorCode();
411  }
412 
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";
416  }
417 };
418 
420  SMLoc PatternLoc;
421 
422  /// A fixed string to match as the pattern or empty if this pattern requires
423  /// a regex match.
424  StringRef FixedStr;
425 
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;
429 
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;
437 
438  /// Maps names of string variables defined in a pattern to the number of
439  /// their parenthesis group in RegExStr capturing their last definition.
440  ///
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".
446  ///
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;
450 
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
457  /// defined.
458  FileCheckNumericVariable *DefinedNumericVariable;
459 
460  /// Number of the parenthesis group in RegExStr that captures the value of
461  /// this numeric variable definition.
462  unsigned CaptureParenGroup;
463  };
464 
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
468  /// variables.
469  StringMap<FileCheckNumericVariableMatch> NumericVariableDefs;
470 
471  /// Pointer to a class instance holding the global state shared by all
472  /// patterns:
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.
478 
479  Check::FileCheckType CheckTy;
480 
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;
485 
486 public:
488  Optional<size_t> Line = None)
489  : Context(Context), CheckTy(Ty), LineNumber(Line) {}
490 
491  /// \returns the location in source code.
492  SMLoc getLoc() const { return PatternLoc; }
493 
494  /// \returns the pointer to the global state for all patterns in this
495  /// FileCheck instance.
497 
498  /// \returns whether \p C is a valid first character for a variable name.
499  static bool isValidVarNameStart(char C);
500 
501  /// Parsing information about a variable.
504  bool IsPseudo;
505  };
506 
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.
525  parseNumericSubstitutionBlock(
526  StringRef Expr,
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.
532  ///
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
540  ///
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
543  /// matched string.
544  ///
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;
559 
560  bool hasVariable() const {
561  return !(Substitutions.empty() && VariableDefs.empty());
562  }
563 
564  Check::FileCheckType getCheckTy() const { return CheckTy; }
565 
566  int getCount() const { return CheckTy.getCount(); }
567 
568 private:
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
573  /// perfect match.
574  unsigned computeMatchDistance(StringRef Buffer) const;
575  /// Finds the closing sequence of a regex variable usage or definition.
576  ///
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
580  /// was not found.
581  size_t FindRegexVarEnd(StringRef Str, SourceMgr &SM);
582 
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.
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
609  /// otherwise.
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.
622  parseBinop(StringRef &Expr, std::unique_ptr<FileCheckExpressionAST> LeftOp,
623  bool IsLegacyLineExpr, Optional<size_t> LineNumber,
624  FileCheckPatternContext *Context, const SourceMgr &SM);
625 };
626 
627 //===----------------------------------------------------------------------===//
628 /// Summary of a FileCheck diagnostic.
629 //===----------------------------------------------------------------------===//
630 
632  /// What is the FileCheck directive for this diagnostic?
634  /// Where is the FileCheck directive for this diagnostic?
635  unsigned CheckLine, CheckCol;
636  /// What type of match result does this diagnostic describe?
637  ///
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.
644  ///
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.
650  enum MatchType {
651  /// Indicates a good match for an expected pattern.
653  /// Indicates a match for an excluded pattern.
655  /// Indicates a match for an expected pattern, but the match is on the
656  /// wrong line.
658  /// Indicates a discarded match for an expected pattern.
660  /// Indicates no match for an excluded pattern.
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.
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.
669  } MatchTy;
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);
678 };
679 
680 //===----------------------------------------------------------------------===//
681 // Check Strings.
682 //===----------------------------------------------------------------------===//
683 
684 /// A check that we found in the input file.
686  /// The pattern to match.
688 
689  /// Which prefix name this check matched.
691 
692  /// The location in the match file that the check string was specified.
694 
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;
698 
700  : Pat(P), Prefix(S), Loc(L) {}
701 
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;
706 
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;
725 };
726 
727 /// FileCheck class takes the request and exposes various methods that
728 /// use information from the request.
729 class FileCheck {
730  FileCheckRequest Req;
731  FileCheckPatternContext PatternContext;
732 
733 public:
734  FileCheck(FileCheckRequest Req) : Req(Req) {}
735 
736  // Combines the check prefixes into a single regex so that we can efficiently
737  // scan for any of the set.
738  //
739  // The semantics are that the longest-match wins which matches our regex
740  // library.
741  Regex buildCheckPrefixRegex();
742 
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
745  /// \p SM.
746  ///
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);
751 
752  bool ValidateCheckPrefixes();
753 
754  /// Canonicalizes whitespaces in the file. Line endings are replaced with
755  /// UNIX-style '\n'.
756  StringRef CanonicalizeFile(MemoryBuffer &MB,
757  SmallVectorImpl<char> &OutputBuffer);
758 
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.
762  ///
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);
767 };
768 } // namespace llvm
769 #endif
static bool Check(DecodeStatus &Out, DecodeStatus In)
uint64_t CallInst * C
Represents a range in source code.
Definition: SMLoc.h:48
Definition: Any.h:26
Indicates a good match for an expected pattern.
Definition: FileCheck.h:652
Indicates no match for an excluded pattern.
Definition: FileCheck.h:661
Parsing information about a variable.
Definition: FileCheck.h:502
LLVMContext & Context
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true) const
Definition: SourceMgr.cpp:368
std::vector< std::string > ImplicitCheckNot
Definition: FileCheck.h:33
Indicates a discarded match for an expected pattern.
Definition: FileCheck.h:659
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Class representing a single binary operation in the AST of an expression.
Definition: FileCheck.h:157
FileCheckPattern(Check::FileCheckType Ty, FileCheckPatternContext *Context, Optional< size_t > Line=None)
Definition: FileCheck.h:487
FileCheckPatternContext * Context
Pointer to a class instance holding, among other things, the table with the values of live string var...
Definition: FileCheck.h:195
Marks when parsing found a -NOT check combined with another CHECK suffix.
Definition: FileCheck.h:273
FileCheckType(FileCheckKind Kind=CheckNone)
Definition: FileCheck.h:284
FileCheckErrorDiagnostic(SMDiagnostic &&Diag)
Definition: FileCheck.h:386
bool AllowDeprecatedDagOverlap
Definition: FileCheck.h:38
Class representing a numeric variable and its associated current value.
Definition: FileCheck.h:96
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode *>> &RecordedNodes)
CheckSame - Implements OP_CheckSame.
StringRef Prefix
Which prefix name this check matched.
Definition: FileCheck.h:690
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:47
FileCheckPattern Pat
The pattern to match.
Definition: FileCheck.h:687
Class holding the FileCheckPattern global state, shared by all patterns: tables holding values of var...
Definition: FileCheck.h:302
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
SMLoc Loc
The location in the match file that the check string was specified.
Definition: FileCheck.h:693
Check::FileCheckType CheckTy
What is the FileCheck directive for this diagnostic?
Definition: FileCheck.h:633
Indicates a match for an expected pattern, but the match is on the wrong line.
Definition: FileCheck.h:657
FileCheckStringSubstitution(FileCheckPatternContext *Context, StringRef VarName, size_t InsertIdx)
Definition: FileCheck.h:224
Class representing a substitution to perform in the RegExStr string.
Definition: FileCheck.h:187
Tagged union holding either a T or a Error.
Definition: yaml2obj.h:21
Marks when parsing found a -COUNT directive with invalid count value.
Definition: FileCheck.h:276
void setValue(uint64_t NewValue)
Sets value of this numeric variable to NewValue.
Definition: FileCheck.h:123
std::vector< std::string > CheckPrefixes
Definition: FileCheck.h:31
Class to represent an error holding a diagnostic with location information used when printing it...
Definition: FileCheck.h:379
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: FileCheck.h:409
Base class representing the AST of a given expression.
Definition: FileCheck.h:48
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
Contains info about various FileCheck options.
Definition: FileCheck.h:30
FileCheck(FileCheckRequest Req)
Definition: FileCheck.h:734
std::vector< std::string > GlobalDefines
Definition: FileCheck.h:34
static std::string getDescription(const CallGraphSCC &SCC)
FileCheckExpressionLiteral(uint64_t Val)
Constructs a literal with the specified value.
Definition: FileCheck.h:65
unsigned InputEndLine
Definition: FileCheck.h:674
FileCheckSubstitution(FileCheckPatternContext *Context, StringRef VarName, size_t InsertIdx)
Definition: FileCheck.h:205
#define P(N)
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: FileCheck.h:388
A check that we found in the input file.
Definition: FileCheck.h:685
std::vector< FileCheckPattern > DagNotStrings
All of the strings that are disallowed from occurring between this match string and the previous one ...
Definition: FileCheck.h:697
StringRef getFromString() const
Definition: FileCheck.h:212
FileCheckUndefVarError(StringRef VarName)
Definition: FileCheck.h:80
Class representing an unsigned literal in the AST of an expression.
Definition: FileCheck.h:58
Optional< size_t > getDefLineNumber()
Definition: FileCheck.h:131
unsigned CheckLine
Where is the FileCheck directive for this diagnostic?
Definition: FileCheck.h:635
StringRef FromStr
The string that needs to be substituted for something else.
Definition: FileCheck.h:199
void log(raw_ostream &OS) const override
Print name of variable associated with this error.
Definition: FileCheck.h:89
SMLoc getLoc() const
Definition: FileCheck.h:492
size_t getIndex() const
Definition: FileCheck.h:215
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
Definition: SourceMgr.h:41
Optional< uint64_t > getValue() const
Definition: FileCheck.h:120
Check::FileCheckType getCheckTy() const
Definition: FileCheck.h:564
Class to represent an undefined variable error, which quotes that variable&#39;s name when printed...
Definition: FileCheck.h:73
bool hasVariable() const
Definition: FileCheck.h:560
StringRef getName() const
Definition: FileCheck.h:117
FileCheckNumericVariableUse(StringRef Name, FileCheckNumericVariable *NumericVariable)
Definition: FileCheck.h:145
Indicates the pattern only matches the end of file.
Definition: FileCheck.h:270
Expected< uint64_t > eval() const
Definition: FileCheck.h:68
raw_ostream & write_escaped(StringRef Str, bool UseHexEscapes=false)
Output Str, turning &#39;\&#39;, &#39;&#39;, &#39; &#39;, &#39;"&#39;, and anything that doesn&#39;t satisfy llvm::isPrint into an escape...
Indicates a fuzzy match that serves as a suggestion for the next intended match for an expected patte...
Definition: FileCheck.h:668
void log(raw_ostream &OS) const override
Print diagnostic associated with this error when printing the error.
Definition: FileCheck.h:393
Indicates no match for an expected pattern, but this might follow good matches when multiple matches ...
Definition: FileCheck.h:665
FileCheckNumericSubstitution(FileCheckPatternContext *Context, StringRef Expr, std::unique_ptr< FileCheckExpressionAST > ExprAST, size_t InsertIdx)
Definition: FileCheck.h:240
unsigned InputEndCol
Definition: FileCheck.h:675
uint64_t(*)(uint64_t, uint64_t) binop_eval_t
Type of functions evaluating a given binary operation.
Definition: FileCheck.h:154
FileCheckPatternContext * getContext() const
Definition: FileCheck.h:496
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:41
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:219
FileCheckNumericVariable(StringRef Name, Optional< size_t > DefLineNumber=None)
Constructor for a variable Name defined at line DefLineNumber or defined before input is parsed if De...
Definition: FileCheck.h:112
Base class for user error types.
Definition: Error.h:344
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
unsigned InputStartLine
The search range if MatchTy is MatchNoneAndExcluded or MatchNoneButExpected, or the match range other...
Definition: FileCheck.h:672
Indicates a match for an excluded pattern.
Definition: FileCheck.h:654
FileCheckASTBinop(binop_eval_t EvalBinop, std::unique_ptr< FileCheckExpressionAST > LeftOp, std::unique_ptr< FileCheckExpressionAST > RightOp)
Definition: FileCheck.h:169
Summary of a FileCheck diagnostic.
Definition: FileCheck.h:631
unsigned InputStartCol
Definition: FileCheck.h:673
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
MatchType
What type of match result does this diagnostic describe?
Definition: FileCheck.h:650
int getCount() const
Definition: FileCheck.h:566
Represents a location in source code.
Definition: SMLoc.h:23
void log(raw_ostream &OS) const override
Print diagnostic associated with this error when printing the error.
Definition: FileCheck.h:414
FileCheck class takes the request and exposes various methods that use information from the request...
Definition: FileCheck.h:729
StringRef getVarName() const
Definition: FileCheck.h:82
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: FileCheck.h:84
Class representing the use of a numeric variable in the AST of an expression.
Definition: FileCheck.h:136
FileCheckString(const FileCheckPattern &P, StringRef S, SMLoc L)
Definition: FileCheck.h:699
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77
void clearValue()
Clears value of this numeric variable, regardless of whether it is currently defined or not...
Definition: FileCheck.h:127
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:261