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