1ee3c74fbSChris Lattner //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2ee3c74fbSChris Lattner //
3ee3c74fbSChris Lattner //                     The LLVM Compiler Infrastructure
4ee3c74fbSChris Lattner //
5ee3c74fbSChris Lattner // This file is distributed under the University of Illinois Open Source
6ee3c74fbSChris Lattner // License. See LICENSE.TXT for details.
7ee3c74fbSChris Lattner //
8ee3c74fbSChris Lattner //===----------------------------------------------------------------------===//
9ee3c74fbSChris Lattner //
10ee3c74fbSChris Lattner // FileCheck does a line-by line check of a file that validates whether it
11ee3c74fbSChris Lattner // contains the expected content.  This is useful for regression tests etc.
12ee3c74fbSChris Lattner //
13ee3c74fbSChris Lattner // This program exits with an error status of 2 on error, exit status of 0 if
14ee3c74fbSChris Lattner // the file matched the expected contents, and exit status of 1 if it did not
15ee3c74fbSChris Lattner // contain the expected contents.
16ee3c74fbSChris Lattner //
17ee3c74fbSChris Lattner //===----------------------------------------------------------------------===//
18ee3c74fbSChris Lattner 
1939a0ffc3SMichael J. Spencer #include "llvm/ADT/OwningPtr.h"
2091d19d8eSChandler Carruth #include "llvm/ADT/SmallString.h"
2191d19d8eSChandler Carruth #include "llvm/ADT/StringExtras.h"
2291d19d8eSChandler Carruth #include "llvm/ADT/StringMap.h"
23ee3c74fbSChris Lattner #include "llvm/Support/CommandLine.h"
24ee3c74fbSChris Lattner #include "llvm/Support/MemoryBuffer.h"
25ee3c74fbSChris Lattner #include "llvm/Support/PrettyStackTrace.h"
26f08d2db9SChris Lattner #include "llvm/Support/Regex.h"
2791d19d8eSChandler Carruth #include "llvm/Support/Signals.h"
28ee3c74fbSChris Lattner #include "llvm/Support/SourceMgr.h"
29ee3c74fbSChris Lattner #include "llvm/Support/raw_ostream.h"
307b6fef82SMichael J. Spencer #include "llvm/Support/system_error.h"
318879e06dSChris Lattner #include <algorithm>
32*981af002SWill Dietz #include <cctype>
33e8b8f1bcSEli Bendersky #include <map>
34e8b8f1bcSEli Bendersky #include <string>
35e8b8f1bcSEli Bendersky #include <vector>
36ee3c74fbSChris Lattner using namespace llvm;
37ee3c74fbSChris Lattner 
38ee3c74fbSChris Lattner static cl::opt<std::string>
39ee3c74fbSChris Lattner CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
40ee3c74fbSChris Lattner 
41ee3c74fbSChris Lattner static cl::opt<std::string>
42ee3c74fbSChris Lattner InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
43ee3c74fbSChris Lattner               cl::init("-"), cl::value_desc("filename"));
44ee3c74fbSChris Lattner 
45ee3c74fbSChris Lattner static cl::opt<std::string>
46ee3c74fbSChris Lattner CheckPrefix("check-prefix", cl::init("CHECK"),
47ee3c74fbSChris Lattner             cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
48ee3c74fbSChris Lattner 
492c3e5cdfSChris Lattner static cl::opt<bool>
502c3e5cdfSChris Lattner NoCanonicalizeWhiteSpace("strict-whitespace",
512c3e5cdfSChris Lattner               cl::desc("Do not treat all horizontal whitespace as equivalent"));
522c3e5cdfSChris Lattner 
5374d50731SChris Lattner //===----------------------------------------------------------------------===//
5474d50731SChris Lattner // Pattern Handling Code.
5574d50731SChris Lattner //===----------------------------------------------------------------------===//
5674d50731SChris Lattner 
5738820972SMatt Arsenault namespace Check {
5838820972SMatt Arsenault   enum CheckType {
5938820972SMatt Arsenault     CheckNone = 0,
6038820972SMatt Arsenault     CheckPlain,
6138820972SMatt Arsenault     CheckNext,
6238820972SMatt Arsenault     CheckNot,
6338820972SMatt Arsenault     CheckDAG,
6438820972SMatt Arsenault     CheckLabel,
650a4c44bdSChris Lattner 
66eba55822SJakob Stoklund Olesen     /// MatchEOF - When set, this pattern only matches the end of file. This is
67eba55822SJakob Stoklund Olesen     /// used for trailing CHECK-NOTs.
6838820972SMatt Arsenault     CheckEOF
6938820972SMatt Arsenault   };
7038820972SMatt Arsenault }
71eba55822SJakob Stoklund Olesen 
7238820972SMatt Arsenault class Pattern {
7338820972SMatt Arsenault   SMLoc PatternLoc;
7491a1b2c9SMichael Liao 
7538820972SMatt Arsenault   Check::CheckType CheckTy;
7691a1b2c9SMichael Liao 
77b16ab0c4SChris Lattner   /// FixedStr - If non-empty, this pattern is a fixed string match with the
78b16ab0c4SChris Lattner   /// specified fixed string.
79221460e0SChris Lattner   StringRef FixedStr;
80b16ab0c4SChris Lattner 
81b16ab0c4SChris Lattner   /// RegEx - If non-empty, this is a regex pattern.
82b16ab0c4SChris Lattner   std::string RegExStr;
838879e06dSChris Lattner 
8492987fb3SAlexander Kornienko   /// \brief Contains the number of line this pattern is in.
8592987fb3SAlexander Kornienko   unsigned LineNumber;
8692987fb3SAlexander Kornienko 
878879e06dSChris Lattner   /// VariableUses - Entries in this vector map to uses of a variable in the
888879e06dSChris Lattner   /// pattern, e.g. "foo[[bar]]baz".  In this case, the RegExStr will contain
898879e06dSChris Lattner   /// "foobaz" and we'll get an entry in this vector that tells us to insert the
908879e06dSChris Lattner   /// value of bar at offset 3.
918879e06dSChris Lattner   std::vector<std::pair<StringRef, unsigned> > VariableUses;
928879e06dSChris Lattner 
93e8b8f1bcSEli Bendersky   /// VariableDefs - Maps definitions of variables to their parenthesized
94e8b8f1bcSEli Bendersky   /// capture numbers.
95e8b8f1bcSEli Bendersky   /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
96e8b8f1bcSEli Bendersky   std::map<StringRef, unsigned> VariableDefs;
978879e06dSChris Lattner 
983b40b445SChris Lattner public:
993b40b445SChris Lattner 
10038820972SMatt Arsenault   Pattern(Check::CheckType Ty)
10138820972SMatt Arsenault     : CheckTy(Ty) { }
10274d50731SChris Lattner 
1030b707eb8SMichael Liao   /// getLoc - Return the location in source code.
1040b707eb8SMichael Liao   SMLoc getLoc() const { return PatternLoc; }
1050b707eb8SMichael Liao 
10643d50d4aSEli Bendersky   /// ParsePattern - Parse the given string into the Pattern.  SM provides the
10743d50d4aSEli Bendersky   /// SourceMgr used for error reports, and LineNumber is the line number in
10843d50d4aSEli Bendersky   /// the input file from which the pattern string was read.
10943d50d4aSEli Bendersky   /// Returns true in case of an error, false otherwise.
11092987fb3SAlexander Kornienko   bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
1113b40b445SChris Lattner 
1123b40b445SChris Lattner   /// Match - Match the pattern string against the input buffer Buffer.  This
1133b40b445SChris Lattner   /// returns the position that is matched or npos if there is no match.  If
1143b40b445SChris Lattner   /// there is a match, the size of the matched string is returned in MatchLen.
1158879e06dSChris Lattner   ///
1168879e06dSChris Lattner   /// The VariableTable StringMap provides the current values of filecheck
1178879e06dSChris Lattner   /// variables and is updated if this match defines new values.
1188879e06dSChris Lattner   size_t Match(StringRef Buffer, size_t &MatchLen,
1198879e06dSChris Lattner                StringMap<StringRef> &VariableTable) const;
120b16ab0c4SChris Lattner 
121e0ef65abSDaniel Dunbar   /// PrintFailureInfo - Print additional information about a failure to match
122e0ef65abSDaniel Dunbar   /// involving this pattern.
123e0ef65abSDaniel Dunbar   void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
124e0ef65abSDaniel Dunbar                         const StringMap<StringRef> &VariableTable) const;
125e0ef65abSDaniel Dunbar 
126f8bd2e5bSStephen Lin   bool hasVariable() const { return !(VariableUses.empty() &&
127f8bd2e5bSStephen Lin                                       VariableDefs.empty()); }
128f8bd2e5bSStephen Lin 
12938820972SMatt Arsenault   Check::CheckType getCheckTy() const { return CheckTy; }
13091a1b2c9SMichael Liao 
131b16ab0c4SChris Lattner private:
1328879e06dSChris Lattner   static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
133e8b8f1bcSEli Bendersky   bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
134e8b8f1bcSEli Bendersky   void AddBackrefToRegEx(unsigned BackrefNum);
135fd29d886SDaniel Dunbar 
136fd29d886SDaniel Dunbar   /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
137fd29d886SDaniel Dunbar   /// matching this pattern at the start of \arg Buffer; a distance of zero
138fd29d886SDaniel Dunbar   /// should correspond to a perfect match.
139fd29d886SDaniel Dunbar   unsigned ComputeMatchDistance(StringRef Buffer,
140fd29d886SDaniel Dunbar                                const StringMap<StringRef> &VariableTable) const;
14192987fb3SAlexander Kornienko 
14292987fb3SAlexander Kornienko   /// \brief Evaluates expression and stores the result to \p Value.
14392987fb3SAlexander Kornienko   /// \return true on success. false when the expression has invalid syntax.
14492987fb3SAlexander Kornienko   bool EvaluateExpression(StringRef Expr, std::string &Value) const;
145061d2baaSEli Bendersky 
146061d2baaSEli Bendersky   /// \brief Finds the closing sequence of a regex variable usage or
147061d2baaSEli Bendersky   /// definition. Str has to point in the beginning of the definition
148061d2baaSEli Bendersky   /// (right after the opening sequence).
149061d2baaSEli Bendersky   /// \return offset of the closing sequence within Str, or npos if it was not
150061d2baaSEli Bendersky   /// found.
151061d2baaSEli Bendersky   size_t FindRegexVarEnd(StringRef Str);
1523b40b445SChris Lattner };
1533b40b445SChris Lattner 
1548879e06dSChris Lattner 
15592987fb3SAlexander Kornienko bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
15692987fb3SAlexander Kornienko                            unsigned LineNumber) {
15792987fb3SAlexander Kornienko   this->LineNumber = LineNumber;
1580a4c44bdSChris Lattner   PatternLoc = SMLoc::getFromPointer(PatternStr.data());
1590a4c44bdSChris Lattner 
16074d50731SChris Lattner   // Ignore trailing whitespace.
16174d50731SChris Lattner   while (!PatternStr.empty() &&
16274d50731SChris Lattner          (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
16374d50731SChris Lattner     PatternStr = PatternStr.substr(0, PatternStr.size()-1);
16474d50731SChris Lattner 
16574d50731SChris Lattner   // Check that there is something on the line.
16674d50731SChris Lattner   if (PatternStr.empty()) {
16703b80a40SChris Lattner     SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
16803b80a40SChris Lattner                     "found empty check string with prefix '" +
16903b80a40SChris Lattner                     CheckPrefix+":'");
17074d50731SChris Lattner     return true;
17174d50731SChris Lattner   }
17274d50731SChris Lattner 
173221460e0SChris Lattner   // Check to see if this is a fixed string, or if it has regex pieces.
174d9466967STed Kremenek   if (PatternStr.size() < 2 ||
1758879e06dSChris Lattner       (PatternStr.find("{{") == StringRef::npos &&
1768879e06dSChris Lattner        PatternStr.find("[[") == StringRef::npos)) {
177221460e0SChris Lattner     FixedStr = PatternStr;
178221460e0SChris Lattner     return false;
179221460e0SChris Lattner   }
180221460e0SChris Lattner 
1818879e06dSChris Lattner   // Paren value #0 is for the fully matched string.  Any new parenthesized
18253e0679dSChris Lattner   // values add from there.
1838879e06dSChris Lattner   unsigned CurParen = 1;
1848879e06dSChris Lattner 
185b16ab0c4SChris Lattner   // Otherwise, there is at least one regex piece.  Build up the regex pattern
186b16ab0c4SChris Lattner   // by escaping scary characters in fixed strings, building up one big regex.
187f08d2db9SChris Lattner   while (!PatternStr.empty()) {
1888879e06dSChris Lattner     // RegEx matches.
18953e0679dSChris Lattner     if (PatternStr.startswith("{{")) {
19043d50d4aSEli Bendersky       // This is the start of a regex match.  Scan for the }}.
191f08d2db9SChris Lattner       size_t End = PatternStr.find("}}");
192f08d2db9SChris Lattner       if (End == StringRef::npos) {
193f08d2db9SChris Lattner         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
19403b80a40SChris Lattner                         SourceMgr::DK_Error,
19503b80a40SChris Lattner                         "found start of regex string with no end '}}'");
196f08d2db9SChris Lattner         return true;
197f08d2db9SChris Lattner       }
198f08d2db9SChris Lattner 
199e53c95f1SChris Lattner       // Enclose {{}} patterns in parens just like [[]] even though we're not
200e53c95f1SChris Lattner       // capturing the result for any purpose.  This is required in case the
201e53c95f1SChris Lattner       // expression contains an alternation like: CHECK:  abc{{x|z}}def.  We
202e53c95f1SChris Lattner       // want this to turn into: "abc(x|z)def" not "abcx|zdef".
203e53c95f1SChris Lattner       RegExStr += '(';
204e53c95f1SChris Lattner       ++CurParen;
205e53c95f1SChris Lattner 
2068879e06dSChris Lattner       if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
2078879e06dSChris Lattner         return true;
208e53c95f1SChris Lattner       RegExStr += ')';
20953e0679dSChris Lattner 
2108879e06dSChris Lattner       PatternStr = PatternStr.substr(End+2);
2118879e06dSChris Lattner       continue;
2128879e06dSChris Lattner     }
2138879e06dSChris Lattner 
2148879e06dSChris Lattner     // Named RegEx matches.  These are of two forms: [[foo:.*]] which matches .*
2158879e06dSChris Lattner     // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
2168879e06dSChris Lattner     // second form is [[foo]] which is a reference to foo.  The variable name
21757cb733bSDaniel Dunbar     // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
2188879e06dSChris Lattner     // it.  This is to catch some common errors.
21953e0679dSChris Lattner     if (PatternStr.startswith("[[")) {
220061d2baaSEli Bendersky       // Find the closing bracket pair ending the match.  End is going to be an
221061d2baaSEli Bendersky       // offset relative to the beginning of the match string.
222061d2baaSEli Bendersky       size_t End = FindRegexVarEnd(PatternStr.substr(2));
223061d2baaSEli Bendersky 
2248879e06dSChris Lattner       if (End == StringRef::npos) {
2258879e06dSChris Lattner         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
22603b80a40SChris Lattner                         SourceMgr::DK_Error,
22703b80a40SChris Lattner                         "invalid named regex reference, no ]] found");
228f08d2db9SChris Lattner         return true;
229f08d2db9SChris Lattner       }
230f08d2db9SChris Lattner 
231061d2baaSEli Bendersky       StringRef MatchStr = PatternStr.substr(2, End);
232061d2baaSEli Bendersky       PatternStr = PatternStr.substr(End+4);
2338879e06dSChris Lattner 
2348879e06dSChris Lattner       // Get the regex name (e.g. "foo").
2358879e06dSChris Lattner       size_t NameEnd = MatchStr.find(':');
2368879e06dSChris Lattner       StringRef Name = MatchStr.substr(0, NameEnd);
2378879e06dSChris Lattner 
2388879e06dSChris Lattner       if (Name.empty()) {
23903b80a40SChris Lattner         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
24003b80a40SChris Lattner                         "invalid name in named regex: empty name");
2418879e06dSChris Lattner         return true;
2428879e06dSChris Lattner       }
2438879e06dSChris Lattner 
24492987fb3SAlexander Kornienko       // Verify that the name/expression is well formed. FileCheck currently
24592987fb3SAlexander Kornienko       // supports @LINE, @LINE+number, @LINE-number expressions. The check here
24692987fb3SAlexander Kornienko       // is relaxed, more strict check is performed in \c EvaluateExpression.
24792987fb3SAlexander Kornienko       bool IsExpression = false;
24892987fb3SAlexander Kornienko       for (unsigned i = 0, e = Name.size(); i != e; ++i) {
24992987fb3SAlexander Kornienko         if (i == 0 && Name[i] == '@') {
25092987fb3SAlexander Kornienko           if (NameEnd != StringRef::npos) {
25192987fb3SAlexander Kornienko             SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
25292987fb3SAlexander Kornienko                             SourceMgr::DK_Error,
25392987fb3SAlexander Kornienko                             "invalid name in named regex definition");
25492987fb3SAlexander Kornienko             return true;
25592987fb3SAlexander Kornienko           }
25692987fb3SAlexander Kornienko           IsExpression = true;
25792987fb3SAlexander Kornienko           continue;
25892987fb3SAlexander Kornienko         }
25992987fb3SAlexander Kornienko         if (Name[i] != '_' && !isalnum(Name[i]) &&
26092987fb3SAlexander Kornienko             (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
2618879e06dSChris Lattner           SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
26203b80a40SChris Lattner                           SourceMgr::DK_Error, "invalid name in named regex");
2638879e06dSChris Lattner           return true;
2648879e06dSChris Lattner         }
26592987fb3SAlexander Kornienko       }
2668879e06dSChris Lattner 
2678879e06dSChris Lattner       // Name can't start with a digit.
26883c74e9fSGuy Benyei       if (isdigit(static_cast<unsigned char>(Name[0]))) {
26903b80a40SChris Lattner         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
27003b80a40SChris Lattner                         "invalid name in named regex");
2718879e06dSChris Lattner         return true;
2728879e06dSChris Lattner       }
2738879e06dSChris Lattner 
2748879e06dSChris Lattner       // Handle [[foo]].
2758879e06dSChris Lattner       if (NameEnd == StringRef::npos) {
276e8b8f1bcSEli Bendersky         // Handle variables that were defined earlier on the same line by
277e8b8f1bcSEli Bendersky         // emitting a backreference.
278e8b8f1bcSEli Bendersky         if (VariableDefs.find(Name) != VariableDefs.end()) {
279e8b8f1bcSEli Bendersky           unsigned VarParenNum = VariableDefs[Name];
280e8b8f1bcSEli Bendersky           if (VarParenNum < 1 || VarParenNum > 9) {
281e8b8f1bcSEli Bendersky             SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
282e8b8f1bcSEli Bendersky                             SourceMgr::DK_Error,
283e8b8f1bcSEli Bendersky                             "Can't back-reference more than 9 variables");
284e8b8f1bcSEli Bendersky             return true;
285e8b8f1bcSEli Bendersky           }
286e8b8f1bcSEli Bendersky           AddBackrefToRegEx(VarParenNum);
287e8b8f1bcSEli Bendersky         } else {
2888879e06dSChris Lattner           VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
289e8b8f1bcSEli Bendersky         }
2908879e06dSChris Lattner         continue;
2918879e06dSChris Lattner       }
2928879e06dSChris Lattner 
2938879e06dSChris Lattner       // Handle [[foo:.*]].
294e8b8f1bcSEli Bendersky       VariableDefs[Name] = CurParen;
2958879e06dSChris Lattner       RegExStr += '(';
2968879e06dSChris Lattner       ++CurParen;
2978879e06dSChris Lattner 
2988879e06dSChris Lattner       if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
2998879e06dSChris Lattner         return true;
3008879e06dSChris Lattner 
3018879e06dSChris Lattner       RegExStr += ')';
3028879e06dSChris Lattner     }
3038879e06dSChris Lattner 
3048879e06dSChris Lattner     // Handle fixed string matches.
3058879e06dSChris Lattner     // Find the end, which is the start of the next regex.
3068879e06dSChris Lattner     size_t FixedMatchEnd = PatternStr.find("{{");
3078879e06dSChris Lattner     FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
3088879e06dSChris Lattner     AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
3098879e06dSChris Lattner     PatternStr = PatternStr.substr(FixedMatchEnd);
310f08d2db9SChris Lattner   }
311f08d2db9SChris Lattner 
31274d50731SChris Lattner   return false;
31374d50731SChris Lattner }
31474d50731SChris Lattner 
3158879e06dSChris Lattner void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
316b16ab0c4SChris Lattner   // Add the characters from FixedStr to the regex, escaping as needed.  This
317b16ab0c4SChris Lattner   // avoids "leaning toothpicks" in common patterns.
318b16ab0c4SChris Lattner   for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
319b16ab0c4SChris Lattner     switch (FixedStr[i]) {
320b16ab0c4SChris Lattner     // These are the special characters matched in "p_ere_exp".
321b16ab0c4SChris Lattner     case '(':
322b16ab0c4SChris Lattner     case ')':
323b16ab0c4SChris Lattner     case '^':
324b16ab0c4SChris Lattner     case '$':
325b16ab0c4SChris Lattner     case '|':
326b16ab0c4SChris Lattner     case '*':
327b16ab0c4SChris Lattner     case '+':
328b16ab0c4SChris Lattner     case '?':
329b16ab0c4SChris Lattner     case '.':
330b16ab0c4SChris Lattner     case '[':
331b16ab0c4SChris Lattner     case '\\':
332b16ab0c4SChris Lattner     case '{':
3338879e06dSChris Lattner       TheStr += '\\';
334b16ab0c4SChris Lattner       // FALL THROUGH.
335b16ab0c4SChris Lattner     default:
3368879e06dSChris Lattner       TheStr += FixedStr[i];
337b16ab0c4SChris Lattner       break;
338b16ab0c4SChris Lattner     }
339b16ab0c4SChris Lattner   }
340b16ab0c4SChris Lattner }
341b16ab0c4SChris Lattner 
342e8b8f1bcSEli Bendersky bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
3438879e06dSChris Lattner                               SourceMgr &SM) {
344e8b8f1bcSEli Bendersky   Regex R(RS);
3458879e06dSChris Lattner   std::string Error;
3468879e06dSChris Lattner   if (!R.isValid(Error)) {
347e8b8f1bcSEli Bendersky     SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
34803b80a40SChris Lattner                     "invalid regex: " + Error);
3498879e06dSChris Lattner     return true;
3508879e06dSChris Lattner   }
3518879e06dSChris Lattner 
352e8b8f1bcSEli Bendersky   RegExStr += RS.str();
3538879e06dSChris Lattner   CurParen += R.getNumMatches();
3548879e06dSChris Lattner   return false;
3558879e06dSChris Lattner }
356b16ab0c4SChris Lattner 
357e8b8f1bcSEli Bendersky void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
358e8b8f1bcSEli Bendersky   assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
359e8b8f1bcSEli Bendersky   std::string Backref = std::string("\\") +
360e8b8f1bcSEli Bendersky                         std::string(1, '0' + BackrefNum);
361e8b8f1bcSEli Bendersky   RegExStr += Backref;
362e8b8f1bcSEli Bendersky }
363e8b8f1bcSEli Bendersky 
36492987fb3SAlexander Kornienko bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
36592987fb3SAlexander Kornienko   // The only supported expression is @LINE([\+-]\d+)?
36692987fb3SAlexander Kornienko   if (!Expr.startswith("@LINE"))
36792987fb3SAlexander Kornienko     return false;
36892987fb3SAlexander Kornienko   Expr = Expr.substr(StringRef("@LINE").size());
36992987fb3SAlexander Kornienko   int Offset = 0;
37092987fb3SAlexander Kornienko   if (!Expr.empty()) {
37192987fb3SAlexander Kornienko     if (Expr[0] == '+')
37292987fb3SAlexander Kornienko       Expr = Expr.substr(1);
37392987fb3SAlexander Kornienko     else if (Expr[0] != '-')
37492987fb3SAlexander Kornienko       return false;
37592987fb3SAlexander Kornienko     if (Expr.getAsInteger(10, Offset))
37692987fb3SAlexander Kornienko       return false;
37792987fb3SAlexander Kornienko   }
37892987fb3SAlexander Kornienko   Value = llvm::itostr(LineNumber + Offset);
37992987fb3SAlexander Kornienko   return true;
38092987fb3SAlexander Kornienko }
38192987fb3SAlexander Kornienko 
382f08d2db9SChris Lattner /// Match - Match the pattern string against the input buffer Buffer.  This
383f08d2db9SChris Lattner /// returns the position that is matched or npos if there is no match.  If
384f08d2db9SChris Lattner /// there is a match, the size of the matched string is returned in MatchLen.
3858879e06dSChris Lattner size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
3868879e06dSChris Lattner                       StringMap<StringRef> &VariableTable) const {
387eba55822SJakob Stoklund Olesen   // If this is the EOF pattern, match it immediately.
38838820972SMatt Arsenault   if (CheckTy == Check::CheckEOF) {
389eba55822SJakob Stoklund Olesen     MatchLen = 0;
390eba55822SJakob Stoklund Olesen     return Buffer.size();
391eba55822SJakob Stoklund Olesen   }
392eba55822SJakob Stoklund Olesen 
393221460e0SChris Lattner   // If this is a fixed string pattern, just match it now.
394221460e0SChris Lattner   if (!FixedStr.empty()) {
395221460e0SChris Lattner     MatchLen = FixedStr.size();
396221460e0SChris Lattner     return Buffer.find(FixedStr);
397221460e0SChris Lattner   }
398221460e0SChris Lattner 
399b16ab0c4SChris Lattner   // Regex match.
4008879e06dSChris Lattner 
4018879e06dSChris Lattner   // If there are variable uses, we need to create a temporary string with the
4028879e06dSChris Lattner   // actual value.
4038879e06dSChris Lattner   StringRef RegExToMatch = RegExStr;
4048879e06dSChris Lattner   std::string TmpStr;
4058879e06dSChris Lattner   if (!VariableUses.empty()) {
4068879e06dSChris Lattner     TmpStr = RegExStr;
4078879e06dSChris Lattner 
4088879e06dSChris Lattner     unsigned InsertOffset = 0;
4098879e06dSChris Lattner     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
41092987fb3SAlexander Kornienko       std::string Value;
41192987fb3SAlexander Kornienko 
41292987fb3SAlexander Kornienko       if (VariableUses[i].first[0] == '@') {
41392987fb3SAlexander Kornienko         if (!EvaluateExpression(VariableUses[i].first, Value))
41492987fb3SAlexander Kornienko           return StringRef::npos;
41592987fb3SAlexander Kornienko       } else {
416e0ef65abSDaniel Dunbar         StringMap<StringRef>::iterator it =
417e0ef65abSDaniel Dunbar           VariableTable.find(VariableUses[i].first);
418e0ef65abSDaniel Dunbar         // If the variable is undefined, return an error.
419e0ef65abSDaniel Dunbar         if (it == VariableTable.end())
420e0ef65abSDaniel Dunbar           return StringRef::npos;
421e0ef65abSDaniel Dunbar 
4228879e06dSChris Lattner         // Look up the value and escape it so that we can plop it into the regex.
423e0ef65abSDaniel Dunbar         AddFixedStringToRegEx(it->second, Value);
42492987fb3SAlexander Kornienko       }
4258879e06dSChris Lattner 
4268879e06dSChris Lattner       // Plop it into the regex at the adjusted offset.
4278879e06dSChris Lattner       TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
4288879e06dSChris Lattner                     Value.begin(), Value.end());
4298879e06dSChris Lattner       InsertOffset += Value.size();
4308879e06dSChris Lattner     }
4318879e06dSChris Lattner 
4328879e06dSChris Lattner     // Match the newly constructed regex.
4338879e06dSChris Lattner     RegExToMatch = TmpStr;
4348879e06dSChris Lattner   }
4358879e06dSChris Lattner 
4368879e06dSChris Lattner 
437b16ab0c4SChris Lattner   SmallVector<StringRef, 4> MatchInfo;
4388879e06dSChris Lattner   if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
439f08d2db9SChris Lattner     return StringRef::npos;
440b16ab0c4SChris Lattner 
441b16ab0c4SChris Lattner   // Successful regex match.
442b16ab0c4SChris Lattner   assert(!MatchInfo.empty() && "Didn't get any match");
443b16ab0c4SChris Lattner   StringRef FullMatch = MatchInfo[0];
444b16ab0c4SChris Lattner 
4458879e06dSChris Lattner   // If this defines any variables, remember their values.
446e8b8f1bcSEli Bendersky   for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
447e8b8f1bcSEli Bendersky                                                      E = VariableDefs.end();
448e8b8f1bcSEli Bendersky        I != E; ++I) {
449e8b8f1bcSEli Bendersky     assert(I->second < MatchInfo.size() && "Internal paren error");
450e8b8f1bcSEli Bendersky     VariableTable[I->first] = MatchInfo[I->second];
4510a4c44bdSChris Lattner   }
4520a4c44bdSChris Lattner 
453b16ab0c4SChris Lattner   MatchLen = FullMatch.size();
454b16ab0c4SChris Lattner   return FullMatch.data()-Buffer.data();
455f08d2db9SChris Lattner }
456f08d2db9SChris Lattner 
457fd29d886SDaniel Dunbar unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
458fd29d886SDaniel Dunbar                               const StringMap<StringRef> &VariableTable) const {
459fd29d886SDaniel Dunbar   // Just compute the number of matching characters. For regular expressions, we
460fd29d886SDaniel Dunbar   // just compare against the regex itself and hope for the best.
461fd29d886SDaniel Dunbar   //
462fd29d886SDaniel Dunbar   // FIXME: One easy improvement here is have the regex lib generate a single
463fd29d886SDaniel Dunbar   // example regular expression which matches, and use that as the example
464fd29d886SDaniel Dunbar   // string.
465fd29d886SDaniel Dunbar   StringRef ExampleString(FixedStr);
466fd29d886SDaniel Dunbar   if (ExampleString.empty())
467fd29d886SDaniel Dunbar     ExampleString = RegExStr;
468fd29d886SDaniel Dunbar 
469e9aa36c8SDaniel Dunbar   // Only compare up to the first line in the buffer, or the string size.
470e9aa36c8SDaniel Dunbar   StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
471e9aa36c8SDaniel Dunbar   BufferPrefix = BufferPrefix.split('\n').first;
472e9aa36c8SDaniel Dunbar   return BufferPrefix.edit_distance(ExampleString);
473fd29d886SDaniel Dunbar }
474fd29d886SDaniel Dunbar 
475e0ef65abSDaniel Dunbar void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
476e0ef65abSDaniel Dunbar                                const StringMap<StringRef> &VariableTable) const{
477e0ef65abSDaniel Dunbar   // If this was a regular expression using variables, print the current
478e0ef65abSDaniel Dunbar   // variable values.
479e0ef65abSDaniel Dunbar   if (!VariableUses.empty()) {
480e0ef65abSDaniel Dunbar     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
481e0ef65abSDaniel Dunbar       SmallString<256> Msg;
482e0ef65abSDaniel Dunbar       raw_svector_ostream OS(Msg);
48392987fb3SAlexander Kornienko       StringRef Var = VariableUses[i].first;
48492987fb3SAlexander Kornienko       if (Var[0] == '@') {
48592987fb3SAlexander Kornienko         std::string Value;
48692987fb3SAlexander Kornienko         if (EvaluateExpression(Var, Value)) {
48792987fb3SAlexander Kornienko           OS << "with expression \"";
48892987fb3SAlexander Kornienko           OS.write_escaped(Var) << "\" equal to \"";
48992987fb3SAlexander Kornienko           OS.write_escaped(Value) << "\"";
49092987fb3SAlexander Kornienko         } else {
49192987fb3SAlexander Kornienko           OS << "uses incorrect expression \"";
49292987fb3SAlexander Kornienko           OS.write_escaped(Var) << "\"";
49392987fb3SAlexander Kornienko         }
49492987fb3SAlexander Kornienko       } else {
49592987fb3SAlexander Kornienko         StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
496e0ef65abSDaniel Dunbar 
497e0ef65abSDaniel Dunbar         // Check for undefined variable references.
498e0ef65abSDaniel Dunbar         if (it == VariableTable.end()) {
499e0ef65abSDaniel Dunbar           OS << "uses undefined variable \"";
50092987fb3SAlexander Kornienko           OS.write_escaped(Var) << "\"";
501e0ef65abSDaniel Dunbar         } else {
502e0ef65abSDaniel Dunbar           OS << "with variable \"";
503e0ef65abSDaniel Dunbar           OS.write_escaped(Var) << "\" equal to \"";
504e0ef65abSDaniel Dunbar           OS.write_escaped(it->second) << "\"";
505e0ef65abSDaniel Dunbar         }
50692987fb3SAlexander Kornienko       }
507e0ef65abSDaniel Dunbar 
50803b80a40SChris Lattner       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
50903b80a40SChris Lattner                       OS.str());
510e0ef65abSDaniel Dunbar     }
511e0ef65abSDaniel Dunbar   }
512fd29d886SDaniel Dunbar 
513fd29d886SDaniel Dunbar   // Attempt to find the closest/best fuzzy match.  Usually an error happens
514fd29d886SDaniel Dunbar   // because some string in the output didn't exactly match. In these cases, we
515fd29d886SDaniel Dunbar   // would like to show the user a best guess at what "should have" matched, to
516fd29d886SDaniel Dunbar   // save them having to actually check the input manually.
517fd29d886SDaniel Dunbar   size_t NumLinesForward = 0;
518fd29d886SDaniel Dunbar   size_t Best = StringRef::npos;
519fd29d886SDaniel Dunbar   double BestQuality = 0;
520fd29d886SDaniel Dunbar 
521fd29d886SDaniel Dunbar   // Use an arbitrary 4k limit on how far we will search.
5222bf486ebSDan Gohman   for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
523fd29d886SDaniel Dunbar     if (Buffer[i] == '\n')
524fd29d886SDaniel Dunbar       ++NumLinesForward;
525fd29d886SDaniel Dunbar 
526df22bbf7SDan Gohman     // Patterns have leading whitespace stripped, so skip whitespace when
527df22bbf7SDan Gohman     // looking for something which looks like a pattern.
528df22bbf7SDan Gohman     if (Buffer[i] == ' ' || Buffer[i] == '\t')
529df22bbf7SDan Gohman       continue;
530df22bbf7SDan Gohman 
531fd29d886SDaniel Dunbar     // Compute the "quality" of this match as an arbitrary combination of the
532fd29d886SDaniel Dunbar     // match distance and the number of lines skipped to get to this match.
533fd29d886SDaniel Dunbar     unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
534fd29d886SDaniel Dunbar     double Quality = Distance + (NumLinesForward / 100.);
535fd29d886SDaniel Dunbar 
536fd29d886SDaniel Dunbar     if (Quality < BestQuality || Best == StringRef::npos) {
537fd29d886SDaniel Dunbar       Best = i;
538fd29d886SDaniel Dunbar       BestQuality = Quality;
539fd29d886SDaniel Dunbar     }
540fd29d886SDaniel Dunbar   }
541fd29d886SDaniel Dunbar 
542fd29d886SDaniel Dunbar   // Print the "possible intended match here" line if we found something
543c069cc8eSDaniel Dunbar   // reasonable and not equal to what we showed in the "scanning from here"
544c069cc8eSDaniel Dunbar   // line.
545c069cc8eSDaniel Dunbar   if (Best && Best != StringRef::npos && BestQuality < 50) {
546fd29d886SDaniel Dunbar       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
54703b80a40SChris Lattner                       SourceMgr::DK_Note, "possible intended match here");
548fd29d886SDaniel Dunbar 
549fd29d886SDaniel Dunbar     // FIXME: If we wanted to be really friendly we would show why the match
550fd29d886SDaniel Dunbar     // failed, as it can be hard to spot simple one character differences.
551fd29d886SDaniel Dunbar   }
552e0ef65abSDaniel Dunbar }
55374d50731SChris Lattner 
554061d2baaSEli Bendersky size_t Pattern::FindRegexVarEnd(StringRef Str) {
555061d2baaSEli Bendersky   // Offset keeps track of the current offset within the input Str
556061d2baaSEli Bendersky   size_t Offset = 0;
557061d2baaSEli Bendersky   // [...] Nesting depth
558061d2baaSEli Bendersky   size_t BracketDepth = 0;
559061d2baaSEli Bendersky 
560061d2baaSEli Bendersky   while (!Str.empty()) {
561061d2baaSEli Bendersky     if (Str.startswith("]]") && BracketDepth == 0)
562061d2baaSEli Bendersky       return Offset;
563061d2baaSEli Bendersky     if (Str[0] == '\\') {
564061d2baaSEli Bendersky       // Backslash escapes the next char within regexes, so skip them both.
565061d2baaSEli Bendersky       Str = Str.substr(2);
566061d2baaSEli Bendersky       Offset += 2;
567061d2baaSEli Bendersky     } else {
568061d2baaSEli Bendersky       switch (Str[0]) {
569061d2baaSEli Bendersky         default:
570061d2baaSEli Bendersky           break;
571061d2baaSEli Bendersky         case '[':
572061d2baaSEli Bendersky           BracketDepth++;
573061d2baaSEli Bendersky           break;
574061d2baaSEli Bendersky         case ']':
575061d2baaSEli Bendersky           assert(BracketDepth > 0 && "Invalid regex");
576061d2baaSEli Bendersky           BracketDepth--;
577061d2baaSEli Bendersky           break;
578061d2baaSEli Bendersky       }
579061d2baaSEli Bendersky       Str = Str.substr(1);
580061d2baaSEli Bendersky       Offset++;
581061d2baaSEli Bendersky     }
582061d2baaSEli Bendersky   }
583061d2baaSEli Bendersky 
584061d2baaSEli Bendersky   return StringRef::npos;
585061d2baaSEli Bendersky }
586061d2baaSEli Bendersky 
587061d2baaSEli Bendersky 
58874d50731SChris Lattner //===----------------------------------------------------------------------===//
58974d50731SChris Lattner // Check Strings.
59074d50731SChris Lattner //===----------------------------------------------------------------------===//
5913b40b445SChris Lattner 
5923b40b445SChris Lattner /// CheckString - This is a check that we found in the input file.
5933b40b445SChris Lattner struct CheckString {
5943b40b445SChris Lattner   /// Pat - The pattern to match.
5953b40b445SChris Lattner   Pattern Pat;
59626cccfe1SChris Lattner 
59726cccfe1SChris Lattner   /// Loc - The location in the match file that the check string was specified.
59826cccfe1SChris Lattner   SMLoc Loc;
59926cccfe1SChris Lattner 
60038820972SMatt Arsenault   /// CheckTy - Specify what kind of check this is. e.g. CHECK-NEXT: directive,
60138820972SMatt Arsenault   /// as opposed to a CHECK: directive.
60238820972SMatt Arsenault   Check::CheckType CheckTy;
603f8bd2e5bSStephen Lin 
60491a1b2c9SMichael Liao   /// DagNotStrings - These are all of the strings that are disallowed from
605236d2d5eSChris Lattner   /// occurring between this match string and the previous one (or start of
606236d2d5eSChris Lattner   /// file).
60791a1b2c9SMichael Liao   std::vector<Pattern> DagNotStrings;
608236d2d5eSChris Lattner 
60938820972SMatt Arsenault   CheckString(const Pattern &P, SMLoc L, Check::CheckType Ty)
61038820972SMatt Arsenault     : Pat(P), Loc(L), CheckTy(Ty) {}
611dcc7d48dSMichael Liao 
61291a1b2c9SMichael Liao   /// Check - Match check string and its "not strings" and/or "dag strings".
613e93a3a08SStephen Lin   size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode,
614f8bd2e5bSStephen Lin                size_t &MatchLen, StringMap<StringRef> &VariableTable) const;
615dcc7d48dSMichael Liao 
616dcc7d48dSMichael Liao   /// CheckNext - Verify there is a single line in the given buffer.
617dcc7d48dSMichael Liao   bool CheckNext(const SourceMgr &SM, StringRef Buffer) const;
618dcc7d48dSMichael Liao 
619dcc7d48dSMichael Liao   /// CheckNot - Verify there's no "not strings" in the given buffer.
620dcc7d48dSMichael Liao   bool CheckNot(const SourceMgr &SM, StringRef Buffer,
62191a1b2c9SMichael Liao                 const std::vector<const Pattern *> &NotStrings,
62291a1b2c9SMichael Liao                 StringMap<StringRef> &VariableTable) const;
62391a1b2c9SMichael Liao 
62491a1b2c9SMichael Liao   /// CheckDag - Match "dag strings" and their mixed "not strings".
62591a1b2c9SMichael Liao   size_t CheckDag(const SourceMgr &SM, StringRef Buffer,
62691a1b2c9SMichael Liao                   std::vector<const Pattern *> &NotStrings,
627dcc7d48dSMichael Liao                   StringMap<StringRef> &VariableTable) const;
62826cccfe1SChris Lattner };
62926cccfe1SChris Lattner 
6305ea04c38SGuy Benyei /// Canonicalize whitespaces in the input file. Line endings are replaced
6315ea04c38SGuy Benyei /// with UNIX-style '\n'.
6325ea04c38SGuy Benyei ///
6335ea04c38SGuy Benyei /// \param PreserveHorizontal Don't squash consecutive horizontal whitespace
6345ea04c38SGuy Benyei /// characters to a single space.
6355ea04c38SGuy Benyei static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB,
6365ea04c38SGuy Benyei                                            bool PreserveHorizontal) {
6370e45d24aSChris Lattner   SmallString<128> NewFile;
638a2f8fc5aSChris Lattner   NewFile.reserve(MB->getBufferSize());
639a2f8fc5aSChris Lattner 
640a2f8fc5aSChris Lattner   for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
641a2f8fc5aSChris Lattner        Ptr != End; ++Ptr) {
642fd781bf0SNAKAMURA Takumi     // Eliminate trailing dosish \r.
643fd781bf0SNAKAMURA Takumi     if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
644fd781bf0SNAKAMURA Takumi       continue;
645fd781bf0SNAKAMURA Takumi     }
646fd781bf0SNAKAMURA Takumi 
6475ea04c38SGuy Benyei     // If current char is not a horizontal whitespace or if horizontal
6485ea04c38SGuy Benyei     // whitespace canonicalization is disabled, dump it to output as is.
6495ea04c38SGuy Benyei     if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) {
650a2f8fc5aSChris Lattner       NewFile.push_back(*Ptr);
651a2f8fc5aSChris Lattner       continue;
652a2f8fc5aSChris Lattner     }
653a2f8fc5aSChris Lattner 
654a2f8fc5aSChris Lattner     // Otherwise, add one space and advance over neighboring space.
655a2f8fc5aSChris Lattner     NewFile.push_back(' ');
656a2f8fc5aSChris Lattner     while (Ptr+1 != End &&
657a2f8fc5aSChris Lattner            (Ptr[1] == ' ' || Ptr[1] == '\t'))
658a2f8fc5aSChris Lattner       ++Ptr;
659a2f8fc5aSChris Lattner   }
660a2f8fc5aSChris Lattner 
661a2f8fc5aSChris Lattner   // Free the old buffer and return a new one.
662a2f8fc5aSChris Lattner   MemoryBuffer *MB2 =
6630e45d24aSChris Lattner     MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
664a2f8fc5aSChris Lattner 
665a2f8fc5aSChris Lattner   delete MB;
666a2f8fc5aSChris Lattner   return MB2;
667a2f8fc5aSChris Lattner }
668a2f8fc5aSChris Lattner 
66938820972SMatt Arsenault static bool IsPartOfWord(char c) {
67038820972SMatt Arsenault   return (isalnum(c) || c == '-' || c == '_');
67138820972SMatt Arsenault }
67238820972SMatt Arsenault 
67338820972SMatt Arsenault static Check::CheckType FindCheckType(StringRef &Buffer, StringRef Prefix) {
674c4d2d471SMatt Arsenault   char NextChar = Buffer[Prefix.size()];
67538820972SMatt Arsenault 
67638820972SMatt Arsenault   // Verify that the : is present after the prefix.
67738820972SMatt Arsenault   if (NextChar == ':') {
678c4d2d471SMatt Arsenault     Buffer = Buffer.substr(Prefix.size() + 1);
67938820972SMatt Arsenault     return Check::CheckPlain;
68038820972SMatt Arsenault   }
68138820972SMatt Arsenault 
68238820972SMatt Arsenault   if (NextChar != '-') {
68338820972SMatt Arsenault     Buffer = Buffer.drop_front(1);
68438820972SMatt Arsenault     return Check::CheckNone;
68538820972SMatt Arsenault   }
68638820972SMatt Arsenault 
687c4d2d471SMatt Arsenault   StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
68838820972SMatt Arsenault   if (Rest.startswith("NEXT:")) {
68938820972SMatt Arsenault     Buffer = Rest.drop_front(sizeof("NEXT:") - 1);
69038820972SMatt Arsenault     return Check::CheckNext;
69138820972SMatt Arsenault   }
69238820972SMatt Arsenault 
69338820972SMatt Arsenault   if (Rest.startswith("NOT:")) {
69438820972SMatt Arsenault     Buffer = Rest.drop_front(sizeof("NOT:") - 1);
69538820972SMatt Arsenault     return Check::CheckNot;
69638820972SMatt Arsenault   }
69738820972SMatt Arsenault 
69838820972SMatt Arsenault   if (Rest.startswith("DAG:")) {
69938820972SMatt Arsenault     Buffer = Rest.drop_front(sizeof("DAG:") - 1);
70038820972SMatt Arsenault     return Check::CheckDAG;
70138820972SMatt Arsenault   }
70238820972SMatt Arsenault 
70338820972SMatt Arsenault   if (Rest.startswith("LABEL:")) {
70438820972SMatt Arsenault     Buffer = Rest.drop_front(sizeof("LABEL:") - 1);
70538820972SMatt Arsenault     return Check::CheckLabel;
70638820972SMatt Arsenault   }
70738820972SMatt Arsenault 
70838820972SMatt Arsenault   Buffer = Buffer.drop_front(1);
70938820972SMatt Arsenault   return Check::CheckNone;
71038820972SMatt Arsenault }
711ee3c74fbSChris Lattner 
712ee3c74fbSChris Lattner /// ReadCheckFile - Read the check file, which specifies the sequence of
713ee3c74fbSChris Lattner /// expected strings.  The strings are added to the CheckStrings vector.
71443d50d4aSEli Bendersky /// Returns true in case of an error, false otherwise.
715ee3c74fbSChris Lattner static bool ReadCheckFile(SourceMgr &SM,
71626cccfe1SChris Lattner                           std::vector<CheckString> &CheckStrings) {
71739a0ffc3SMichael J. Spencer   OwningPtr<MemoryBuffer> File;
71839a0ffc3SMichael J. Spencer   if (error_code ec =
7198c811724SRafael Espindola         MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) {
720ee3c74fbSChris Lattner     errs() << "Could not open check file '" << CheckFilename << "': "
7217b6fef82SMichael J. Spencer            << ec.message() << '\n';
722ee3c74fbSChris Lattner     return true;
723ee3c74fbSChris Lattner   }
724a2f8fc5aSChris Lattner 
725a2f8fc5aSChris Lattner   // If we want to canonicalize whitespace, strip excess whitespace from the
7265ea04c38SGuy Benyei   // buffer containing the CHECK lines. Remove DOS style line endings.
727e963d660SBenjamin Kramer   MemoryBuffer *F =
728e963d660SBenjamin Kramer     CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
729a2f8fc5aSChris Lattner 
730ee3c74fbSChris Lattner   SM.AddNewSourceBuffer(F, SMLoc());
731ee3c74fbSChris Lattner 
73210f10cedSChris Lattner   // Find all instances of CheckPrefix followed by : in the file.
733caa5fc0cSChris Lattner   StringRef Buffer = F->getBuffer();
73491a1b2c9SMichael Liao   std::vector<Pattern> DagNotMatches;
735236d2d5eSChris Lattner 
73643d50d4aSEli Bendersky   // LineNumber keeps track of the line on which CheckPrefix instances are
73743d50d4aSEli Bendersky   // found.
73892987fb3SAlexander Kornienko   unsigned LineNumber = 1;
73992987fb3SAlexander Kornienko 
740ee3c74fbSChris Lattner   while (1) {
741ee3c74fbSChris Lattner     // See if Prefix occurs in the memory buffer.
74292987fb3SAlexander Kornienko     size_t PrefixLoc = Buffer.find(CheckPrefix);
743ee3c74fbSChris Lattner     // If we didn't find a match, we're done.
74492987fb3SAlexander Kornienko     if (PrefixLoc == StringRef::npos)
745ee3c74fbSChris Lattner       break;
746ee3c74fbSChris Lattner 
74792987fb3SAlexander Kornienko     LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
74892987fb3SAlexander Kornienko 
749c2735158SRui Ueyama     // Keep the charcter before our prefix so we can validate that we have
750c2735158SRui Ueyama     // found our prefix, and account for cases when PrefixLoc is 0.
751c2735158SRui Ueyama     Buffer = Buffer.substr(std::min(PrefixLoc-1, PrefixLoc));
75292987fb3SAlexander Kornienko 
753c2735158SRui Ueyama     const char *CheckPrefixStart = Buffer.data() + (PrefixLoc == 0 ? 0 : 1);
754da108b4eSChris Lattner 
755c2735158SRui Ueyama     // Make sure we have actually found our prefix, and not a word containing
756c2735158SRui Ueyama     // our prefix.
75738820972SMatt Arsenault     if (PrefixLoc != 0 && IsPartOfWord(Buffer[0])) {
758c2735158SRui Ueyama       Buffer = Buffer.substr(CheckPrefix.size());
759c2735158SRui Ueyama       continue;
760c2735158SRui Ueyama     }
761c2735158SRui Ueyama 
76238820972SMatt Arsenault     // When we find a check prefix, keep track of what kind of type of CHECK we
76338820972SMatt Arsenault     // have.
76438820972SMatt Arsenault     Check::CheckType CheckTy = FindCheckType(Buffer, CheckPrefix);
76538820972SMatt Arsenault     if (CheckTy == Check::CheckNone)
76610f10cedSChris Lattner       continue;
76710f10cedSChris Lattner 
76838820972SMatt Arsenault     // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
76938820972SMatt Arsenault     // leading and trailing whitespace.
770236d2d5eSChris Lattner     Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
771ee3c74fbSChris Lattner 
772ee3c74fbSChris Lattner     // Scan ahead to the end of line.
773caa5fc0cSChris Lattner     size_t EOL = Buffer.find_first_of("\n\r");
774ee3c74fbSChris Lattner 
775838fb09aSDan Gohman     // Remember the location of the start of the pattern, for diagnostics.
776838fb09aSDan Gohman     SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
777838fb09aSDan Gohman 
77874d50731SChris Lattner     // Parse the pattern.
77938820972SMatt Arsenault     Pattern P(CheckTy);
78092987fb3SAlexander Kornienko     if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
781ee3c74fbSChris Lattner       return true;
782ee3c74fbSChris Lattner 
783f8bd2e5bSStephen Lin     // Verify that CHECK-LABEL lines do not define or use variables
78438820972SMatt Arsenault     if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
785f8bd2e5bSStephen Lin       SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
786f8bd2e5bSStephen Lin                       SourceMgr::DK_Error,
787f8bd2e5bSStephen Lin                       "found '"+CheckPrefix+"-LABEL:' with variable definition"
788398b32a2SStephen Lin                       " or use");
789f8bd2e5bSStephen Lin       return true;
790f8bd2e5bSStephen Lin     }
791f8bd2e5bSStephen Lin 
792236d2d5eSChris Lattner     Buffer = Buffer.substr(EOL);
79374d50731SChris Lattner 
794da108b4eSChris Lattner     // Verify that CHECK-NEXT lines have at least one CHECK line before them.
79538820972SMatt Arsenault     if ((CheckTy == Check::CheckNext) && CheckStrings.empty()) {
796da108b4eSChris Lattner       SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
79703b80a40SChris Lattner                       SourceMgr::DK_Error,
798da108b4eSChris Lattner                       "found '"+CheckPrefix+"-NEXT:' without previous '"+
79903b80a40SChris Lattner                       CheckPrefix+ ": line");
800da108b4eSChris Lattner       return true;
801da108b4eSChris Lattner     }
802da108b4eSChris Lattner 
80391a1b2c9SMichael Liao     // Handle CHECK-DAG/-NOT.
80438820972SMatt Arsenault     if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
80591a1b2c9SMichael Liao       DagNotMatches.push_back(P);
80674d50731SChris Lattner       continue;
80774d50731SChris Lattner     }
80874d50731SChris Lattner 
809ee3c74fbSChris Lattner     // Okay, add the string we captured to the output vector and move on.
8103b40b445SChris Lattner     CheckStrings.push_back(CheckString(P,
811838fb09aSDan Gohman                                        PatternLoc,
81238820972SMatt Arsenault                                        CheckTy));
81391a1b2c9SMichael Liao     std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
814ee3c74fbSChris Lattner   }
815ee3c74fbSChris Lattner 
81691a1b2c9SMichael Liao   // Add an EOF pattern for any trailing CHECK-DAG/-NOTs.
81791a1b2c9SMichael Liao   if (!DagNotMatches.empty()) {
81838820972SMatt Arsenault     CheckStrings.push_back(CheckString(Pattern(Check::CheckEOF),
819eba55822SJakob Stoklund Olesen                                        SMLoc::getFromPointer(Buffer.data()),
82038820972SMatt Arsenault                                        Check::CheckEOF));
82191a1b2c9SMichael Liao     std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
822eba55822SJakob Stoklund Olesen   }
823eba55822SJakob Stoklund Olesen 
824ee3c74fbSChris Lattner   if (CheckStrings.empty()) {
82510f10cedSChris Lattner     errs() << "error: no check strings found with prefix '" << CheckPrefix
82610f10cedSChris Lattner            << ":'\n";
827ee3c74fbSChris Lattner     return true;
828ee3c74fbSChris Lattner   }
829ee3c74fbSChris Lattner 
830ee3c74fbSChris Lattner   return false;
831ee3c74fbSChris Lattner }
832ee3c74fbSChris Lattner 
83391a1b2c9SMichael Liao static void PrintCheckFailed(const SourceMgr &SM, const SMLoc &Loc,
83491a1b2c9SMichael Liao                              const Pattern &Pat, StringRef Buffer,
835e0ef65abSDaniel Dunbar                              StringMap<StringRef> &VariableTable) {
836da108b4eSChris Lattner   // Otherwise, we have an error, emit an error message.
83791a1b2c9SMichael Liao   SM.PrintMessage(Loc, SourceMgr::DK_Error,
83803b80a40SChris Lattner                   "expected string not found in input");
839da108b4eSChris Lattner 
840da108b4eSChris Lattner   // Print the "scanning from here" line.  If the current position is at the
841da108b4eSChris Lattner   // end of a line, advance to the start of the next line.
842caa5fc0cSChris Lattner   Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
843da108b4eSChris Lattner 
84403b80a40SChris Lattner   SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
84503b80a40SChris Lattner                   "scanning from here");
846e0ef65abSDaniel Dunbar 
847e0ef65abSDaniel Dunbar   // Allow the pattern to print additional information if desired.
84891a1b2c9SMichael Liao   Pat.PrintFailureInfo(SM, Buffer, VariableTable);
84991a1b2c9SMichael Liao }
85091a1b2c9SMichael Liao 
85191a1b2c9SMichael Liao static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
85291a1b2c9SMichael Liao                              StringRef Buffer,
85391a1b2c9SMichael Liao                              StringMap<StringRef> &VariableTable) {
85491a1b2c9SMichael Liao   PrintCheckFailed(SM, CheckStr.Loc, CheckStr.Pat, Buffer, VariableTable);
855da108b4eSChris Lattner }
856da108b4eSChris Lattner 
85737183584SChris Lattner /// CountNumNewlinesBetween - Count the number of newlines in the specified
85837183584SChris Lattner /// range.
85937183584SChris Lattner static unsigned CountNumNewlinesBetween(StringRef Range) {
860da108b4eSChris Lattner   unsigned NumNewLines = 0;
86137183584SChris Lattner   while (1) {
862da108b4eSChris Lattner     // Scan for newline.
86337183584SChris Lattner     Range = Range.substr(Range.find_first_of("\n\r"));
86437183584SChris Lattner     if (Range.empty()) return NumNewLines;
865da108b4eSChris Lattner 
866da108b4eSChris Lattner     ++NumNewLines;
867da108b4eSChris Lattner 
868da108b4eSChris Lattner     // Handle \n\r and \r\n as a single newline.
86937183584SChris Lattner     if (Range.size() > 1 &&
87037183584SChris Lattner         (Range[1] == '\n' || Range[1] == '\r') &&
87137183584SChris Lattner         (Range[0] != Range[1]))
87237183584SChris Lattner       Range = Range.substr(1);
87337183584SChris Lattner     Range = Range.substr(1);
874da108b4eSChris Lattner   }
875da108b4eSChris Lattner }
876da108b4eSChris Lattner 
877dcc7d48dSMichael Liao size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer,
878e93a3a08SStephen Lin                           bool IsLabelScanMode, size_t &MatchLen,
879dcc7d48dSMichael Liao                           StringMap<StringRef> &VariableTable) const {
88091a1b2c9SMichael Liao   size_t LastPos = 0;
88191a1b2c9SMichael Liao   std::vector<const Pattern *> NotStrings;
88291a1b2c9SMichael Liao 
883e93a3a08SStephen Lin   // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
884e93a3a08SStephen Lin   // bounds; we have not processed variable definitions within the bounded block
885e93a3a08SStephen Lin   // yet so cannot handle any final CHECK-DAG yet; this is handled when going
886e93a3a08SStephen Lin   // over the block again (including the last CHECK-LABEL) in normal mode.
887e93a3a08SStephen Lin   if (!IsLabelScanMode) {
88891a1b2c9SMichael Liao     // Match "dag strings" (with mixed "not strings" if any).
88991a1b2c9SMichael Liao     LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable);
89091a1b2c9SMichael Liao     if (LastPos == StringRef::npos)
89191a1b2c9SMichael Liao       return StringRef::npos;
892e93a3a08SStephen Lin   }
89391a1b2c9SMichael Liao 
89491a1b2c9SMichael Liao   // Match itself from the last position after matching CHECK-DAG.
89591a1b2c9SMichael Liao   StringRef MatchBuffer = Buffer.substr(LastPos);
89691a1b2c9SMichael Liao   size_t MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
897dcc7d48dSMichael Liao   if (MatchPos == StringRef::npos) {
89891a1b2c9SMichael Liao     PrintCheckFailed(SM, *this, MatchBuffer, VariableTable);
899dcc7d48dSMichael Liao     return StringRef::npos;
900dcc7d48dSMichael Liao   }
90191a1b2c9SMichael Liao   MatchPos += LastPos;
902dcc7d48dSMichael Liao 
903e93a3a08SStephen Lin   // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
904e93a3a08SStephen Lin   // or CHECK-NOT
905e93a3a08SStephen Lin   if (!IsLabelScanMode) {
90691a1b2c9SMichael Liao     StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
907dcc7d48dSMichael Liao 
908dcc7d48dSMichael Liao     // If this check is a "CHECK-NEXT", verify that the previous match was on
909dcc7d48dSMichael Liao     // the previous line (i.e. that there is one newline between them).
910dcc7d48dSMichael Liao     if (CheckNext(SM, SkippedRegion))
911dcc7d48dSMichael Liao       return StringRef::npos;
912dcc7d48dSMichael Liao 
913dcc7d48dSMichael Liao     // If this match had "not strings", verify that they don't exist in the
914dcc7d48dSMichael Liao     // skipped region.
91591a1b2c9SMichael Liao     if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
916dcc7d48dSMichael Liao       return StringRef::npos;
917f8bd2e5bSStephen Lin   }
918dcc7d48dSMichael Liao 
919dcc7d48dSMichael Liao   return MatchPos;
920dcc7d48dSMichael Liao }
921dcc7d48dSMichael Liao 
922dcc7d48dSMichael Liao bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
92338820972SMatt Arsenault   if (CheckTy != Check::CheckNext)
924dcc7d48dSMichael Liao     return false;
925dcc7d48dSMichael Liao 
926dcc7d48dSMichael Liao   // Count the number of newlines between the previous match and this one.
927dcc7d48dSMichael Liao   assert(Buffer.data() !=
928dcc7d48dSMichael Liao          SM.getMemoryBuffer(
929dcc7d48dSMichael Liao            SM.FindBufferContainingLoc(
930dcc7d48dSMichael Liao              SMLoc::getFromPointer(Buffer.data())))->getBufferStart() &&
931dcc7d48dSMichael Liao          "CHECK-NEXT can't be the first check in a file");
932dcc7d48dSMichael Liao 
933dcc7d48dSMichael Liao   unsigned NumNewLines = CountNumNewlinesBetween(Buffer);
934dcc7d48dSMichael Liao 
935dcc7d48dSMichael Liao   if (NumNewLines == 0) {
936dcc7d48dSMichael Liao     SM.PrintMessage(Loc, SourceMgr::DK_Error, CheckPrefix+
937dcc7d48dSMichael Liao                     "-NEXT: is on the same line as previous match");
938dcc7d48dSMichael Liao     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
939dcc7d48dSMichael Liao                     SourceMgr::DK_Note, "'next' match was here");
940dcc7d48dSMichael Liao     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
941dcc7d48dSMichael Liao                     "previous match ended here");
942dcc7d48dSMichael Liao     return true;
943dcc7d48dSMichael Liao   }
944dcc7d48dSMichael Liao 
945dcc7d48dSMichael Liao   if (NumNewLines != 1) {
946dcc7d48dSMichael Liao     SM.PrintMessage(Loc, SourceMgr::DK_Error, CheckPrefix+
947dcc7d48dSMichael Liao                     "-NEXT: is not on the line after the previous match");
948dcc7d48dSMichael Liao     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
949dcc7d48dSMichael Liao                     SourceMgr::DK_Note, "'next' match was here");
950dcc7d48dSMichael Liao     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
951dcc7d48dSMichael Liao                     "previous match ended here");
952dcc7d48dSMichael Liao     return true;
953dcc7d48dSMichael Liao   }
954dcc7d48dSMichael Liao 
955dcc7d48dSMichael Liao   return false;
956dcc7d48dSMichael Liao }
957dcc7d48dSMichael Liao 
958dcc7d48dSMichael Liao bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer,
95991a1b2c9SMichael Liao                            const std::vector<const Pattern *> &NotStrings,
960dcc7d48dSMichael Liao                            StringMap<StringRef> &VariableTable) const {
961dcc7d48dSMichael Liao   for (unsigned ChunkNo = 0, e = NotStrings.size();
962dcc7d48dSMichael Liao        ChunkNo != e; ++ChunkNo) {
96391a1b2c9SMichael Liao     const Pattern *Pat = NotStrings[ChunkNo];
96438820972SMatt Arsenault     assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
96591a1b2c9SMichael Liao 
966dcc7d48dSMichael Liao     size_t MatchLen = 0;
96791a1b2c9SMichael Liao     size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);
968dcc7d48dSMichael Liao 
969dcc7d48dSMichael Liao     if (Pos == StringRef::npos) continue;
970dcc7d48dSMichael Liao 
971dcc7d48dSMichael Liao     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos),
972dcc7d48dSMichael Liao                     SourceMgr::DK_Error,
973dcc7d48dSMichael Liao                     CheckPrefix+"-NOT: string occurred!");
97491a1b2c9SMichael Liao     SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note,
975dcc7d48dSMichael Liao                     CheckPrefix+"-NOT: pattern specified here");
976dcc7d48dSMichael Liao     return true;
977dcc7d48dSMichael Liao   }
978dcc7d48dSMichael Liao 
979dcc7d48dSMichael Liao   return false;
980dcc7d48dSMichael Liao }
981dcc7d48dSMichael Liao 
98291a1b2c9SMichael Liao size_t CheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
98391a1b2c9SMichael Liao                              std::vector<const Pattern *> &NotStrings,
98491a1b2c9SMichael Liao                              StringMap<StringRef> &VariableTable) const {
98591a1b2c9SMichael Liao   if (DagNotStrings.empty())
98691a1b2c9SMichael Liao     return 0;
98791a1b2c9SMichael Liao 
98891a1b2c9SMichael Liao   size_t LastPos = 0;
98991a1b2c9SMichael Liao   size_t StartPos = LastPos;
99091a1b2c9SMichael Liao 
99191a1b2c9SMichael Liao   for (unsigned ChunkNo = 0, e = DagNotStrings.size();
99291a1b2c9SMichael Liao        ChunkNo != e; ++ChunkNo) {
99391a1b2c9SMichael Liao     const Pattern &Pat = DagNotStrings[ChunkNo];
99491a1b2c9SMichael Liao 
99538820972SMatt Arsenault     assert((Pat.getCheckTy() == Check::CheckDAG ||
99638820972SMatt Arsenault             Pat.getCheckTy() == Check::CheckNot) &&
99791a1b2c9SMichael Liao            "Invalid CHECK-DAG or CHECK-NOT!");
99891a1b2c9SMichael Liao 
99938820972SMatt Arsenault     if (Pat.getCheckTy() == Check::CheckNot) {
100091a1b2c9SMichael Liao       NotStrings.push_back(&Pat);
100191a1b2c9SMichael Liao       continue;
100291a1b2c9SMichael Liao     }
100391a1b2c9SMichael Liao 
100438820972SMatt Arsenault     assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
100591a1b2c9SMichael Liao 
100691a1b2c9SMichael Liao     size_t MatchLen = 0, MatchPos;
100791a1b2c9SMichael Liao 
100891a1b2c9SMichael Liao     // CHECK-DAG always matches from the start.
100991a1b2c9SMichael Liao     StringRef MatchBuffer = Buffer.substr(StartPos);
101091a1b2c9SMichael Liao     MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
101191a1b2c9SMichael Liao     // With a group of CHECK-DAGs, a single mismatching means the match on
101291a1b2c9SMichael Liao     // that group of CHECK-DAGs fails immediately.
101391a1b2c9SMichael Liao     if (MatchPos == StringRef::npos) {
101491a1b2c9SMichael Liao       PrintCheckFailed(SM, Pat.getLoc(), Pat, MatchBuffer, VariableTable);
101591a1b2c9SMichael Liao       return StringRef::npos;
101691a1b2c9SMichael Liao     }
101791a1b2c9SMichael Liao     // Re-calc it as the offset relative to the start of the original string.
101891a1b2c9SMichael Liao     MatchPos += StartPos;
101991a1b2c9SMichael Liao 
102091a1b2c9SMichael Liao     if (!NotStrings.empty()) {
102191a1b2c9SMichael Liao       if (MatchPos < LastPos) {
102291a1b2c9SMichael Liao         // Reordered?
102391a1b2c9SMichael Liao         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + MatchPos),
102491a1b2c9SMichael Liao                         SourceMgr::DK_Error,
102591a1b2c9SMichael Liao                         CheckPrefix+"-DAG: found a match of CHECK-DAG"
102691a1b2c9SMichael Liao                         " reordering across a CHECK-NOT");
102791a1b2c9SMichael Liao         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + LastPos),
102891a1b2c9SMichael Liao                         SourceMgr::DK_Note,
102991a1b2c9SMichael Liao                         CheckPrefix+"-DAG: the farthest match of CHECK-DAG"
103091a1b2c9SMichael Liao                         " is found here");
103191a1b2c9SMichael Liao         SM.PrintMessage(NotStrings[0]->getLoc(), SourceMgr::DK_Note,
103291a1b2c9SMichael Liao                         CheckPrefix+"-NOT: the crossed pattern specified"
103391a1b2c9SMichael Liao                         " here");
103491a1b2c9SMichael Liao         SM.PrintMessage(Pat.getLoc(), SourceMgr::DK_Note,
103591a1b2c9SMichael Liao                         CheckPrefix+"-DAG: the reordered pattern specified"
103691a1b2c9SMichael Liao                         " here");
103791a1b2c9SMichael Liao         return StringRef::npos;
103891a1b2c9SMichael Liao       }
103991a1b2c9SMichael Liao       // All subsequent CHECK-DAGs should be matched from the farthest
104091a1b2c9SMichael Liao       // position of all precedent CHECK-DAGs (including this one.)
104191a1b2c9SMichael Liao       StartPos = LastPos;
104291a1b2c9SMichael Liao       // If there's CHECK-NOTs between two CHECK-DAGs or from CHECK to
104391a1b2c9SMichael Liao       // CHECK-DAG, verify that there's no 'not' strings occurred in that
104491a1b2c9SMichael Liao       // region.
104591a1b2c9SMichael Liao       StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1046cf708c32STim Northover       if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
104791a1b2c9SMichael Liao         return StringRef::npos;
104891a1b2c9SMichael Liao       // Clear "not strings".
104991a1b2c9SMichael Liao       NotStrings.clear();
105091a1b2c9SMichael Liao     }
105191a1b2c9SMichael Liao 
105291a1b2c9SMichael Liao     // Update the last position with CHECK-DAG matches.
105391a1b2c9SMichael Liao     LastPos = std::max(MatchPos + MatchLen, LastPos);
105491a1b2c9SMichael Liao   }
105591a1b2c9SMichael Liao 
105691a1b2c9SMichael Liao   return LastPos;
105791a1b2c9SMichael Liao }
105891a1b2c9SMichael Liao 
1059c2735158SRui Ueyama bool ValidateCheckPrefix() {
1060c2735158SRui Ueyama   // The check prefix must contain only alphanumeric, hyphens and underscores.
1061c2735158SRui Ueyama   Regex prefixValidator("^[a-zA-Z0-9_-]*$");
1062c2735158SRui Ueyama   return prefixValidator.match(CheckPrefix);
1063c2735158SRui Ueyama }
1064c2735158SRui Ueyama 
1065ee3c74fbSChris Lattner int main(int argc, char **argv) {
1066ee3c74fbSChris Lattner   sys::PrintStackTraceOnErrorSignal();
1067ee3c74fbSChris Lattner   PrettyStackTraceProgram X(argc, argv);
1068ee3c74fbSChris Lattner   cl::ParseCommandLineOptions(argc, argv);
1069ee3c74fbSChris Lattner 
1070c2735158SRui Ueyama   if (!ValidateCheckPrefix()) {
1071c2735158SRui Ueyama     errs() << "Supplied check-prefix is invalid! Prefixes must start with a "
1072c2735158SRui Ueyama               "letter and contain only alphanumeric characters, hyphens and "
1073c2735158SRui Ueyama               "underscores\n";
1074c2735158SRui Ueyama     return 2;
1075c2735158SRui Ueyama   }
1076c2735158SRui Ueyama 
1077ee3c74fbSChris Lattner   SourceMgr SM;
1078ee3c74fbSChris Lattner 
1079ee3c74fbSChris Lattner   // Read the expected strings from the check file.
108026cccfe1SChris Lattner   std::vector<CheckString> CheckStrings;
1081ee3c74fbSChris Lattner   if (ReadCheckFile(SM, CheckStrings))
1082ee3c74fbSChris Lattner     return 2;
1083ee3c74fbSChris Lattner 
1084ee3c74fbSChris Lattner   // Open the file to check and add it to SourceMgr.
108539a0ffc3SMichael J. Spencer   OwningPtr<MemoryBuffer> File;
108639a0ffc3SMichael J. Spencer   if (error_code ec =
10878c811724SRafael Espindola         MemoryBuffer::getFileOrSTDIN(InputFilename, File)) {
1088ee3c74fbSChris Lattner     errs() << "Could not open input file '" << InputFilename << "': "
10897b6fef82SMichael J. Spencer            << ec.message() << '\n';
10908e1c6477SEli Bendersky     return 2;
1091ee3c74fbSChris Lattner   }
10922c3e5cdfSChris Lattner 
1093e963d660SBenjamin Kramer   if (File->getBufferSize() == 0) {
1094b692bed7SChris Lattner     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
10958e1c6477SEli Bendersky     return 2;
1096b692bed7SChris Lattner   }
1097b692bed7SChris Lattner 
10982c3e5cdfSChris Lattner   // Remove duplicate spaces in the input file if requested.
10995ea04c38SGuy Benyei   // Remove DOS style line endings.
1100e963d660SBenjamin Kramer   MemoryBuffer *F =
1101e963d660SBenjamin Kramer     CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
11022c3e5cdfSChris Lattner 
1103ee3c74fbSChris Lattner   SM.AddNewSourceBuffer(F, SMLoc());
1104ee3c74fbSChris Lattner 
11058879e06dSChris Lattner   /// VariableTable - This holds all the current filecheck variables.
11068879e06dSChris Lattner   StringMap<StringRef> VariableTable;
11078879e06dSChris Lattner 
1108ee3c74fbSChris Lattner   // Check that we have all of the expected strings, in order, in the input
1109ee3c74fbSChris Lattner   // file.
1110caa5fc0cSChris Lattner   StringRef Buffer = F->getBuffer();
1111ee3c74fbSChris Lattner 
1112f8bd2e5bSStephen Lin   bool hasError = false;
1113ee3c74fbSChris Lattner 
1114f8bd2e5bSStephen Lin   unsigned i = 0, j = 0, e = CheckStrings.size();
1115ee3c74fbSChris Lattner 
1116f8bd2e5bSStephen Lin   while (true) {
1117f8bd2e5bSStephen Lin     StringRef CheckRegion;
1118f8bd2e5bSStephen Lin     if (j == e) {
1119f8bd2e5bSStephen Lin       CheckRegion = Buffer;
1120f8bd2e5bSStephen Lin     } else {
1121f8bd2e5bSStephen Lin       const CheckString &CheckLabelStr = CheckStrings[j];
112238820972SMatt Arsenault       if (CheckLabelStr.CheckTy != Check::CheckLabel) {
1123f8bd2e5bSStephen Lin         ++j;
1124f8bd2e5bSStephen Lin         continue;
1125da108b4eSChris Lattner       }
1126da108b4eSChris Lattner 
1127f8bd2e5bSStephen Lin       // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1128f8bd2e5bSStephen Lin       size_t MatchLabelLen = 0;
1129e93a3a08SStephen Lin       size_t MatchLabelPos = CheckLabelStr.Check(SM, Buffer, true,
1130f8bd2e5bSStephen Lin                                                  MatchLabelLen, VariableTable);
1131f8bd2e5bSStephen Lin       if (MatchLabelPos == StringRef::npos) {
1132f8bd2e5bSStephen Lin         hasError = true;
1133f8bd2e5bSStephen Lin         break;
1134f8bd2e5bSStephen Lin       }
1135f8bd2e5bSStephen Lin 
1136f8bd2e5bSStephen Lin       CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1137f8bd2e5bSStephen Lin       Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1138f8bd2e5bSStephen Lin       ++j;
1139f8bd2e5bSStephen Lin     }
1140f8bd2e5bSStephen Lin 
1141f8bd2e5bSStephen Lin     for ( ; i != j; ++i) {
1142f8bd2e5bSStephen Lin       const CheckString &CheckStr = CheckStrings[i];
1143f8bd2e5bSStephen Lin 
1144f8bd2e5bSStephen Lin       // Check each string within the scanned region, including a second check
1145f8bd2e5bSStephen Lin       // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1146f8bd2e5bSStephen Lin       size_t MatchLen = 0;
1147e93a3a08SStephen Lin       size_t MatchPos = CheckStr.Check(SM, CheckRegion, false, MatchLen,
1148f8bd2e5bSStephen Lin                                        VariableTable);
1149f8bd2e5bSStephen Lin 
1150f8bd2e5bSStephen Lin       if (MatchPos == StringRef::npos) {
1151f8bd2e5bSStephen Lin         hasError = true;
1152f8bd2e5bSStephen Lin         i = j;
1153f8bd2e5bSStephen Lin         break;
1154f8bd2e5bSStephen Lin       }
1155f8bd2e5bSStephen Lin 
1156f8bd2e5bSStephen Lin       CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1157f8bd2e5bSStephen Lin     }
1158f8bd2e5bSStephen Lin 
1159f8bd2e5bSStephen Lin     if (j == e)
1160f8bd2e5bSStephen Lin       break;
1161f8bd2e5bSStephen Lin   }
1162f8bd2e5bSStephen Lin 
1163f8bd2e5bSStephen Lin   return hasError ? 1 : 0;
1164ee3c74fbSChris Lattner }
1165