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