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>
32e8b8f1bcSEli Bendersky #include <map>
33e8b8f1bcSEli Bendersky #include <string>
34e8b8f1bcSEli Bendersky #include <vector>
35ee3c74fbSChris Lattner using namespace llvm;
36ee3c74fbSChris Lattner 
37ee3c74fbSChris Lattner static cl::opt<std::string>
38ee3c74fbSChris Lattner CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
39ee3c74fbSChris Lattner 
40ee3c74fbSChris Lattner static cl::opt<std::string>
41ee3c74fbSChris Lattner InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
42ee3c74fbSChris Lattner               cl::init("-"), cl::value_desc("filename"));
43ee3c74fbSChris Lattner 
44ee3c74fbSChris Lattner static cl::opt<std::string>
45ee3c74fbSChris Lattner CheckPrefix("check-prefix", cl::init("CHECK"),
46ee3c74fbSChris Lattner             cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
47ee3c74fbSChris Lattner 
482c3e5cdfSChris Lattner static cl::opt<bool>
492c3e5cdfSChris Lattner NoCanonicalizeWhiteSpace("strict-whitespace",
502c3e5cdfSChris Lattner               cl::desc("Do not treat all horizontal whitespace as equivalent"));
512c3e5cdfSChris Lattner 
5274d50731SChris Lattner //===----------------------------------------------------------------------===//
5374d50731SChris Lattner // Pattern Handling Code.
5474d50731SChris Lattner //===----------------------------------------------------------------------===//
5574d50731SChris Lattner 
5638820972SMatt Arsenault namespace Check {
5738820972SMatt Arsenault   enum CheckType {
5838820972SMatt Arsenault     CheckNone = 0,
5938820972SMatt Arsenault     CheckPlain,
6038820972SMatt Arsenault     CheckNext,
6138820972SMatt Arsenault     CheckNot,
6238820972SMatt Arsenault     CheckDAG,
6338820972SMatt Arsenault     CheckLabel,
640a4c44bdSChris Lattner 
65eba55822SJakob Stoklund Olesen     /// MatchEOF - When set, this pattern only matches the end of file. This is
66eba55822SJakob Stoklund Olesen     /// used for trailing CHECK-NOTs.
6738820972SMatt Arsenault     CheckEOF
6838820972SMatt Arsenault   };
6938820972SMatt Arsenault }
70eba55822SJakob Stoklund Olesen 
7138820972SMatt Arsenault class Pattern {
7238820972SMatt Arsenault   SMLoc PatternLoc;
7391a1b2c9SMichael Liao 
7438820972SMatt Arsenault   Check::CheckType CheckTy;
7591a1b2c9SMichael Liao 
76b16ab0c4SChris Lattner   /// FixedStr - If non-empty, this pattern is a fixed string match with the
77b16ab0c4SChris Lattner   /// specified fixed string.
78221460e0SChris Lattner   StringRef FixedStr;
79b16ab0c4SChris Lattner 
80b16ab0c4SChris Lattner   /// RegEx - If non-empty, this is a regex pattern.
81b16ab0c4SChris Lattner   std::string RegExStr;
828879e06dSChris Lattner 
8392987fb3SAlexander Kornienko   /// \brief Contains the number of line this pattern is in.
8492987fb3SAlexander Kornienko   unsigned LineNumber;
8592987fb3SAlexander Kornienko 
868879e06dSChris Lattner   /// VariableUses - Entries in this vector map to uses of a variable in the
878879e06dSChris Lattner   /// pattern, e.g. "foo[[bar]]baz".  In this case, the RegExStr will contain
888879e06dSChris Lattner   /// "foobaz" and we'll get an entry in this vector that tells us to insert the
898879e06dSChris Lattner   /// value of bar at offset 3.
908879e06dSChris Lattner   std::vector<std::pair<StringRef, unsigned> > VariableUses;
918879e06dSChris Lattner 
92e8b8f1bcSEli Bendersky   /// VariableDefs - Maps definitions of variables to their parenthesized
93e8b8f1bcSEli Bendersky   /// capture numbers.
94e8b8f1bcSEli Bendersky   /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
95e8b8f1bcSEli Bendersky   std::map<StringRef, unsigned> VariableDefs;
968879e06dSChris Lattner 
973b40b445SChris Lattner public:
983b40b445SChris Lattner 
9938820972SMatt Arsenault   Pattern(Check::CheckType Ty)
10038820972SMatt Arsenault     : CheckTy(Ty) { }
10174d50731SChris Lattner 
1020b707eb8SMichael Liao   /// getLoc - Return the location in source code.
1030b707eb8SMichael Liao   SMLoc getLoc() const { return PatternLoc; }
1040b707eb8SMichael Liao 
10543d50d4aSEli Bendersky   /// ParsePattern - Parse the given string into the Pattern.  SM provides the
10643d50d4aSEli Bendersky   /// SourceMgr used for error reports, and LineNumber is the line number in
10743d50d4aSEli Bendersky   /// the input file from which the pattern string was read.
10843d50d4aSEli Bendersky   /// Returns true in case of an error, false otherwise.
10992987fb3SAlexander Kornienko   bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
1103b40b445SChris Lattner 
1113b40b445SChris Lattner   /// Match - Match the pattern string against the input buffer Buffer.  This
1123b40b445SChris Lattner   /// returns the position that is matched or npos if there is no match.  If
1133b40b445SChris Lattner   /// there is a match, the size of the matched string is returned in MatchLen.
1148879e06dSChris Lattner   ///
1158879e06dSChris Lattner   /// The VariableTable StringMap provides the current values of filecheck
1168879e06dSChris Lattner   /// variables and is updated if this match defines new values.
1178879e06dSChris Lattner   size_t Match(StringRef Buffer, size_t &MatchLen,
1188879e06dSChris Lattner                StringMap<StringRef> &VariableTable) const;
119b16ab0c4SChris Lattner 
120e0ef65abSDaniel Dunbar   /// PrintFailureInfo - Print additional information about a failure to match
121e0ef65abSDaniel Dunbar   /// involving this pattern.
122e0ef65abSDaniel Dunbar   void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
123e0ef65abSDaniel Dunbar                         const StringMap<StringRef> &VariableTable) const;
124e0ef65abSDaniel Dunbar 
125f8bd2e5bSStephen Lin   bool hasVariable() const { return !(VariableUses.empty() &&
126f8bd2e5bSStephen Lin                                       VariableDefs.empty()); }
127f8bd2e5bSStephen Lin 
12838820972SMatt Arsenault   Check::CheckType getCheckTy() const { return CheckTy; }
12991a1b2c9SMichael Liao 
130b16ab0c4SChris Lattner private:
1318879e06dSChris Lattner   static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
132e8b8f1bcSEli Bendersky   bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
133e8b8f1bcSEli Bendersky   void AddBackrefToRegEx(unsigned BackrefNum);
134fd29d886SDaniel Dunbar 
135fd29d886SDaniel Dunbar   /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
136fd29d886SDaniel Dunbar   /// matching this pattern at the start of \arg Buffer; a distance of zero
137fd29d886SDaniel Dunbar   /// should correspond to a perfect match.
138fd29d886SDaniel Dunbar   unsigned ComputeMatchDistance(StringRef Buffer,
139fd29d886SDaniel Dunbar                                const StringMap<StringRef> &VariableTable) const;
14092987fb3SAlexander Kornienko 
14192987fb3SAlexander Kornienko   /// \brief Evaluates expression and stores the result to \p Value.
14292987fb3SAlexander Kornienko   /// \return true on success. false when the expression has invalid syntax.
14392987fb3SAlexander Kornienko   bool EvaluateExpression(StringRef Expr, std::string &Value) const;
144061d2baaSEli Bendersky 
145061d2baaSEli Bendersky   /// \brief Finds the closing sequence of a regex variable usage or
146061d2baaSEli Bendersky   /// definition. Str has to point in the beginning of the definition
147061d2baaSEli Bendersky   /// (right after the opening sequence).
148061d2baaSEli Bendersky   /// \return offset of the closing sequence within Str, or npos if it was not
149061d2baaSEli Bendersky   /// found.
150061d2baaSEli Bendersky   size_t FindRegexVarEnd(StringRef Str);
1513b40b445SChris Lattner };
1523b40b445SChris Lattner 
1538879e06dSChris Lattner 
15492987fb3SAlexander Kornienko bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
15592987fb3SAlexander Kornienko                            unsigned LineNumber) {
15692987fb3SAlexander Kornienko   this->LineNumber = LineNumber;
1570a4c44bdSChris Lattner   PatternLoc = SMLoc::getFromPointer(PatternStr.data());
1580a4c44bdSChris Lattner 
15974d50731SChris Lattner   // Ignore trailing whitespace.
16074d50731SChris Lattner   while (!PatternStr.empty() &&
16174d50731SChris Lattner          (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
16274d50731SChris Lattner     PatternStr = PatternStr.substr(0, PatternStr.size()-1);
16374d50731SChris Lattner 
16474d50731SChris Lattner   // Check that there is something on the line.
16574d50731SChris Lattner   if (PatternStr.empty()) {
16603b80a40SChris Lattner     SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
16703b80a40SChris Lattner                     "found empty check string with prefix '" +
16803b80a40SChris Lattner                     CheckPrefix+":'");
16974d50731SChris Lattner     return true;
17074d50731SChris Lattner   }
17174d50731SChris Lattner 
172221460e0SChris Lattner   // Check to see if this is a fixed string, or if it has regex pieces.
173d9466967STed Kremenek   if (PatternStr.size() < 2 ||
1748879e06dSChris Lattner       (PatternStr.find("{{") == StringRef::npos &&
1758879e06dSChris Lattner        PatternStr.find("[[") == StringRef::npos)) {
176221460e0SChris Lattner     FixedStr = PatternStr;
177221460e0SChris Lattner     return false;
178221460e0SChris Lattner   }
179221460e0SChris Lattner 
1808879e06dSChris Lattner   // Paren value #0 is for the fully matched string.  Any new parenthesized
18153e0679dSChris Lattner   // values add from there.
1828879e06dSChris Lattner   unsigned CurParen = 1;
1838879e06dSChris Lattner 
184b16ab0c4SChris Lattner   // Otherwise, there is at least one regex piece.  Build up the regex pattern
185b16ab0c4SChris Lattner   // by escaping scary characters in fixed strings, building up one big regex.
186f08d2db9SChris Lattner   while (!PatternStr.empty()) {
1878879e06dSChris Lattner     // RegEx matches.
18853e0679dSChris Lattner     if (PatternStr.startswith("{{")) {
18943d50d4aSEli Bendersky       // This is the start of a regex match.  Scan for the }}.
190f08d2db9SChris Lattner       size_t End = PatternStr.find("}}");
191f08d2db9SChris Lattner       if (End == StringRef::npos) {
192f08d2db9SChris Lattner         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
19303b80a40SChris Lattner                         SourceMgr::DK_Error,
19403b80a40SChris Lattner                         "found start of regex string with no end '}}'");
195f08d2db9SChris Lattner         return true;
196f08d2db9SChris Lattner       }
197f08d2db9SChris Lattner 
198e53c95f1SChris Lattner       // Enclose {{}} patterns in parens just like [[]] even though we're not
199e53c95f1SChris Lattner       // capturing the result for any purpose.  This is required in case the
200e53c95f1SChris Lattner       // expression contains an alternation like: CHECK:  abc{{x|z}}def.  We
201e53c95f1SChris Lattner       // want this to turn into: "abc(x|z)def" not "abcx|zdef".
202e53c95f1SChris Lattner       RegExStr += '(';
203e53c95f1SChris Lattner       ++CurParen;
204e53c95f1SChris Lattner 
2058879e06dSChris Lattner       if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
2068879e06dSChris Lattner         return true;
207e53c95f1SChris Lattner       RegExStr += ')';
20853e0679dSChris Lattner 
2098879e06dSChris Lattner       PatternStr = PatternStr.substr(End+2);
2108879e06dSChris Lattner       continue;
2118879e06dSChris Lattner     }
2128879e06dSChris Lattner 
2138879e06dSChris Lattner     // Named RegEx matches.  These are of two forms: [[foo:.*]] which matches .*
2148879e06dSChris Lattner     // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
2158879e06dSChris Lattner     // second form is [[foo]] which is a reference to foo.  The variable name
21657cb733bSDaniel Dunbar     // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
2178879e06dSChris Lattner     // it.  This is to catch some common errors.
21853e0679dSChris Lattner     if (PatternStr.startswith("[[")) {
219061d2baaSEli Bendersky       // Find the closing bracket pair ending the match.  End is going to be an
220061d2baaSEli Bendersky       // offset relative to the beginning of the match string.
221061d2baaSEli Bendersky       size_t End = FindRegexVarEnd(PatternStr.substr(2));
222061d2baaSEli Bendersky 
2238879e06dSChris Lattner       if (End == StringRef::npos) {
2248879e06dSChris Lattner         SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
22503b80a40SChris Lattner                         SourceMgr::DK_Error,
22603b80a40SChris Lattner                         "invalid named regex reference, no ]] found");
227f08d2db9SChris Lattner         return true;
228f08d2db9SChris Lattner       }
229f08d2db9SChris Lattner 
230061d2baaSEli Bendersky       StringRef MatchStr = PatternStr.substr(2, End);
231061d2baaSEli Bendersky       PatternStr = PatternStr.substr(End+4);
2328879e06dSChris Lattner 
2338879e06dSChris Lattner       // Get the regex name (e.g. "foo").
2348879e06dSChris Lattner       size_t NameEnd = MatchStr.find(':');
2358879e06dSChris Lattner       StringRef Name = MatchStr.substr(0, NameEnd);
2368879e06dSChris Lattner 
2378879e06dSChris Lattner       if (Name.empty()) {
23803b80a40SChris Lattner         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
23903b80a40SChris Lattner                         "invalid name in named regex: empty name");
2408879e06dSChris Lattner         return true;
2418879e06dSChris Lattner       }
2428879e06dSChris Lattner 
24392987fb3SAlexander Kornienko       // Verify that the name/expression is well formed. FileCheck currently
24492987fb3SAlexander Kornienko       // supports @LINE, @LINE+number, @LINE-number expressions. The check here
24592987fb3SAlexander Kornienko       // is relaxed, more strict check is performed in \c EvaluateExpression.
24692987fb3SAlexander Kornienko       bool IsExpression = false;
24792987fb3SAlexander Kornienko       for (unsigned i = 0, e = Name.size(); i != e; ++i) {
24892987fb3SAlexander Kornienko         if (i == 0 && Name[i] == '@') {
24992987fb3SAlexander Kornienko           if (NameEnd != StringRef::npos) {
25092987fb3SAlexander Kornienko             SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
25192987fb3SAlexander Kornienko                             SourceMgr::DK_Error,
25292987fb3SAlexander Kornienko                             "invalid name in named regex definition");
25392987fb3SAlexander Kornienko             return true;
25492987fb3SAlexander Kornienko           }
25592987fb3SAlexander Kornienko           IsExpression = true;
25692987fb3SAlexander Kornienko           continue;
25792987fb3SAlexander Kornienko         }
25892987fb3SAlexander Kornienko         if (Name[i] != '_' && !isalnum(Name[i]) &&
25992987fb3SAlexander Kornienko             (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
2608879e06dSChris Lattner           SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
26103b80a40SChris Lattner                           SourceMgr::DK_Error, "invalid name in named regex");
2628879e06dSChris Lattner           return true;
2638879e06dSChris Lattner         }
26492987fb3SAlexander Kornienko       }
2658879e06dSChris Lattner 
2668879e06dSChris Lattner       // Name can't start with a digit.
26783c74e9fSGuy Benyei       if (isdigit(static_cast<unsigned char>(Name[0]))) {
26803b80a40SChris Lattner         SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
26903b80a40SChris Lattner                         "invalid name in named regex");
2708879e06dSChris Lattner         return true;
2718879e06dSChris Lattner       }
2728879e06dSChris Lattner 
2738879e06dSChris Lattner       // Handle [[foo]].
2748879e06dSChris Lattner       if (NameEnd == StringRef::npos) {
275e8b8f1bcSEli Bendersky         // Handle variables that were defined earlier on the same line by
276e8b8f1bcSEli Bendersky         // emitting a backreference.
277e8b8f1bcSEli Bendersky         if (VariableDefs.find(Name) != VariableDefs.end()) {
278e8b8f1bcSEli Bendersky           unsigned VarParenNum = VariableDefs[Name];
279e8b8f1bcSEli Bendersky           if (VarParenNum < 1 || VarParenNum > 9) {
280e8b8f1bcSEli Bendersky             SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
281e8b8f1bcSEli Bendersky                             SourceMgr::DK_Error,
282e8b8f1bcSEli Bendersky                             "Can't back-reference more than 9 variables");
283e8b8f1bcSEli Bendersky             return true;
284e8b8f1bcSEli Bendersky           }
285e8b8f1bcSEli Bendersky           AddBackrefToRegEx(VarParenNum);
286e8b8f1bcSEli Bendersky         } else {
2878879e06dSChris Lattner           VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
288e8b8f1bcSEli Bendersky         }
2898879e06dSChris Lattner         continue;
2908879e06dSChris Lattner       }
2918879e06dSChris Lattner 
2928879e06dSChris Lattner       // Handle [[foo:.*]].
293e8b8f1bcSEli Bendersky       VariableDefs[Name] = CurParen;
2948879e06dSChris Lattner       RegExStr += '(';
2958879e06dSChris Lattner       ++CurParen;
2968879e06dSChris Lattner 
2978879e06dSChris Lattner       if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
2988879e06dSChris Lattner         return true;
2998879e06dSChris Lattner 
3008879e06dSChris Lattner       RegExStr += ')';
3018879e06dSChris Lattner     }
3028879e06dSChris Lattner 
3038879e06dSChris Lattner     // Handle fixed string matches.
3048879e06dSChris Lattner     // Find the end, which is the start of the next regex.
3058879e06dSChris Lattner     size_t FixedMatchEnd = PatternStr.find("{{");
3068879e06dSChris Lattner     FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
3078879e06dSChris Lattner     AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
3088879e06dSChris Lattner     PatternStr = PatternStr.substr(FixedMatchEnd);
309f08d2db9SChris Lattner   }
310f08d2db9SChris Lattner 
31174d50731SChris Lattner   return false;
31274d50731SChris Lattner }
31374d50731SChris Lattner 
3148879e06dSChris Lattner void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
315b16ab0c4SChris Lattner   // Add the characters from FixedStr to the regex, escaping as needed.  This
316b16ab0c4SChris Lattner   // avoids "leaning toothpicks" in common patterns.
317b16ab0c4SChris Lattner   for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
318b16ab0c4SChris Lattner     switch (FixedStr[i]) {
319b16ab0c4SChris Lattner     // These are the special characters matched in "p_ere_exp".
320b16ab0c4SChris Lattner     case '(':
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 '{':
3328879e06dSChris Lattner       TheStr += '\\';
333b16ab0c4SChris Lattner       // FALL THROUGH.
334b16ab0c4SChris Lattner     default:
3358879e06dSChris Lattner       TheStr += FixedStr[i];
336b16ab0c4SChris Lattner       break;
337b16ab0c4SChris Lattner     }
338b16ab0c4SChris Lattner   }
339b16ab0c4SChris Lattner }
340b16ab0c4SChris Lattner 
341e8b8f1bcSEli Bendersky bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
3428879e06dSChris Lattner                               SourceMgr &SM) {
343e8b8f1bcSEli Bendersky   Regex R(RS);
3448879e06dSChris Lattner   std::string Error;
3458879e06dSChris Lattner   if (!R.isValid(Error)) {
346e8b8f1bcSEli Bendersky     SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
34703b80a40SChris Lattner                     "invalid regex: " + Error);
3488879e06dSChris Lattner     return true;
3498879e06dSChris Lattner   }
3508879e06dSChris Lattner 
351e8b8f1bcSEli Bendersky   RegExStr += RS.str();
3528879e06dSChris Lattner   CurParen += R.getNumMatches();
3538879e06dSChris Lattner   return false;
3548879e06dSChris Lattner }
355b16ab0c4SChris Lattner 
356e8b8f1bcSEli Bendersky void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
357e8b8f1bcSEli Bendersky   assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
358e8b8f1bcSEli Bendersky   std::string Backref = std::string("\\") +
359e8b8f1bcSEli Bendersky                         std::string(1, '0' + BackrefNum);
360e8b8f1bcSEli Bendersky   RegExStr += Backref;
361e8b8f1bcSEli Bendersky }
362e8b8f1bcSEli Bendersky 
36392987fb3SAlexander Kornienko bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
36492987fb3SAlexander Kornienko   // The only supported expression is @LINE([\+-]\d+)?
36592987fb3SAlexander Kornienko   if (!Expr.startswith("@LINE"))
36692987fb3SAlexander Kornienko     return false;
36792987fb3SAlexander Kornienko   Expr = Expr.substr(StringRef("@LINE").size());
36892987fb3SAlexander Kornienko   int Offset = 0;
36992987fb3SAlexander Kornienko   if (!Expr.empty()) {
37092987fb3SAlexander Kornienko     if (Expr[0] == '+')
37192987fb3SAlexander Kornienko       Expr = Expr.substr(1);
37292987fb3SAlexander Kornienko     else if (Expr[0] != '-')
37392987fb3SAlexander Kornienko       return false;
37492987fb3SAlexander Kornienko     if (Expr.getAsInteger(10, Offset))
37592987fb3SAlexander Kornienko       return false;
37692987fb3SAlexander Kornienko   }
37792987fb3SAlexander Kornienko   Value = llvm::itostr(LineNumber + Offset);
37892987fb3SAlexander Kornienko   return true;
37992987fb3SAlexander Kornienko }
38092987fb3SAlexander Kornienko 
381f08d2db9SChris Lattner /// Match - Match the pattern string against the input buffer Buffer.  This
382f08d2db9SChris Lattner /// returns the position that is matched or npos if there is no match.  If
383f08d2db9SChris Lattner /// there is a match, the size of the matched string is returned in MatchLen.
3848879e06dSChris Lattner size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
3858879e06dSChris Lattner                       StringMap<StringRef> &VariableTable) const {
386eba55822SJakob Stoklund Olesen   // If this is the EOF pattern, match it immediately.
38738820972SMatt Arsenault   if (CheckTy == Check::CheckEOF) {
388eba55822SJakob Stoklund Olesen     MatchLen = 0;
389eba55822SJakob Stoklund Olesen     return Buffer.size();
390eba55822SJakob Stoklund Olesen   }
391eba55822SJakob Stoklund Olesen 
392221460e0SChris Lattner   // If this is a fixed string pattern, just match it now.
393221460e0SChris Lattner   if (!FixedStr.empty()) {
394221460e0SChris Lattner     MatchLen = FixedStr.size();
395221460e0SChris Lattner     return Buffer.find(FixedStr);
396221460e0SChris Lattner   }
397221460e0SChris Lattner 
398b16ab0c4SChris Lattner   // Regex match.
3998879e06dSChris Lattner 
4008879e06dSChris Lattner   // If there are variable uses, we need to create a temporary string with the
4018879e06dSChris Lattner   // actual value.
4028879e06dSChris Lattner   StringRef RegExToMatch = RegExStr;
4038879e06dSChris Lattner   std::string TmpStr;
4048879e06dSChris Lattner   if (!VariableUses.empty()) {
4058879e06dSChris Lattner     TmpStr = RegExStr;
4068879e06dSChris Lattner 
4078879e06dSChris Lattner     unsigned InsertOffset = 0;
4088879e06dSChris Lattner     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
40992987fb3SAlexander Kornienko       std::string Value;
41092987fb3SAlexander Kornienko 
41192987fb3SAlexander Kornienko       if (VariableUses[i].first[0] == '@') {
41292987fb3SAlexander Kornienko         if (!EvaluateExpression(VariableUses[i].first, Value))
41392987fb3SAlexander Kornienko           return StringRef::npos;
41492987fb3SAlexander Kornienko       } else {
415e0ef65abSDaniel Dunbar         StringMap<StringRef>::iterator it =
416e0ef65abSDaniel Dunbar           VariableTable.find(VariableUses[i].first);
417e0ef65abSDaniel Dunbar         // If the variable is undefined, return an error.
418e0ef65abSDaniel Dunbar         if (it == VariableTable.end())
419e0ef65abSDaniel Dunbar           return StringRef::npos;
420e0ef65abSDaniel Dunbar 
4218879e06dSChris Lattner         // Look up the value and escape it so that we can plop it into the regex.
422e0ef65abSDaniel Dunbar         AddFixedStringToRegEx(it->second, Value);
42392987fb3SAlexander Kornienko       }
4248879e06dSChris Lattner 
4258879e06dSChris Lattner       // Plop it into the regex at the adjusted offset.
4268879e06dSChris Lattner       TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
4278879e06dSChris Lattner                     Value.begin(), Value.end());
4288879e06dSChris Lattner       InsertOffset += Value.size();
4298879e06dSChris Lattner     }
4308879e06dSChris Lattner 
4318879e06dSChris Lattner     // Match the newly constructed regex.
4328879e06dSChris Lattner     RegExToMatch = TmpStr;
4338879e06dSChris Lattner   }
4348879e06dSChris Lattner 
4358879e06dSChris Lattner 
436b16ab0c4SChris Lattner   SmallVector<StringRef, 4> MatchInfo;
4378879e06dSChris Lattner   if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
438f08d2db9SChris Lattner     return StringRef::npos;
439b16ab0c4SChris Lattner 
440b16ab0c4SChris Lattner   // Successful regex match.
441b16ab0c4SChris Lattner   assert(!MatchInfo.empty() && "Didn't get any match");
442b16ab0c4SChris Lattner   StringRef FullMatch = MatchInfo[0];
443b16ab0c4SChris Lattner 
4448879e06dSChris Lattner   // If this defines any variables, remember their values.
445e8b8f1bcSEli Bendersky   for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
446e8b8f1bcSEli Bendersky                                                      E = VariableDefs.end();
447e8b8f1bcSEli Bendersky        I != E; ++I) {
448e8b8f1bcSEli Bendersky     assert(I->second < MatchInfo.size() && "Internal paren error");
449e8b8f1bcSEli Bendersky     VariableTable[I->first] = MatchInfo[I->second];
4500a4c44bdSChris Lattner   }
4510a4c44bdSChris Lattner 
452b16ab0c4SChris Lattner   MatchLen = FullMatch.size();
453b16ab0c4SChris Lattner   return FullMatch.data()-Buffer.data();
454f08d2db9SChris Lattner }
455f08d2db9SChris Lattner 
456fd29d886SDaniel Dunbar unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
457fd29d886SDaniel Dunbar                               const StringMap<StringRef> &VariableTable) const {
458fd29d886SDaniel Dunbar   // Just compute the number of matching characters. For regular expressions, we
459fd29d886SDaniel Dunbar   // just compare against the regex itself and hope for the best.
460fd29d886SDaniel Dunbar   //
461fd29d886SDaniel Dunbar   // FIXME: One easy improvement here is have the regex lib generate a single
462fd29d886SDaniel Dunbar   // example regular expression which matches, and use that as the example
463fd29d886SDaniel Dunbar   // string.
464fd29d886SDaniel Dunbar   StringRef ExampleString(FixedStr);
465fd29d886SDaniel Dunbar   if (ExampleString.empty())
466fd29d886SDaniel Dunbar     ExampleString = RegExStr;
467fd29d886SDaniel Dunbar 
468e9aa36c8SDaniel Dunbar   // Only compare up to the first line in the buffer, or the string size.
469e9aa36c8SDaniel Dunbar   StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
470e9aa36c8SDaniel Dunbar   BufferPrefix = BufferPrefix.split('\n').first;
471e9aa36c8SDaniel Dunbar   return BufferPrefix.edit_distance(ExampleString);
472fd29d886SDaniel Dunbar }
473fd29d886SDaniel Dunbar 
474e0ef65abSDaniel Dunbar void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
475e0ef65abSDaniel Dunbar                                const StringMap<StringRef> &VariableTable) const{
476e0ef65abSDaniel Dunbar   // If this was a regular expression using variables, print the current
477e0ef65abSDaniel Dunbar   // variable values.
478e0ef65abSDaniel Dunbar   if (!VariableUses.empty()) {
479e0ef65abSDaniel Dunbar     for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
480e0ef65abSDaniel Dunbar       SmallString<256> Msg;
481e0ef65abSDaniel Dunbar       raw_svector_ostream OS(Msg);
48292987fb3SAlexander Kornienko       StringRef Var = VariableUses[i].first;
48392987fb3SAlexander Kornienko       if (Var[0] == '@') {
48492987fb3SAlexander Kornienko         std::string Value;
48592987fb3SAlexander Kornienko         if (EvaluateExpression(Var, Value)) {
48692987fb3SAlexander Kornienko           OS << "with expression \"";
48792987fb3SAlexander Kornienko           OS.write_escaped(Var) << "\" equal to \"";
48892987fb3SAlexander Kornienko           OS.write_escaped(Value) << "\"";
48992987fb3SAlexander Kornienko         } else {
49092987fb3SAlexander Kornienko           OS << "uses incorrect expression \"";
49192987fb3SAlexander Kornienko           OS.write_escaped(Var) << "\"";
49292987fb3SAlexander Kornienko         }
49392987fb3SAlexander Kornienko       } else {
49492987fb3SAlexander Kornienko         StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
495e0ef65abSDaniel Dunbar 
496e0ef65abSDaniel Dunbar         // Check for undefined variable references.
497e0ef65abSDaniel Dunbar         if (it == VariableTable.end()) {
498e0ef65abSDaniel Dunbar           OS << "uses undefined variable \"";
49992987fb3SAlexander Kornienko           OS.write_escaped(Var) << "\"";
500e0ef65abSDaniel Dunbar         } else {
501e0ef65abSDaniel Dunbar           OS << "with variable \"";
502e0ef65abSDaniel Dunbar           OS.write_escaped(Var) << "\" equal to \"";
503e0ef65abSDaniel Dunbar           OS.write_escaped(it->second) << "\"";
504e0ef65abSDaniel Dunbar         }
50592987fb3SAlexander Kornienko       }
506e0ef65abSDaniel Dunbar 
50703b80a40SChris Lattner       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
50803b80a40SChris Lattner                       OS.str());
509e0ef65abSDaniel Dunbar     }
510e0ef65abSDaniel Dunbar   }
511fd29d886SDaniel Dunbar 
512fd29d886SDaniel Dunbar   // Attempt to find the closest/best fuzzy match.  Usually an error happens
513fd29d886SDaniel Dunbar   // because some string in the output didn't exactly match. In these cases, we
514fd29d886SDaniel Dunbar   // would like to show the user a best guess at what "should have" matched, to
515fd29d886SDaniel Dunbar   // save them having to actually check the input manually.
516fd29d886SDaniel Dunbar   size_t NumLinesForward = 0;
517fd29d886SDaniel Dunbar   size_t Best = StringRef::npos;
518fd29d886SDaniel Dunbar   double BestQuality = 0;
519fd29d886SDaniel Dunbar 
520fd29d886SDaniel Dunbar   // Use an arbitrary 4k limit on how far we will search.
5212bf486ebSDan Gohman   for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
522fd29d886SDaniel Dunbar     if (Buffer[i] == '\n')
523fd29d886SDaniel Dunbar       ++NumLinesForward;
524fd29d886SDaniel Dunbar 
525df22bbf7SDan Gohman     // Patterns have leading whitespace stripped, so skip whitespace when
526df22bbf7SDan Gohman     // looking for something which looks like a pattern.
527df22bbf7SDan Gohman     if (Buffer[i] == ' ' || Buffer[i] == '\t')
528df22bbf7SDan Gohman       continue;
529df22bbf7SDan Gohman 
530fd29d886SDaniel Dunbar     // Compute the "quality" of this match as an arbitrary combination of the
531fd29d886SDaniel Dunbar     // match distance and the number of lines skipped to get to this match.
532fd29d886SDaniel Dunbar     unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
533fd29d886SDaniel Dunbar     double Quality = Distance + (NumLinesForward / 100.);
534fd29d886SDaniel Dunbar 
535fd29d886SDaniel Dunbar     if (Quality < BestQuality || Best == StringRef::npos) {
536fd29d886SDaniel Dunbar       Best = i;
537fd29d886SDaniel Dunbar       BestQuality = Quality;
538fd29d886SDaniel Dunbar     }
539fd29d886SDaniel Dunbar   }
540fd29d886SDaniel Dunbar 
541fd29d886SDaniel Dunbar   // Print the "possible intended match here" line if we found something
542c069cc8eSDaniel Dunbar   // reasonable and not equal to what we showed in the "scanning from here"
543c069cc8eSDaniel Dunbar   // line.
544c069cc8eSDaniel Dunbar   if (Best && Best != StringRef::npos && BestQuality < 50) {
545fd29d886SDaniel Dunbar       SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
54603b80a40SChris Lattner                       SourceMgr::DK_Note, "possible intended match here");
547fd29d886SDaniel Dunbar 
548fd29d886SDaniel Dunbar     // FIXME: If we wanted to be really friendly we would show why the match
549fd29d886SDaniel Dunbar     // failed, as it can be hard to spot simple one character differences.
550fd29d886SDaniel Dunbar   }
551e0ef65abSDaniel Dunbar }
55274d50731SChris Lattner 
553061d2baaSEli Bendersky size_t Pattern::FindRegexVarEnd(StringRef Str) {
554061d2baaSEli Bendersky   // Offset keeps track of the current offset within the input Str
555061d2baaSEli Bendersky   size_t Offset = 0;
556061d2baaSEli Bendersky   // [...] Nesting depth
557061d2baaSEli Bendersky   size_t BracketDepth = 0;
558061d2baaSEli Bendersky 
559061d2baaSEli Bendersky   while (!Str.empty()) {
560061d2baaSEli Bendersky     if (Str.startswith("]]") && BracketDepth == 0)
561061d2baaSEli Bendersky       return Offset;
562061d2baaSEli Bendersky     if (Str[0] == '\\') {
563061d2baaSEli Bendersky       // Backslash escapes the next char within regexes, so skip them both.
564061d2baaSEli Bendersky       Str = Str.substr(2);
565061d2baaSEli Bendersky       Offset += 2;
566061d2baaSEli Bendersky     } else {
567061d2baaSEli Bendersky       switch (Str[0]) {
568061d2baaSEli Bendersky         default:
569061d2baaSEli Bendersky           break;
570061d2baaSEli Bendersky         case '[':
571061d2baaSEli Bendersky           BracketDepth++;
572061d2baaSEli Bendersky           break;
573061d2baaSEli Bendersky         case ']':
574061d2baaSEli Bendersky           assert(BracketDepth > 0 && "Invalid regex");
575061d2baaSEli Bendersky           BracketDepth--;
576061d2baaSEli Bendersky           break;
577061d2baaSEli Bendersky       }
578061d2baaSEli Bendersky       Str = Str.substr(1);
579061d2baaSEli Bendersky       Offset++;
580061d2baaSEli Bendersky     }
581061d2baaSEli Bendersky   }
582061d2baaSEli Bendersky 
583061d2baaSEli Bendersky   return StringRef::npos;
584061d2baaSEli Bendersky }
585061d2baaSEli Bendersky 
586061d2baaSEli Bendersky 
58774d50731SChris Lattner //===----------------------------------------------------------------------===//
58874d50731SChris Lattner // Check Strings.
58974d50731SChris Lattner //===----------------------------------------------------------------------===//
5903b40b445SChris Lattner 
5913b40b445SChris Lattner /// CheckString - This is a check that we found in the input file.
5923b40b445SChris Lattner struct CheckString {
5933b40b445SChris Lattner   /// Pat - The pattern to match.
5943b40b445SChris Lattner   Pattern Pat;
59526cccfe1SChris Lattner 
59626cccfe1SChris Lattner   /// Loc - The location in the match file that the check string was specified.
59726cccfe1SChris Lattner   SMLoc Loc;
59826cccfe1SChris Lattner 
59938820972SMatt Arsenault   /// CheckTy - Specify what kind of check this is. e.g. CHECK-NEXT: directive,
60038820972SMatt Arsenault   /// as opposed to a CHECK: directive.
60138820972SMatt Arsenault   Check::CheckType CheckTy;
602f8bd2e5bSStephen Lin 
60391a1b2c9SMichael Liao   /// DagNotStrings - These are all of the strings that are disallowed from
604236d2d5eSChris Lattner   /// occurring between this match string and the previous one (or start of
605236d2d5eSChris Lattner   /// file).
60691a1b2c9SMichael Liao   std::vector<Pattern> DagNotStrings;
607236d2d5eSChris Lattner 
60838820972SMatt Arsenault   CheckString(const Pattern &P, SMLoc L, Check::CheckType Ty)
60938820972SMatt Arsenault     : Pat(P), Loc(L), CheckTy(Ty) {}
610dcc7d48dSMichael Liao 
61191a1b2c9SMichael Liao   /// Check - Match check string and its "not strings" and/or "dag strings".
612f8bd2e5bSStephen Lin   size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabel,
613f8bd2e5bSStephen Lin                size_t &MatchLen, StringMap<StringRef> &VariableTable) const;
614dcc7d48dSMichael Liao 
615dcc7d48dSMichael Liao   /// CheckNext - Verify there is a single line in the given buffer.
616dcc7d48dSMichael Liao   bool CheckNext(const SourceMgr &SM, StringRef Buffer) const;
617dcc7d48dSMichael Liao 
618dcc7d48dSMichael Liao   /// CheckNot - Verify there's no "not strings" in the given buffer.
619dcc7d48dSMichael Liao   bool CheckNot(const SourceMgr &SM, StringRef Buffer,
62091a1b2c9SMichael Liao                 const std::vector<const Pattern *> &NotStrings,
62191a1b2c9SMichael Liao                 StringMap<StringRef> &VariableTable) const;
62291a1b2c9SMichael Liao 
62391a1b2c9SMichael Liao   /// CheckDag - Match "dag strings" and their mixed "not strings".
62491a1b2c9SMichael Liao   size_t CheckDag(const SourceMgr &SM, StringRef Buffer,
62591a1b2c9SMichael Liao                   std::vector<const Pattern *> &NotStrings,
626dcc7d48dSMichael Liao                   StringMap<StringRef> &VariableTable) const;
62726cccfe1SChris Lattner };
62826cccfe1SChris Lattner 
6295ea04c38SGuy Benyei /// Canonicalize whitespaces in the input file. Line endings are replaced
6305ea04c38SGuy Benyei /// with UNIX-style '\n'.
6315ea04c38SGuy Benyei ///
6325ea04c38SGuy Benyei /// \param PreserveHorizontal Don't squash consecutive horizontal whitespace
6335ea04c38SGuy Benyei /// characters to a single space.
6345ea04c38SGuy Benyei static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB,
6355ea04c38SGuy Benyei                                            bool PreserveHorizontal) {
6360e45d24aSChris Lattner   SmallString<128> NewFile;
637a2f8fc5aSChris Lattner   NewFile.reserve(MB->getBufferSize());
638a2f8fc5aSChris Lattner 
639a2f8fc5aSChris Lattner   for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
640a2f8fc5aSChris Lattner        Ptr != End; ++Ptr) {
641fd781bf0SNAKAMURA Takumi     // Eliminate trailing dosish \r.
642fd781bf0SNAKAMURA Takumi     if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
643fd781bf0SNAKAMURA Takumi       continue;
644fd781bf0SNAKAMURA Takumi     }
645fd781bf0SNAKAMURA Takumi 
6465ea04c38SGuy Benyei     // If current char is not a horizontal whitespace or if horizontal
6475ea04c38SGuy Benyei     // whitespace canonicalization is disabled, dump it to output as is.
6485ea04c38SGuy Benyei     if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) {
649a2f8fc5aSChris Lattner       NewFile.push_back(*Ptr);
650a2f8fc5aSChris Lattner       continue;
651a2f8fc5aSChris Lattner     }
652a2f8fc5aSChris Lattner 
653a2f8fc5aSChris Lattner     // Otherwise, add one space and advance over neighboring space.
654a2f8fc5aSChris Lattner     NewFile.push_back(' ');
655a2f8fc5aSChris Lattner     while (Ptr+1 != End &&
656a2f8fc5aSChris Lattner            (Ptr[1] == ' ' || Ptr[1] == '\t'))
657a2f8fc5aSChris Lattner       ++Ptr;
658a2f8fc5aSChris Lattner   }
659a2f8fc5aSChris Lattner 
660a2f8fc5aSChris Lattner   // Free the old buffer and return a new one.
661a2f8fc5aSChris Lattner   MemoryBuffer *MB2 =
6620e45d24aSChris Lattner     MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
663a2f8fc5aSChris Lattner 
664a2f8fc5aSChris Lattner   delete MB;
665a2f8fc5aSChris Lattner   return MB2;
666a2f8fc5aSChris Lattner }
667a2f8fc5aSChris Lattner 
66838820972SMatt Arsenault static bool IsPartOfWord(char c) {
66938820972SMatt Arsenault   return (isalnum(c) || c == '-' || c == '_');
67038820972SMatt Arsenault }
67138820972SMatt Arsenault 
67238820972SMatt Arsenault static Check::CheckType FindCheckType(StringRef &Buffer, StringRef Prefix) {
673*c4d2d471SMatt Arsenault   char NextChar = Buffer[Prefix.size()];
67438820972SMatt Arsenault 
67538820972SMatt Arsenault   // Verify that the : is present after the prefix.
67638820972SMatt Arsenault   if (NextChar == ':') {
677*c4d2d471SMatt Arsenault     Buffer = Buffer.substr(Prefix.size() + 1);
67838820972SMatt Arsenault     return Check::CheckPlain;
67938820972SMatt Arsenault   }
68038820972SMatt Arsenault 
68138820972SMatt Arsenault   if (NextChar != '-') {
68238820972SMatt Arsenault     Buffer = Buffer.drop_front(1);
68338820972SMatt Arsenault     return Check::CheckNone;
68438820972SMatt Arsenault   }
68538820972SMatt Arsenault 
686*c4d2d471SMatt Arsenault   StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
68738820972SMatt Arsenault   if (Rest.startswith("NEXT:")) {
68838820972SMatt Arsenault     Buffer = Rest.drop_front(sizeof("NEXT:") - 1);
68938820972SMatt Arsenault     return Check::CheckNext;
69038820972SMatt Arsenault   }
69138820972SMatt Arsenault 
69238820972SMatt Arsenault   if (Rest.startswith("NOT:")) {
69338820972SMatt Arsenault     Buffer = Rest.drop_front(sizeof("NOT:") - 1);
69438820972SMatt Arsenault     return Check::CheckNot;
69538820972SMatt Arsenault   }
69638820972SMatt Arsenault 
69738820972SMatt Arsenault   if (Rest.startswith("DAG:")) {
69838820972SMatt Arsenault     Buffer = Rest.drop_front(sizeof("DAG:") - 1);
69938820972SMatt Arsenault     return Check::CheckDAG;
70038820972SMatt Arsenault   }
70138820972SMatt Arsenault 
70238820972SMatt Arsenault   if (Rest.startswith("LABEL:")) {
70338820972SMatt Arsenault     Buffer = Rest.drop_front(sizeof("LABEL:") - 1);
70438820972SMatt Arsenault     return Check::CheckLabel;
70538820972SMatt Arsenault   }
70638820972SMatt Arsenault 
70738820972SMatt Arsenault   Buffer = Buffer.drop_front(1);
70838820972SMatt Arsenault   return Check::CheckNone;
70938820972SMatt Arsenault }
710ee3c74fbSChris Lattner 
711ee3c74fbSChris Lattner /// ReadCheckFile - Read the check file, which specifies the sequence of
712ee3c74fbSChris Lattner /// expected strings.  The strings are added to the CheckStrings vector.
71343d50d4aSEli Bendersky /// Returns true in case of an error, false otherwise.
714ee3c74fbSChris Lattner static bool ReadCheckFile(SourceMgr &SM,
71526cccfe1SChris Lattner                           std::vector<CheckString> &CheckStrings) {
71639a0ffc3SMichael J. Spencer   OwningPtr<MemoryBuffer> File;
71739a0ffc3SMichael J. Spencer   if (error_code ec =
7188c811724SRafael Espindola         MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) {
719ee3c74fbSChris Lattner     errs() << "Could not open check file '" << CheckFilename << "': "
7207b6fef82SMichael J. Spencer            << ec.message() << '\n';
721ee3c74fbSChris Lattner     return true;
722ee3c74fbSChris Lattner   }
723a2f8fc5aSChris Lattner 
724a2f8fc5aSChris Lattner   // If we want to canonicalize whitespace, strip excess whitespace from the
7255ea04c38SGuy Benyei   // buffer containing the CHECK lines. Remove DOS style line endings.
726e963d660SBenjamin Kramer   MemoryBuffer *F =
727e963d660SBenjamin Kramer     CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
728a2f8fc5aSChris Lattner 
729ee3c74fbSChris Lattner   SM.AddNewSourceBuffer(F, SMLoc());
730ee3c74fbSChris Lattner 
73110f10cedSChris Lattner   // Find all instances of CheckPrefix followed by : in the file.
732caa5fc0cSChris Lattner   StringRef Buffer = F->getBuffer();
73391a1b2c9SMichael Liao   std::vector<Pattern> DagNotMatches;
734236d2d5eSChris Lattner 
73543d50d4aSEli Bendersky   // LineNumber keeps track of the line on which CheckPrefix instances are
73643d50d4aSEli Bendersky   // found.
73792987fb3SAlexander Kornienko   unsigned LineNumber = 1;
73892987fb3SAlexander Kornienko 
739ee3c74fbSChris Lattner   while (1) {
740ee3c74fbSChris Lattner     // See if Prefix occurs in the memory buffer.
74192987fb3SAlexander Kornienko     size_t PrefixLoc = Buffer.find(CheckPrefix);
742ee3c74fbSChris Lattner     // If we didn't find a match, we're done.
74392987fb3SAlexander Kornienko     if (PrefixLoc == StringRef::npos)
744ee3c74fbSChris Lattner       break;
745ee3c74fbSChris Lattner 
74692987fb3SAlexander Kornienko     LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
74792987fb3SAlexander Kornienko 
748c2735158SRui Ueyama     // Keep the charcter before our prefix so we can validate that we have
749c2735158SRui Ueyama     // found our prefix, and account for cases when PrefixLoc is 0.
750c2735158SRui Ueyama     Buffer = Buffer.substr(std::min(PrefixLoc-1, PrefixLoc));
75192987fb3SAlexander Kornienko 
752c2735158SRui Ueyama     const char *CheckPrefixStart = Buffer.data() + (PrefixLoc == 0 ? 0 : 1);
753da108b4eSChris Lattner 
754c2735158SRui Ueyama     // Make sure we have actually found our prefix, and not a word containing
755c2735158SRui Ueyama     // our prefix.
75638820972SMatt Arsenault     if (PrefixLoc != 0 && IsPartOfWord(Buffer[0])) {
757c2735158SRui Ueyama       Buffer = Buffer.substr(CheckPrefix.size());
758c2735158SRui Ueyama       continue;
759c2735158SRui Ueyama     }
760c2735158SRui Ueyama 
76138820972SMatt Arsenault     // When we find a check prefix, keep track of what kind of type of CHECK we
76238820972SMatt Arsenault     // have.
76338820972SMatt Arsenault     Check::CheckType CheckTy = FindCheckType(Buffer, CheckPrefix);
76438820972SMatt Arsenault     if (CheckTy == Check::CheckNone)
76510f10cedSChris Lattner       continue;
76610f10cedSChris Lattner 
76738820972SMatt Arsenault     // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
76838820972SMatt Arsenault     // leading and trailing whitespace.
769236d2d5eSChris Lattner     Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
770ee3c74fbSChris Lattner 
771ee3c74fbSChris Lattner     // Scan ahead to the end of line.
772caa5fc0cSChris Lattner     size_t EOL = Buffer.find_first_of("\n\r");
773ee3c74fbSChris Lattner 
774838fb09aSDan Gohman     // Remember the location of the start of the pattern, for diagnostics.
775838fb09aSDan Gohman     SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
776838fb09aSDan Gohman 
77774d50731SChris Lattner     // Parse the pattern.
77838820972SMatt Arsenault     Pattern P(CheckTy);
77992987fb3SAlexander Kornienko     if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
780ee3c74fbSChris Lattner       return true;
781ee3c74fbSChris Lattner 
782f8bd2e5bSStephen Lin     // Verify that CHECK-LABEL lines do not define or use variables
78338820972SMatt Arsenault     if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
784f8bd2e5bSStephen Lin       SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
785f8bd2e5bSStephen Lin                       SourceMgr::DK_Error,
786f8bd2e5bSStephen Lin                       "found '"+CheckPrefix+"-LABEL:' with variable definition"
787398b32a2SStephen Lin                       " or use");
788f8bd2e5bSStephen Lin       return true;
789f8bd2e5bSStephen Lin     }
790f8bd2e5bSStephen Lin 
791236d2d5eSChris Lattner     Buffer = Buffer.substr(EOL);
79274d50731SChris Lattner 
793da108b4eSChris Lattner     // Verify that CHECK-NEXT lines have at least one CHECK line before them.
79438820972SMatt Arsenault     if ((CheckTy == Check::CheckNext) && CheckStrings.empty()) {
795da108b4eSChris Lattner       SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
79603b80a40SChris Lattner                       SourceMgr::DK_Error,
797da108b4eSChris Lattner                       "found '"+CheckPrefix+"-NEXT:' without previous '"+
79803b80a40SChris Lattner                       CheckPrefix+ ": line");
799da108b4eSChris Lattner       return true;
800da108b4eSChris Lattner     }
801da108b4eSChris Lattner 
80291a1b2c9SMichael Liao     // Handle CHECK-DAG/-NOT.
80338820972SMatt Arsenault     if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
80491a1b2c9SMichael Liao       DagNotMatches.push_back(P);
80574d50731SChris Lattner       continue;
80674d50731SChris Lattner     }
80774d50731SChris Lattner 
808ee3c74fbSChris Lattner     // Okay, add the string we captured to the output vector and move on.
8093b40b445SChris Lattner     CheckStrings.push_back(CheckString(P,
810838fb09aSDan Gohman                                        PatternLoc,
81138820972SMatt Arsenault                                        CheckTy));
81291a1b2c9SMichael Liao     std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
813ee3c74fbSChris Lattner   }
814ee3c74fbSChris Lattner 
81591a1b2c9SMichael Liao   // Add an EOF pattern for any trailing CHECK-DAG/-NOTs.
81691a1b2c9SMichael Liao   if (!DagNotMatches.empty()) {
81738820972SMatt Arsenault     CheckStrings.push_back(CheckString(Pattern(Check::CheckEOF),
818eba55822SJakob Stoklund Olesen                                        SMLoc::getFromPointer(Buffer.data()),
81938820972SMatt Arsenault                                        Check::CheckEOF));
82091a1b2c9SMichael Liao     std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
821eba55822SJakob Stoklund Olesen   }
822eba55822SJakob Stoklund Olesen 
823ee3c74fbSChris Lattner   if (CheckStrings.empty()) {
82410f10cedSChris Lattner     errs() << "error: no check strings found with prefix '" << CheckPrefix
82510f10cedSChris Lattner            << ":'\n";
826ee3c74fbSChris Lattner     return true;
827ee3c74fbSChris Lattner   }
828ee3c74fbSChris Lattner 
829ee3c74fbSChris Lattner   return false;
830ee3c74fbSChris Lattner }
831ee3c74fbSChris Lattner 
83291a1b2c9SMichael Liao static void PrintCheckFailed(const SourceMgr &SM, const SMLoc &Loc,
83391a1b2c9SMichael Liao                              const Pattern &Pat, StringRef Buffer,
834e0ef65abSDaniel Dunbar                              StringMap<StringRef> &VariableTable) {
835da108b4eSChris Lattner   // Otherwise, we have an error, emit an error message.
83691a1b2c9SMichael Liao   SM.PrintMessage(Loc, SourceMgr::DK_Error,
83703b80a40SChris Lattner                   "expected string not found in input");
838da108b4eSChris Lattner 
839da108b4eSChris Lattner   // Print the "scanning from here" line.  If the current position is at the
840da108b4eSChris Lattner   // end of a line, advance to the start of the next line.
841caa5fc0cSChris Lattner   Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
842da108b4eSChris Lattner 
84303b80a40SChris Lattner   SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
84403b80a40SChris Lattner                   "scanning from here");
845e0ef65abSDaniel Dunbar 
846e0ef65abSDaniel Dunbar   // Allow the pattern to print additional information if desired.
84791a1b2c9SMichael Liao   Pat.PrintFailureInfo(SM, Buffer, VariableTable);
84891a1b2c9SMichael Liao }
84991a1b2c9SMichael Liao 
85091a1b2c9SMichael Liao static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
85191a1b2c9SMichael Liao                              StringRef Buffer,
85291a1b2c9SMichael Liao                              StringMap<StringRef> &VariableTable) {
85391a1b2c9SMichael Liao   PrintCheckFailed(SM, CheckStr.Loc, CheckStr.Pat, Buffer, VariableTable);
854da108b4eSChris Lattner }
855da108b4eSChris Lattner 
85637183584SChris Lattner /// CountNumNewlinesBetween - Count the number of newlines in the specified
85737183584SChris Lattner /// range.
85837183584SChris Lattner static unsigned CountNumNewlinesBetween(StringRef Range) {
859da108b4eSChris Lattner   unsigned NumNewLines = 0;
86037183584SChris Lattner   while (1) {
861da108b4eSChris Lattner     // Scan for newline.
86237183584SChris Lattner     Range = Range.substr(Range.find_first_of("\n\r"));
86337183584SChris Lattner     if (Range.empty()) return NumNewLines;
864da108b4eSChris Lattner 
865da108b4eSChris Lattner     ++NumNewLines;
866da108b4eSChris Lattner 
867da108b4eSChris Lattner     // Handle \n\r and \r\n as a single newline.
86837183584SChris Lattner     if (Range.size() > 1 &&
86937183584SChris Lattner         (Range[1] == '\n' || Range[1] == '\r') &&
87037183584SChris Lattner         (Range[0] != Range[1]))
87137183584SChris Lattner       Range = Range.substr(1);
87237183584SChris Lattner     Range = Range.substr(1);
873da108b4eSChris Lattner   }
874da108b4eSChris Lattner }
875da108b4eSChris Lattner 
876dcc7d48dSMichael Liao size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer,
877f8bd2e5bSStephen Lin                           bool IsLabel, size_t &MatchLen,
878dcc7d48dSMichael Liao                           StringMap<StringRef> &VariableTable) const {
87991a1b2c9SMichael Liao   size_t LastPos = 0;
88091a1b2c9SMichael Liao   std::vector<const Pattern *> NotStrings;
88191a1b2c9SMichael Liao 
882f8bd2e5bSStephen Lin   if (!IsLabel) {
88391a1b2c9SMichael Liao     // Match "dag strings" (with mixed "not strings" if any).
88491a1b2c9SMichael Liao     LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable);
88591a1b2c9SMichael Liao     if (LastPos == StringRef::npos)
88691a1b2c9SMichael Liao       return StringRef::npos;
887f8bd2e5bSStephen Lin   }
88891a1b2c9SMichael Liao 
88991a1b2c9SMichael Liao   // Match itself from the last position after matching CHECK-DAG.
89091a1b2c9SMichael Liao   StringRef MatchBuffer = Buffer.substr(LastPos);
89191a1b2c9SMichael Liao   size_t MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
892dcc7d48dSMichael Liao   if (MatchPos == StringRef::npos) {
89391a1b2c9SMichael Liao     PrintCheckFailed(SM, *this, MatchBuffer, VariableTable);
894dcc7d48dSMichael Liao     return StringRef::npos;
895dcc7d48dSMichael Liao   }
89691a1b2c9SMichael Liao   MatchPos += LastPos;
897dcc7d48dSMichael Liao 
898f8bd2e5bSStephen Lin   if (!IsLabel) {
89991a1b2c9SMichael Liao     StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
900dcc7d48dSMichael Liao 
901dcc7d48dSMichael Liao     // If this check is a "CHECK-NEXT", verify that the previous match was on
902dcc7d48dSMichael Liao     // the previous line (i.e. that there is one newline between them).
903dcc7d48dSMichael Liao     if (CheckNext(SM, SkippedRegion))
904dcc7d48dSMichael Liao       return StringRef::npos;
905dcc7d48dSMichael Liao 
906dcc7d48dSMichael Liao     // If this match had "not strings", verify that they don't exist in the
907dcc7d48dSMichael Liao     // skipped region.
90891a1b2c9SMichael Liao     if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
909dcc7d48dSMichael Liao       return StringRef::npos;
910f8bd2e5bSStephen Lin   }
911dcc7d48dSMichael Liao 
912dcc7d48dSMichael Liao   return MatchPos;
913dcc7d48dSMichael Liao }
914dcc7d48dSMichael Liao 
915dcc7d48dSMichael Liao bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
91638820972SMatt Arsenault   if (CheckTy != Check::CheckNext)
917dcc7d48dSMichael Liao     return false;
918dcc7d48dSMichael Liao 
919dcc7d48dSMichael Liao   // Count the number of newlines between the previous match and this one.
920dcc7d48dSMichael Liao   assert(Buffer.data() !=
921dcc7d48dSMichael Liao          SM.getMemoryBuffer(
922dcc7d48dSMichael Liao            SM.FindBufferContainingLoc(
923dcc7d48dSMichael Liao              SMLoc::getFromPointer(Buffer.data())))->getBufferStart() &&
924dcc7d48dSMichael Liao          "CHECK-NEXT can't be the first check in a file");
925dcc7d48dSMichael Liao 
926dcc7d48dSMichael Liao   unsigned NumNewLines = CountNumNewlinesBetween(Buffer);
927dcc7d48dSMichael Liao 
928dcc7d48dSMichael Liao   if (NumNewLines == 0) {
929dcc7d48dSMichael Liao     SM.PrintMessage(Loc, SourceMgr::DK_Error, CheckPrefix+
930dcc7d48dSMichael Liao                     "-NEXT: is on the same line as previous match");
931dcc7d48dSMichael Liao     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
932dcc7d48dSMichael Liao                     SourceMgr::DK_Note, "'next' match was here");
933dcc7d48dSMichael Liao     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
934dcc7d48dSMichael Liao                     "previous match ended here");
935dcc7d48dSMichael Liao     return true;
936dcc7d48dSMichael Liao   }
937dcc7d48dSMichael Liao 
938dcc7d48dSMichael Liao   if (NumNewLines != 1) {
939dcc7d48dSMichael Liao     SM.PrintMessage(Loc, SourceMgr::DK_Error, CheckPrefix+
940dcc7d48dSMichael Liao                     "-NEXT: is not on the line after the previous match");
941dcc7d48dSMichael Liao     SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
942dcc7d48dSMichael Liao                     SourceMgr::DK_Note, "'next' match was here");
943dcc7d48dSMichael Liao     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
944dcc7d48dSMichael Liao                     "previous match ended here");
945dcc7d48dSMichael Liao     return true;
946dcc7d48dSMichael Liao   }
947dcc7d48dSMichael Liao 
948dcc7d48dSMichael Liao   return false;
949dcc7d48dSMichael Liao }
950dcc7d48dSMichael Liao 
951dcc7d48dSMichael Liao bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer,
95291a1b2c9SMichael Liao                            const std::vector<const Pattern *> &NotStrings,
953dcc7d48dSMichael Liao                            StringMap<StringRef> &VariableTable) const {
954dcc7d48dSMichael Liao   for (unsigned ChunkNo = 0, e = NotStrings.size();
955dcc7d48dSMichael Liao        ChunkNo != e; ++ChunkNo) {
95691a1b2c9SMichael Liao     const Pattern *Pat = NotStrings[ChunkNo];
95738820972SMatt Arsenault     assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
95891a1b2c9SMichael Liao 
959dcc7d48dSMichael Liao     size_t MatchLen = 0;
96091a1b2c9SMichael Liao     size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);
961dcc7d48dSMichael Liao 
962dcc7d48dSMichael Liao     if (Pos == StringRef::npos) continue;
963dcc7d48dSMichael Liao 
964dcc7d48dSMichael Liao     SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos),
965dcc7d48dSMichael Liao                     SourceMgr::DK_Error,
966dcc7d48dSMichael Liao                     CheckPrefix+"-NOT: string occurred!");
96791a1b2c9SMichael Liao     SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note,
968dcc7d48dSMichael Liao                     CheckPrefix+"-NOT: pattern specified here");
969dcc7d48dSMichael Liao     return true;
970dcc7d48dSMichael Liao   }
971dcc7d48dSMichael Liao 
972dcc7d48dSMichael Liao   return false;
973dcc7d48dSMichael Liao }
974dcc7d48dSMichael Liao 
97591a1b2c9SMichael Liao size_t CheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
97691a1b2c9SMichael Liao                              std::vector<const Pattern *> &NotStrings,
97791a1b2c9SMichael Liao                              StringMap<StringRef> &VariableTable) const {
97891a1b2c9SMichael Liao   if (DagNotStrings.empty())
97991a1b2c9SMichael Liao     return 0;
98091a1b2c9SMichael Liao 
98191a1b2c9SMichael Liao   size_t LastPos = 0;
98291a1b2c9SMichael Liao   size_t StartPos = LastPos;
98391a1b2c9SMichael Liao 
98491a1b2c9SMichael Liao   for (unsigned ChunkNo = 0, e = DagNotStrings.size();
98591a1b2c9SMichael Liao        ChunkNo != e; ++ChunkNo) {
98691a1b2c9SMichael Liao     const Pattern &Pat = DagNotStrings[ChunkNo];
98791a1b2c9SMichael Liao 
98838820972SMatt Arsenault     assert((Pat.getCheckTy() == Check::CheckDAG ||
98938820972SMatt Arsenault             Pat.getCheckTy() == Check::CheckNot) &&
99091a1b2c9SMichael Liao            "Invalid CHECK-DAG or CHECK-NOT!");
99191a1b2c9SMichael Liao 
99238820972SMatt Arsenault     if (Pat.getCheckTy() == Check::CheckNot) {
99391a1b2c9SMichael Liao       NotStrings.push_back(&Pat);
99491a1b2c9SMichael Liao       continue;
99591a1b2c9SMichael Liao     }
99691a1b2c9SMichael Liao 
99738820972SMatt Arsenault     assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
99891a1b2c9SMichael Liao 
99991a1b2c9SMichael Liao     size_t MatchLen = 0, MatchPos;
100091a1b2c9SMichael Liao 
100191a1b2c9SMichael Liao     // CHECK-DAG always matches from the start.
100291a1b2c9SMichael Liao     StringRef MatchBuffer = Buffer.substr(StartPos);
100391a1b2c9SMichael Liao     MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
100491a1b2c9SMichael Liao     // With a group of CHECK-DAGs, a single mismatching means the match on
100591a1b2c9SMichael Liao     // that group of CHECK-DAGs fails immediately.
100691a1b2c9SMichael Liao     if (MatchPos == StringRef::npos) {
100791a1b2c9SMichael Liao       PrintCheckFailed(SM, Pat.getLoc(), Pat, MatchBuffer, VariableTable);
100891a1b2c9SMichael Liao       return StringRef::npos;
100991a1b2c9SMichael Liao     }
101091a1b2c9SMichael Liao     // Re-calc it as the offset relative to the start of the original string.
101191a1b2c9SMichael Liao     MatchPos += StartPos;
101291a1b2c9SMichael Liao 
101391a1b2c9SMichael Liao     if (!NotStrings.empty()) {
101491a1b2c9SMichael Liao       if (MatchPos < LastPos) {
101591a1b2c9SMichael Liao         // Reordered?
101691a1b2c9SMichael Liao         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + MatchPos),
101791a1b2c9SMichael Liao                         SourceMgr::DK_Error,
101891a1b2c9SMichael Liao                         CheckPrefix+"-DAG: found a match of CHECK-DAG"
101991a1b2c9SMichael Liao                         " reordering across a CHECK-NOT");
102091a1b2c9SMichael Liao         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + LastPos),
102191a1b2c9SMichael Liao                         SourceMgr::DK_Note,
102291a1b2c9SMichael Liao                         CheckPrefix+"-DAG: the farthest match of CHECK-DAG"
102391a1b2c9SMichael Liao                         " is found here");
102491a1b2c9SMichael Liao         SM.PrintMessage(NotStrings[0]->getLoc(), SourceMgr::DK_Note,
102591a1b2c9SMichael Liao                         CheckPrefix+"-NOT: the crossed pattern specified"
102691a1b2c9SMichael Liao                         " here");
102791a1b2c9SMichael Liao         SM.PrintMessage(Pat.getLoc(), SourceMgr::DK_Note,
102891a1b2c9SMichael Liao                         CheckPrefix+"-DAG: the reordered pattern specified"
102991a1b2c9SMichael Liao                         " here");
103091a1b2c9SMichael Liao         return StringRef::npos;
103191a1b2c9SMichael Liao       }
103291a1b2c9SMichael Liao       // All subsequent CHECK-DAGs should be matched from the farthest
103391a1b2c9SMichael Liao       // position of all precedent CHECK-DAGs (including this one.)
103491a1b2c9SMichael Liao       StartPos = LastPos;
103591a1b2c9SMichael Liao       // If there's CHECK-NOTs between two CHECK-DAGs or from CHECK to
103691a1b2c9SMichael Liao       // CHECK-DAG, verify that there's no 'not' strings occurred in that
103791a1b2c9SMichael Liao       // region.
103891a1b2c9SMichael Liao       StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1039cf708c32STim Northover       if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
104091a1b2c9SMichael Liao         return StringRef::npos;
104191a1b2c9SMichael Liao       // Clear "not strings".
104291a1b2c9SMichael Liao       NotStrings.clear();
104391a1b2c9SMichael Liao     }
104491a1b2c9SMichael Liao 
104591a1b2c9SMichael Liao     // Update the last position with CHECK-DAG matches.
104691a1b2c9SMichael Liao     LastPos = std::max(MatchPos + MatchLen, LastPos);
104791a1b2c9SMichael Liao   }
104891a1b2c9SMichael Liao 
104991a1b2c9SMichael Liao   return LastPos;
105091a1b2c9SMichael Liao }
105191a1b2c9SMichael Liao 
1052c2735158SRui Ueyama bool ValidateCheckPrefix() {
1053c2735158SRui Ueyama   // The check prefix must contain only alphanumeric, hyphens and underscores.
1054c2735158SRui Ueyama   Regex prefixValidator("^[a-zA-Z0-9_-]*$");
1055c2735158SRui Ueyama   return prefixValidator.match(CheckPrefix);
1056c2735158SRui Ueyama }
1057c2735158SRui Ueyama 
1058ee3c74fbSChris Lattner int main(int argc, char **argv) {
1059ee3c74fbSChris Lattner   sys::PrintStackTraceOnErrorSignal();
1060ee3c74fbSChris Lattner   PrettyStackTraceProgram X(argc, argv);
1061ee3c74fbSChris Lattner   cl::ParseCommandLineOptions(argc, argv);
1062ee3c74fbSChris Lattner 
1063c2735158SRui Ueyama   if (!ValidateCheckPrefix()) {
1064c2735158SRui Ueyama     errs() << "Supplied check-prefix is invalid! Prefixes must start with a "
1065c2735158SRui Ueyama               "letter and contain only alphanumeric characters, hyphens and "
1066c2735158SRui Ueyama               "underscores\n";
1067c2735158SRui Ueyama     return 2;
1068c2735158SRui Ueyama   }
1069c2735158SRui Ueyama 
1070ee3c74fbSChris Lattner   SourceMgr SM;
1071ee3c74fbSChris Lattner 
1072ee3c74fbSChris Lattner   // Read the expected strings from the check file.
107326cccfe1SChris Lattner   std::vector<CheckString> CheckStrings;
1074ee3c74fbSChris Lattner   if (ReadCheckFile(SM, CheckStrings))
1075ee3c74fbSChris Lattner     return 2;
1076ee3c74fbSChris Lattner 
1077ee3c74fbSChris Lattner   // Open the file to check and add it to SourceMgr.
107839a0ffc3SMichael J. Spencer   OwningPtr<MemoryBuffer> File;
107939a0ffc3SMichael J. Spencer   if (error_code ec =
10808c811724SRafael Espindola         MemoryBuffer::getFileOrSTDIN(InputFilename, File)) {
1081ee3c74fbSChris Lattner     errs() << "Could not open input file '" << InputFilename << "': "
10827b6fef82SMichael J. Spencer            << ec.message() << '\n';
10838e1c6477SEli Bendersky     return 2;
1084ee3c74fbSChris Lattner   }
10852c3e5cdfSChris Lattner 
1086e963d660SBenjamin Kramer   if (File->getBufferSize() == 0) {
1087b692bed7SChris Lattner     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
10888e1c6477SEli Bendersky     return 2;
1089b692bed7SChris Lattner   }
1090b692bed7SChris Lattner 
10912c3e5cdfSChris Lattner   // Remove duplicate spaces in the input file if requested.
10925ea04c38SGuy Benyei   // Remove DOS style line endings.
1093e963d660SBenjamin Kramer   MemoryBuffer *F =
1094e963d660SBenjamin Kramer     CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
10952c3e5cdfSChris Lattner 
1096ee3c74fbSChris Lattner   SM.AddNewSourceBuffer(F, SMLoc());
1097ee3c74fbSChris Lattner 
10988879e06dSChris Lattner   /// VariableTable - This holds all the current filecheck variables.
10998879e06dSChris Lattner   StringMap<StringRef> VariableTable;
11008879e06dSChris Lattner 
1101ee3c74fbSChris Lattner   // Check that we have all of the expected strings, in order, in the input
1102ee3c74fbSChris Lattner   // file.
1103caa5fc0cSChris Lattner   StringRef Buffer = F->getBuffer();
1104ee3c74fbSChris Lattner 
1105f8bd2e5bSStephen Lin   bool hasError = false;
1106ee3c74fbSChris Lattner 
1107f8bd2e5bSStephen Lin   unsigned i = 0, j = 0, e = CheckStrings.size();
1108ee3c74fbSChris Lattner 
1109f8bd2e5bSStephen Lin   while (true) {
1110f8bd2e5bSStephen Lin     StringRef CheckRegion;
1111f8bd2e5bSStephen Lin     if (j == e) {
1112f8bd2e5bSStephen Lin       CheckRegion = Buffer;
1113f8bd2e5bSStephen Lin     } else {
1114f8bd2e5bSStephen Lin       const CheckString &CheckLabelStr = CheckStrings[j];
111538820972SMatt Arsenault       if (CheckLabelStr.CheckTy != Check::CheckLabel) {
1116f8bd2e5bSStephen Lin         ++j;
1117f8bd2e5bSStephen Lin         continue;
1118da108b4eSChris Lattner       }
1119da108b4eSChris Lattner 
1120f8bd2e5bSStephen Lin       // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1121f8bd2e5bSStephen Lin       size_t MatchLabelLen = 0;
1122f8bd2e5bSStephen Lin       size_t MatchLabelPos = CheckLabelStr.Check(SM, Buffer, true,
1123f8bd2e5bSStephen Lin                                                  MatchLabelLen, VariableTable);
1124f8bd2e5bSStephen Lin       if (MatchLabelPos == StringRef::npos) {
1125f8bd2e5bSStephen Lin         hasError = true;
1126f8bd2e5bSStephen Lin         break;
1127f8bd2e5bSStephen Lin       }
1128f8bd2e5bSStephen Lin 
1129f8bd2e5bSStephen Lin       CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1130f8bd2e5bSStephen Lin       Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1131f8bd2e5bSStephen Lin       ++j;
1132f8bd2e5bSStephen Lin     }
1133f8bd2e5bSStephen Lin 
1134f8bd2e5bSStephen Lin     for ( ; i != j; ++i) {
1135f8bd2e5bSStephen Lin       const CheckString &CheckStr = CheckStrings[i];
1136f8bd2e5bSStephen Lin 
1137f8bd2e5bSStephen Lin       // Check each string within the scanned region, including a second check
1138f8bd2e5bSStephen Lin       // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1139f8bd2e5bSStephen Lin       size_t MatchLen = 0;
1140f8bd2e5bSStephen Lin       size_t MatchPos = CheckStr.Check(SM, CheckRegion, false, MatchLen,
1141f8bd2e5bSStephen Lin                                        VariableTable);
1142f8bd2e5bSStephen Lin 
1143f8bd2e5bSStephen Lin       if (MatchPos == StringRef::npos) {
1144f8bd2e5bSStephen Lin         hasError = true;
1145f8bd2e5bSStephen Lin         i = j;
1146f8bd2e5bSStephen Lin         break;
1147f8bd2e5bSStephen Lin       }
1148f8bd2e5bSStephen Lin 
1149f8bd2e5bSStephen Lin       CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1150f8bd2e5bSStephen Lin     }
1151f8bd2e5bSStephen Lin 
1152f8bd2e5bSStephen Lin     if (j == e)
1153f8bd2e5bSStephen Lin       break;
1154f8bd2e5bSStephen Lin   }
1155f8bd2e5bSStephen Lin 
1156f8bd2e5bSStephen Lin   return hasError ? 1 : 0;
1157ee3c74fbSChris Lattner }
1158