blob: c1d017fae4b93f01b9652bcd516c34fa49039af1 [file] [log] [blame]
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// FileCheck does a line-by line check of a file that validates whether it
11// contains the expected content. This is useful for regression tests etc.
12//
13// This program exits with an error status of 2 on error, exit status of 0 if
14// the file matched the expected contents, and exit status of 1 if it did not
15// contain the expected contents.
16//
17//===----------------------------------------------------------------------===//
18
Michael J. Spencer3ff95632010-12-16 03:29:14 +000019#include "llvm/ADT/OwningPtr.h"
Chris Lattner81cb8ca2009-07-08 18:44:05 +000020#include "llvm/Support/CommandLine.h"
21#include "llvm/Support/MemoryBuffer.h"
22#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner52870082009-09-24 21:47:32 +000023#include "llvm/Support/Regex.h"
Chris Lattner81cb8ca2009-07-08 18:44:05 +000024#include "llvm/Support/SourceMgr.h"
25#include "llvm/Support/raw_ostream.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000026#include "llvm/Support/Signals.h"
Michael J. Spencer333fb042010-12-09 17:36:48 +000027#include "llvm/Support/system_error.h"
Daniel Dunbarfafe93c2009-11-22 22:08:06 +000028#include "llvm/ADT/SmallString.h"
Alexander Kornienko70a870a2012-11-14 21:07:37 +000029#include "llvm/ADT/StringExtras.h"
Chris Lattnereec96952009-09-27 07:56:52 +000030#include "llvm/ADT/StringMap.h"
31#include <algorithm>
Eli Bendersky9756ca72012-12-01 21:54:48 +000032#include <map>
33#include <string>
34#include <vector>
Chris Lattner81cb8ca2009-07-08 18:44:05 +000035using namespace llvm;
36
37static cl::opt<std::string>
38CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
39
40static cl::opt<std::string>
41InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
42 cl::init("-"), cl::value_desc("filename"));
43
44static cl::opt<std::string>
45CheckPrefix("check-prefix", cl::init("CHECK"),
46 cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
47
Chris Lattner88a7e9e2009-07-11 18:58:15 +000048static cl::opt<bool>
49NoCanonicalizeWhiteSpace("strict-whitespace",
50 cl::desc("Do not treat all horizontal whitespace as equivalent"));
51
Chris Lattnera29703e2009-09-24 20:39:13 +000052//===----------------------------------------------------------------------===//
53// Pattern Handling Code.
54//===----------------------------------------------------------------------===//
55
Chris Lattner9fc66782009-09-24 20:25:55 +000056class Pattern {
Chris Lattner94638f02009-09-25 17:29:36 +000057 SMLoc PatternLoc;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000058
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +000059 /// MatchEOF - When set, this pattern only matches the end of file. This is
60 /// used for trailing CHECK-NOTs.
61 bool MatchEOF;
62
Chris Lattner5d6a05f2009-09-25 17:23:43 +000063 /// FixedStr - If non-empty, this pattern is a fixed string match with the
64 /// specified fixed string.
Chris Lattner2702e6a2009-09-25 17:09:12 +000065 StringRef FixedStr;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000066
Chris Lattner5d6a05f2009-09-25 17:23:43 +000067 /// RegEx - If non-empty, this is a regex pattern.
68 std::string RegExStr;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000069
Alexander Kornienko70a870a2012-11-14 21:07:37 +000070 /// \brief Contains the number of line this pattern is in.
71 unsigned LineNumber;
72
Chris Lattnereec96952009-09-27 07:56:52 +000073 /// VariableUses - Entries in this vector map to uses of a variable in the
74 /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain
75 /// "foobaz" and we'll get an entry in this vector that tells us to insert the
76 /// value of bar at offset 3.
77 std::vector<std::pair<StringRef, unsigned> > VariableUses;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000078
Eli Bendersky9756ca72012-12-01 21:54:48 +000079 /// VariableDefs - Maps definitions of variables to their parenthesized
80 /// capture numbers.
81 /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
82 std::map<StringRef, unsigned> VariableDefs;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000083
Chris Lattner9fc66782009-09-24 20:25:55 +000084public:
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000085
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +000086 Pattern(bool matchEOF = false) : MatchEOF(matchEOF) { }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000087
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +000088 /// ParsePattern - Parse the given string into the Pattern. SM provides the
89 /// SourceMgr used for error reports, and LineNumber is the line number in
90 /// the input file from which the pattern string was read.
91 /// Returns true in case of an error, false otherwise.
Alexander Kornienko70a870a2012-11-14 21:07:37 +000092 bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000093
Chris Lattner9fc66782009-09-24 20:25:55 +000094 /// Match - Match the pattern string against the input buffer Buffer. This
95 /// returns the position that is matched or npos if there is no match. If
96 /// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattnereec96952009-09-27 07:56:52 +000097 ///
98 /// The VariableTable StringMap provides the current values of filecheck
99 /// variables and is updated if this match defines new values.
100 size_t Match(StringRef Buffer, size_t &MatchLen,
101 StringMap<StringRef> &VariableTable) const;
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000102
103 /// PrintFailureInfo - Print additional information about a failure to match
104 /// involving this pattern.
105 void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
106 const StringMap<StringRef> &VariableTable) const;
107
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000108private:
Chris Lattnereec96952009-09-27 07:56:52 +0000109 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
Eli Bendersky9756ca72012-12-01 21:54:48 +0000110 bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
111 void AddBackrefToRegEx(unsigned BackrefNum);
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000112
113 /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
114 /// matching this pattern at the start of \arg Buffer; a distance of zero
115 /// should correspond to a perfect match.
116 unsigned ComputeMatchDistance(StringRef Buffer,
117 const StringMap<StringRef> &VariableTable) const;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000118
119 /// \brief Evaluates expression and stores the result to \p Value.
120 /// \return true on success. false when the expression has invalid syntax.
121 bool EvaluateExpression(StringRef Expr, std::string &Value) const;
Eli Bendersky4db65112012-12-02 16:02:41 +0000122
123 /// \brief Finds the closing sequence of a regex variable usage or
124 /// definition. Str has to point in the beginning of the definition
125 /// (right after the opening sequence).
126 /// \return offset of the closing sequence within Str, or npos if it was not
127 /// found.
128 size_t FindRegexVarEnd(StringRef Str);
Chris Lattner9fc66782009-09-24 20:25:55 +0000129};
130
Chris Lattnereec96952009-09-27 07:56:52 +0000131
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000132bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
133 unsigned LineNumber) {
134 this->LineNumber = LineNumber;
Chris Lattner94638f02009-09-25 17:29:36 +0000135 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000136
Chris Lattnera29703e2009-09-24 20:39:13 +0000137 // Ignore trailing whitespace.
138 while (!PatternStr.empty() &&
139 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
140 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000141
Chris Lattnera29703e2009-09-24 20:39:13 +0000142 // Check that there is something on the line.
143 if (PatternStr.empty()) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000144 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
145 "found empty check string with prefix '" +
146 CheckPrefix+":'");
Chris Lattnera29703e2009-09-24 20:39:13 +0000147 return true;
148 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000149
Chris Lattner2702e6a2009-09-25 17:09:12 +0000150 // Check to see if this is a fixed string, or if it has regex pieces.
Ted Kremenek4f505172012-09-08 04:32:13 +0000151 if (PatternStr.size() < 2 ||
Chris Lattnereec96952009-09-27 07:56:52 +0000152 (PatternStr.find("{{") == StringRef::npos &&
153 PatternStr.find("[[") == StringRef::npos)) {
Chris Lattner2702e6a2009-09-25 17:09:12 +0000154 FixedStr = PatternStr;
155 return false;
156 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000157
Chris Lattnereec96952009-09-27 07:56:52 +0000158 // Paren value #0 is for the fully matched string. Any new parenthesized
Chris Lattner13a38c42011-04-09 06:18:02 +0000159 // values add from there.
Chris Lattnereec96952009-09-27 07:56:52 +0000160 unsigned CurParen = 1;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000161
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000162 // Otherwise, there is at least one regex piece. Build up the regex pattern
163 // by escaping scary characters in fixed strings, building up one big regex.
Chris Lattner52870082009-09-24 21:47:32 +0000164 while (!PatternStr.empty()) {
Chris Lattnereec96952009-09-27 07:56:52 +0000165 // RegEx matches.
Chris Lattner13a38c42011-04-09 06:18:02 +0000166 if (PatternStr.startswith("{{")) {
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +0000167 // This is the start of a regex match. Scan for the }}.
Chris Lattnereec96952009-09-27 07:56:52 +0000168 size_t End = PatternStr.find("}}");
169 if (End == StringRef::npos) {
170 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000171 SourceMgr::DK_Error,
172 "found start of regex string with no end '}}'");
Chris Lattnereec96952009-09-27 07:56:52 +0000173 return true;
174 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000175
Chris Lattner42e31df2011-04-09 06:37:03 +0000176 // Enclose {{}} patterns in parens just like [[]] even though we're not
177 // capturing the result for any purpose. This is required in case the
178 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
179 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
180 RegExStr += '(';
181 ++CurParen;
182
Chris Lattnereec96952009-09-27 07:56:52 +0000183 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
184 return true;
Chris Lattner42e31df2011-04-09 06:37:03 +0000185 RegExStr += ')';
Chris Lattner13a38c42011-04-09 06:18:02 +0000186
Chris Lattnereec96952009-09-27 07:56:52 +0000187 PatternStr = PatternStr.substr(End+2);
Chris Lattner52870082009-09-24 21:47:32 +0000188 continue;
189 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000190
Chris Lattnereec96952009-09-27 07:56:52 +0000191 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
192 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
193 // second form is [[foo]] which is a reference to foo. The variable name
Daniel Dunbar964ac012009-11-22 22:07:50 +0000194 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
Chris Lattnereec96952009-09-27 07:56:52 +0000195 // it. This is to catch some common errors.
Chris Lattner13a38c42011-04-09 06:18:02 +0000196 if (PatternStr.startswith("[[")) {
Eli Bendersky4db65112012-12-02 16:02:41 +0000197 // Find the closing bracket pair ending the match. End is going to be an
198 // offset relative to the beginning of the match string.
199 size_t End = FindRegexVarEnd(PatternStr.substr(2));
200
Chris Lattnereec96952009-09-27 07:56:52 +0000201 if (End == StringRef::npos) {
202 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000203 SourceMgr::DK_Error,
204 "invalid named regex reference, no ]] found");
Chris Lattnereec96952009-09-27 07:56:52 +0000205 return true;
206 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000207
Eli Bendersky4db65112012-12-02 16:02:41 +0000208 StringRef MatchStr = PatternStr.substr(2, End);
209 PatternStr = PatternStr.substr(End+4);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000210
Chris Lattnereec96952009-09-27 07:56:52 +0000211 // Get the regex name (e.g. "foo").
212 size_t NameEnd = MatchStr.find(':');
213 StringRef Name = MatchStr.substr(0, NameEnd);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000214
Chris Lattnereec96952009-09-27 07:56:52 +0000215 if (Name.empty()) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000216 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
217 "invalid name in named regex: empty name");
Chris Lattnereec96952009-09-27 07:56:52 +0000218 return true;
219 }
220
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000221 // Verify that the name/expression is well formed. FileCheck currently
222 // supports @LINE, @LINE+number, @LINE-number expressions. The check here
223 // is relaxed, more strict check is performed in \c EvaluateExpression.
224 bool IsExpression = false;
225 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
226 if (i == 0 && Name[i] == '@') {
227 if (NameEnd != StringRef::npos) {
228 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
229 SourceMgr::DK_Error,
230 "invalid name in named regex definition");
231 return true;
232 }
233 IsExpression = true;
234 continue;
235 }
236 if (Name[i] != '_' && !isalnum(Name[i]) &&
237 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
Chris Lattnereec96952009-09-27 07:56:52 +0000238 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000239 SourceMgr::DK_Error, "invalid name in named regex");
Chris Lattnereec96952009-09-27 07:56:52 +0000240 return true;
241 }
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000242 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000243
Chris Lattnereec96952009-09-27 07:56:52 +0000244 // Name can't start with a digit.
245 if (isdigit(Name[0])) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000246 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
247 "invalid name in named regex");
Chris Lattnereec96952009-09-27 07:56:52 +0000248 return true;
249 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000250
Chris Lattnereec96952009-09-27 07:56:52 +0000251 // Handle [[foo]].
252 if (NameEnd == StringRef::npos) {
Eli Bendersky9756ca72012-12-01 21:54:48 +0000253 // Handle variables that were defined earlier on the same line by
254 // emitting a backreference.
255 if (VariableDefs.find(Name) != VariableDefs.end()) {
256 unsigned VarParenNum = VariableDefs[Name];
257 if (VarParenNum < 1 || VarParenNum > 9) {
258 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
259 SourceMgr::DK_Error,
260 "Can't back-reference more than 9 variables");
261 return true;
262 }
263 AddBackrefToRegEx(VarParenNum);
264 } else {
265 VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
266 }
Chris Lattnereec96952009-09-27 07:56:52 +0000267 continue;
268 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000269
Chris Lattnereec96952009-09-27 07:56:52 +0000270 // Handle [[foo:.*]].
Eli Bendersky9756ca72012-12-01 21:54:48 +0000271 VariableDefs[Name] = CurParen;
Chris Lattnereec96952009-09-27 07:56:52 +0000272 RegExStr += '(';
273 ++CurParen;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000274
Chris Lattnereec96952009-09-27 07:56:52 +0000275 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
276 return true;
277
278 RegExStr += ')';
Chris Lattner52870082009-09-24 21:47:32 +0000279 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000280
Chris Lattnereec96952009-09-27 07:56:52 +0000281 // Handle fixed string matches.
282 // Find the end, which is the start of the next regex.
283 size_t FixedMatchEnd = PatternStr.find("{{");
284 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
285 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
286 PatternStr = PatternStr.substr(FixedMatchEnd);
Chris Lattner52870082009-09-24 21:47:32 +0000287 }
Chris Lattneradea46e2009-09-24 20:45:07 +0000288
Chris Lattnera29703e2009-09-24 20:39:13 +0000289 return false;
290}
291
Chris Lattnereec96952009-09-27 07:56:52 +0000292void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000293 // Add the characters from FixedStr to the regex, escaping as needed. This
294 // avoids "leaning toothpicks" in common patterns.
295 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
296 switch (FixedStr[i]) {
297 // These are the special characters matched in "p_ere_exp".
298 case '(':
299 case ')':
300 case '^':
301 case '$':
302 case '|':
303 case '*':
304 case '+':
305 case '?':
306 case '.':
307 case '[':
308 case '\\':
309 case '{':
Chris Lattnereec96952009-09-27 07:56:52 +0000310 TheStr += '\\';
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000311 // FALL THROUGH.
312 default:
Chris Lattnereec96952009-09-27 07:56:52 +0000313 TheStr += FixedStr[i];
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000314 break;
315 }
316 }
317}
318
Eli Bendersky9756ca72012-12-01 21:54:48 +0000319bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
Chris Lattnereec96952009-09-27 07:56:52 +0000320 SourceMgr &SM) {
Eli Bendersky9756ca72012-12-01 21:54:48 +0000321 Regex R(RS);
Chris Lattnereec96952009-09-27 07:56:52 +0000322 std::string Error;
323 if (!R.isValid(Error)) {
Eli Bendersky9756ca72012-12-01 21:54:48 +0000324 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000325 "invalid regex: " + Error);
Chris Lattnereec96952009-09-27 07:56:52 +0000326 return true;
327 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000328
Eli Bendersky9756ca72012-12-01 21:54:48 +0000329 RegExStr += RS.str();
Chris Lattnereec96952009-09-27 07:56:52 +0000330 CurParen += R.getNumMatches();
331 return false;
332}
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000333
Eli Bendersky9756ca72012-12-01 21:54:48 +0000334void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
335 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
336 std::string Backref = std::string("\\") +
337 std::string(1, '0' + BackrefNum);
338 RegExStr += Backref;
339}
340
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000341bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
342 // The only supported expression is @LINE([\+-]\d+)?
343 if (!Expr.startswith("@LINE"))
344 return false;
345 Expr = Expr.substr(StringRef("@LINE").size());
346 int Offset = 0;
347 if (!Expr.empty()) {
348 if (Expr[0] == '+')
349 Expr = Expr.substr(1);
350 else if (Expr[0] != '-')
351 return false;
352 if (Expr.getAsInteger(10, Offset))
353 return false;
354 }
355 Value = llvm::itostr(LineNumber + Offset);
356 return true;
357}
358
Chris Lattner52870082009-09-24 21:47:32 +0000359/// Match - Match the pattern string against the input buffer Buffer. This
360/// returns the position that is matched or npos if there is no match. If
361/// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattnereec96952009-09-27 07:56:52 +0000362size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
363 StringMap<StringRef> &VariableTable) const {
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000364 // If this is the EOF pattern, match it immediately.
365 if (MatchEOF) {
366 MatchLen = 0;
367 return Buffer.size();
368 }
369
Chris Lattner2702e6a2009-09-25 17:09:12 +0000370 // If this is a fixed string pattern, just match it now.
371 if (!FixedStr.empty()) {
372 MatchLen = FixedStr.size();
373 return Buffer.find(FixedStr);
374 }
Chris Lattnereec96952009-09-27 07:56:52 +0000375
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000376 // Regex match.
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000377
Chris Lattnereec96952009-09-27 07:56:52 +0000378 // If there are variable uses, we need to create a temporary string with the
379 // actual value.
380 StringRef RegExToMatch = RegExStr;
381 std::string TmpStr;
382 if (!VariableUses.empty()) {
383 TmpStr = RegExStr;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000384
Chris Lattnereec96952009-09-27 07:56:52 +0000385 unsigned InsertOffset = 0;
386 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
Chris Lattnereec96952009-09-27 07:56:52 +0000387 std::string Value;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000388
389 if (VariableUses[i].first[0] == '@') {
390 if (!EvaluateExpression(VariableUses[i].first, Value))
391 return StringRef::npos;
392 } else {
393 StringMap<StringRef>::iterator it =
394 VariableTable.find(VariableUses[i].first);
395 // If the variable is undefined, return an error.
396 if (it == VariableTable.end())
397 return StringRef::npos;
398
399 // Look up the value and escape it so that we can plop it into the regex.
400 AddFixedStringToRegEx(it->second, Value);
401 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000402
Chris Lattnereec96952009-09-27 07:56:52 +0000403 // Plop it into the regex at the adjusted offset.
404 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
405 Value.begin(), Value.end());
406 InsertOffset += Value.size();
407 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000408
Chris Lattnereec96952009-09-27 07:56:52 +0000409 // Match the newly constructed regex.
410 RegExToMatch = TmpStr;
411 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000412
413
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000414 SmallVector<StringRef, 4> MatchInfo;
Chris Lattnereec96952009-09-27 07:56:52 +0000415 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000416 return StringRef::npos;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000417
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000418 // Successful regex match.
419 assert(!MatchInfo.empty() && "Didn't get any match");
420 StringRef FullMatch = MatchInfo[0];
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000421
Chris Lattnereec96952009-09-27 07:56:52 +0000422 // If this defines any variables, remember their values.
Eli Bendersky9756ca72012-12-01 21:54:48 +0000423 for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
424 E = VariableDefs.end();
425 I != E; ++I) {
426 assert(I->second < MatchInfo.size() && "Internal paren error");
427 VariableTable[I->first] = MatchInfo[I->second];
Chris Lattner94638f02009-09-25 17:29:36 +0000428 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000429
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000430 MatchLen = FullMatch.size();
431 return FullMatch.data()-Buffer.data();
Chris Lattner52870082009-09-24 21:47:32 +0000432}
433
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000434unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
435 const StringMap<StringRef> &VariableTable) const {
436 // Just compute the number of matching characters. For regular expressions, we
437 // just compare against the regex itself and hope for the best.
438 //
439 // FIXME: One easy improvement here is have the regex lib generate a single
440 // example regular expression which matches, and use that as the example
441 // string.
442 StringRef ExampleString(FixedStr);
443 if (ExampleString.empty())
444 ExampleString = RegExStr;
445
Daniel Dunbar0806f9f2010-01-30 00:24:06 +0000446 // Only compare up to the first line in the buffer, or the string size.
447 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
448 BufferPrefix = BufferPrefix.split('\n').first;
449 return BufferPrefix.edit_distance(ExampleString);
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000450}
451
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000452void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
453 const StringMap<StringRef> &VariableTable) const{
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000454 // If this was a regular expression using variables, print the current
455 // variable values.
456 if (!VariableUses.empty()) {
457 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000458 SmallString<256> Msg;
459 raw_svector_ostream OS(Msg);
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000460 StringRef Var = VariableUses[i].first;
461 if (Var[0] == '@') {
462 std::string Value;
463 if (EvaluateExpression(Var, Value)) {
464 OS << "with expression \"";
465 OS.write_escaped(Var) << "\" equal to \"";
466 OS.write_escaped(Value) << "\"";
467 } else {
468 OS << "uses incorrect expression \"";
469 OS.write_escaped(Var) << "\"";
470 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000471 } else {
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000472 StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
473
474 // Check for undefined variable references.
475 if (it == VariableTable.end()) {
476 OS << "uses undefined variable \"";
477 OS.write_escaped(Var) << "\"";
478 } else {
479 OS << "with variable \"";
480 OS.write_escaped(Var) << "\" equal to \"";
481 OS.write_escaped(it->second) << "\"";
482 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000483 }
484
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000485 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
486 OS.str());
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000487 }
488 }
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000489
490 // Attempt to find the closest/best fuzzy match. Usually an error happens
491 // because some string in the output didn't exactly match. In these cases, we
492 // would like to show the user a best guess at what "should have" matched, to
493 // save them having to actually check the input manually.
494 size_t NumLinesForward = 0;
495 size_t Best = StringRef::npos;
496 double BestQuality = 0;
497
498 // Use an arbitrary 4k limit on how far we will search.
Dan Gohmane3a1e502010-01-29 21:57:46 +0000499 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000500 if (Buffer[i] == '\n')
501 ++NumLinesForward;
502
Dan Gohmand8a55412010-01-29 21:55:16 +0000503 // Patterns have leading whitespace stripped, so skip whitespace when
504 // looking for something which looks like a pattern.
505 if (Buffer[i] == ' ' || Buffer[i] == '\t')
506 continue;
507
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000508 // Compute the "quality" of this match as an arbitrary combination of the
509 // match distance and the number of lines skipped to get to this match.
510 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
511 double Quality = Distance + (NumLinesForward / 100.);
512
513 if (Quality < BestQuality || Best == StringRef::npos) {
514 Best = i;
515 BestQuality = Quality;
516 }
517 }
518
Daniel Dunbar7a68e0d2010-03-19 18:07:43 +0000519 // Print the "possible intended match here" line if we found something
520 // reasonable and not equal to what we showed in the "scanning from here"
521 // line.
522 if (Best && Best != StringRef::npos && BestQuality < 50) {
523 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000524 SourceMgr::DK_Note, "possible intended match here");
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000525
526 // FIXME: If we wanted to be really friendly we would show why the match
527 // failed, as it can be hard to spot simple one character differences.
528 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000529}
Chris Lattnera29703e2009-09-24 20:39:13 +0000530
Eli Bendersky4db65112012-12-02 16:02:41 +0000531size_t Pattern::FindRegexVarEnd(StringRef Str) {
532 // Offset keeps track of the current offset within the input Str
533 size_t Offset = 0;
534 // [...] Nesting depth
535 size_t BracketDepth = 0;
536
537 while (!Str.empty()) {
538 if (Str.startswith("]]") && BracketDepth == 0)
539 return Offset;
540 if (Str[0] == '\\') {
541 // Backslash escapes the next char within regexes, so skip them both.
542 Str = Str.substr(2);
543 Offset += 2;
544 } else {
545 switch (Str[0]) {
546 default:
547 break;
548 case '[':
549 BracketDepth++;
550 break;
551 case ']':
552 assert(BracketDepth > 0 && "Invalid regex");
553 BracketDepth--;
554 break;
555 }
556 Str = Str.substr(1);
557 Offset++;
558 }
559 }
560
561 return StringRef::npos;
562}
563
564
Chris Lattnera29703e2009-09-24 20:39:13 +0000565//===----------------------------------------------------------------------===//
566// Check Strings.
567//===----------------------------------------------------------------------===//
Chris Lattner9fc66782009-09-24 20:25:55 +0000568
569/// CheckString - This is a check that we found in the input file.
570struct CheckString {
571 /// Pat - The pattern to match.
572 Pattern Pat;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000573
Chris Lattner207e1bc2009-08-15 17:41:04 +0000574 /// Loc - The location in the match file that the check string was specified.
575 SMLoc Loc;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000576
Chris Lattner5dafafd2009-08-15 18:32:21 +0000577 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
578 /// to a CHECK: directive.
579 bool IsCheckNext;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000580
Chris Lattnerf15380b2009-09-20 22:35:26 +0000581 /// NotStrings - These are all of the strings that are disallowed from
582 /// occurring between this match string and the previous one (or start of
583 /// file).
Chris Lattnera29703e2009-09-24 20:39:13 +0000584 std::vector<std::pair<SMLoc, Pattern> > NotStrings;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000585
Chris Lattner9fc66782009-09-24 20:25:55 +0000586 CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
587 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
Chris Lattner207e1bc2009-08-15 17:41:04 +0000588};
589
Chris Lattneradea46e2009-09-24 20:45:07 +0000590/// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
591/// memory buffer, free it, and return a new one.
592static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
Chris Lattner4c842dd2010-04-05 22:42:30 +0000593 SmallString<128> NewFile;
Chris Lattneradea46e2009-09-24 20:45:07 +0000594 NewFile.reserve(MB->getBufferSize());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000595
Chris Lattneradea46e2009-09-24 20:45:07 +0000596 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
597 Ptr != End; ++Ptr) {
NAKAMURA Takumi9f6e03f2010-11-14 03:28:22 +0000598 // Eliminate trailing dosish \r.
599 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
600 continue;
601 }
602
Dmitri Gribenko9d227af2012-09-21 15:26:34 +0000603 // If current char is not a horizontal whitespace, dump it to output as is.
Chris Lattneradea46e2009-09-24 20:45:07 +0000604 if (*Ptr != ' ' && *Ptr != '\t') {
605 NewFile.push_back(*Ptr);
606 continue;
607 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000608
Chris Lattneradea46e2009-09-24 20:45:07 +0000609 // Otherwise, add one space and advance over neighboring space.
610 NewFile.push_back(' ');
611 while (Ptr+1 != End &&
612 (Ptr[1] == ' ' || Ptr[1] == '\t'))
613 ++Ptr;
614 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000615
Chris Lattneradea46e2009-09-24 20:45:07 +0000616 // Free the old buffer and return a new one.
617 MemoryBuffer *MB2 =
Chris Lattner4c842dd2010-04-05 22:42:30 +0000618 MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000619
Chris Lattneradea46e2009-09-24 20:45:07 +0000620 delete MB;
621 return MB2;
622}
623
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000624
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000625/// ReadCheckFile - Read the check file, which specifies the sequence of
626/// expected strings. The strings are added to the CheckStrings vector.
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +0000627/// Returns true in case of an error, false otherwise.
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000628static bool ReadCheckFile(SourceMgr &SM,
Chris Lattner207e1bc2009-08-15 17:41:04 +0000629 std::vector<CheckString> &CheckStrings) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000630 OwningPtr<MemoryBuffer> File;
631 if (error_code ec =
632 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) {
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000633 errs() << "Could not open check file '" << CheckFilename << "': "
Michael J. Spencer333fb042010-12-09 17:36:48 +0000634 << ec.message() << '\n';
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000635 return true;
636 }
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000637 MemoryBuffer *F = File.take();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000638
Chris Lattneradea46e2009-09-24 20:45:07 +0000639 // If we want to canonicalize whitespace, strip excess whitespace from the
640 // buffer containing the CHECK lines.
641 if (!NoCanonicalizeWhiteSpace)
642 F = CanonicalizeInputFile(F);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000643
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000644 SM.AddNewSourceBuffer(F, SMLoc());
645
Chris Lattnerd7e25052009-08-15 18:00:42 +0000646 // Find all instances of CheckPrefix followed by : in the file.
Chris Lattner96077032009-09-20 22:11:44 +0000647 StringRef Buffer = F->getBuffer();
Chris Lattnera29703e2009-09-24 20:39:13 +0000648 std::vector<std::pair<SMLoc, Pattern> > NotMatches;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000649
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +0000650 // LineNumber keeps track of the line on which CheckPrefix instances are
651 // found.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000652 unsigned LineNumber = 1;
653
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000654 while (1) {
655 // See if Prefix occurs in the memory buffer.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000656 size_t PrefixLoc = Buffer.find(CheckPrefix);
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000657 // If we didn't find a match, we're done.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000658 if (PrefixLoc == StringRef::npos)
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000659 break;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000660
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000661 LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
662
663 Buffer = Buffer.substr(PrefixLoc);
664
Chris Lattner96077032009-09-20 22:11:44 +0000665 const char *CheckPrefixStart = Buffer.data();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000666
Chris Lattner5dafafd2009-08-15 18:32:21 +0000667 // When we find a check prefix, keep track of whether we find CHECK: or
668 // CHECK-NEXT:
Chris Lattnerf15380b2009-09-20 22:35:26 +0000669 bool IsCheckNext = false, IsCheckNot = false;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000670
Chris Lattnerd7e25052009-08-15 18:00:42 +0000671 // Verify that the : is present after the prefix.
Chris Lattner96077032009-09-20 22:11:44 +0000672 if (Buffer[CheckPrefix.size()] == ':') {
673 Buffer = Buffer.substr(CheckPrefix.size()+1);
Chris Lattner96077032009-09-20 22:11:44 +0000674 } else if (Buffer.size() > CheckPrefix.size()+6 &&
675 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Benjamin Kramer30ce40e2012-09-18 20:51:39 +0000676 Buffer = Buffer.substr(CheckPrefix.size()+6);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000677 IsCheckNext = true;
Chris Lattnerf15380b2009-09-20 22:35:26 +0000678 } else if (Buffer.size() > CheckPrefix.size()+5 &&
679 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
Benjamin Kramer30ce40e2012-09-18 20:51:39 +0000680 Buffer = Buffer.substr(CheckPrefix.size()+5);
Chris Lattnerf15380b2009-09-20 22:35:26 +0000681 IsCheckNot = true;
Chris Lattner5dafafd2009-08-15 18:32:21 +0000682 } else {
Chris Lattner96077032009-09-20 22:11:44 +0000683 Buffer = Buffer.substr(1);
Chris Lattnerd7e25052009-08-15 18:00:42 +0000684 continue;
685 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000686
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000687 // Okay, we found the prefix, yay. Remember the rest of the line, but
688 // ignore leading and trailing whitespace.
Chris Lattnerf15380b2009-09-20 22:35:26 +0000689 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000690
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000691 // Scan ahead to the end of line.
Chris Lattner96077032009-09-20 22:11:44 +0000692 size_t EOL = Buffer.find_first_of("\n\r");
Chris Lattnera29703e2009-09-24 20:39:13 +0000693
Dan Gohmane5463432010-01-29 21:53:18 +0000694 // Remember the location of the start of the pattern, for diagnostics.
695 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
696
Chris Lattnera29703e2009-09-24 20:39:13 +0000697 // Parse the pattern.
698 Pattern P;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000699 if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000700 return true;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000701
Chris Lattnera29703e2009-09-24 20:39:13 +0000702 Buffer = Buffer.substr(EOL);
703
Chris Lattner5dafafd2009-08-15 18:32:21 +0000704 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
705 if (IsCheckNext && CheckStrings.empty()) {
706 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000707 SourceMgr::DK_Error,
Chris Lattner5dafafd2009-08-15 18:32:21 +0000708 "found '"+CheckPrefix+"-NEXT:' without previous '"+
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000709 CheckPrefix+ ": line");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000710 return true;
711 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000712
Chris Lattnera29703e2009-09-24 20:39:13 +0000713 // Handle CHECK-NOT.
714 if (IsCheckNot) {
715 NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
716 P));
717 continue;
718 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000719
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000720 // Okay, add the string we captured to the output vector and move on.
Chris Lattner9fc66782009-09-24 20:25:55 +0000721 CheckStrings.push_back(CheckString(P,
Dan Gohmane5463432010-01-29 21:53:18 +0000722 PatternLoc,
Chris Lattner5dafafd2009-08-15 18:32:21 +0000723 IsCheckNext));
Chris Lattnerf15380b2009-09-20 22:35:26 +0000724 std::swap(NotMatches, CheckStrings.back().NotStrings);
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000725 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000726
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000727 // Add an EOF pattern for any trailing CHECK-NOTs.
728 if (!NotMatches.empty()) {
729 CheckStrings.push_back(CheckString(Pattern(true),
730 SMLoc::getFromPointer(Buffer.data()),
731 false));
732 std::swap(NotMatches, CheckStrings.back().NotStrings);
733 }
734
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000735 if (CheckStrings.empty()) {
Chris Lattnerd7e25052009-08-15 18:00:42 +0000736 errs() << "error: no check strings found with prefix '" << CheckPrefix
737 << ":'\n";
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000738 return true;
739 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000740
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000741 return false;
742}
743
Chris Lattner5dafafd2009-08-15 18:32:21 +0000744static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000745 StringRef Buffer,
746 StringMap<StringRef> &VariableTable) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000747 // Otherwise, we have an error, emit an error message.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000748 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
749 "expected string not found in input");
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000750
Chris Lattner5dafafd2009-08-15 18:32:21 +0000751 // Print the "scanning from here" line. If the current position is at the
752 // end of a line, advance to the start of the next line.
Chris Lattner96077032009-09-20 22:11:44 +0000753 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000754
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000755 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
756 "scanning from here");
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000757
758 // Allow the pattern to print additional information if desired.
759 CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000760}
761
Chris Lattner3711b7a2009-09-20 22:42:44 +0000762/// CountNumNewlinesBetween - Count the number of newlines in the specified
763/// range.
764static unsigned CountNumNewlinesBetween(StringRef Range) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000765 unsigned NumNewLines = 0;
Chris Lattner3711b7a2009-09-20 22:42:44 +0000766 while (1) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000767 // Scan for newline.
Chris Lattner3711b7a2009-09-20 22:42:44 +0000768 Range = Range.substr(Range.find_first_of("\n\r"));
769 if (Range.empty()) return NumNewLines;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000770
Chris Lattner5dafafd2009-08-15 18:32:21 +0000771 ++NumNewLines;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000772
Chris Lattner5dafafd2009-08-15 18:32:21 +0000773 // Handle \n\r and \r\n as a single newline.
Chris Lattner3711b7a2009-09-20 22:42:44 +0000774 if (Range.size() > 1 &&
775 (Range[1] == '\n' || Range[1] == '\r') &&
776 (Range[0] != Range[1]))
777 Range = Range.substr(1);
778 Range = Range.substr(1);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000779 }
Chris Lattner5dafafd2009-08-15 18:32:21 +0000780}
781
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000782int main(int argc, char **argv) {
783 sys::PrintStackTraceOnErrorSignal();
784 PrettyStackTraceProgram X(argc, argv);
785 cl::ParseCommandLineOptions(argc, argv);
786
787 SourceMgr SM;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000788
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000789 // Read the expected strings from the check file.
Chris Lattner207e1bc2009-08-15 17:41:04 +0000790 std::vector<CheckString> CheckStrings;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000791 if (ReadCheckFile(SM, CheckStrings))
792 return 2;
793
794 // Open the file to check and add it to SourceMgr.
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000795 OwningPtr<MemoryBuffer> File;
796 if (error_code ec =
797 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000798 errs() << "Could not open input file '" << InputFilename << "': "
Michael J. Spencer333fb042010-12-09 17:36:48 +0000799 << ec.message() << '\n';
Eli Bendersky7f8e76f2012-11-30 13:51:33 +0000800 return 2;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000801 }
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000802 MemoryBuffer *F = File.take();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000803
Chris Lattner1aac1862011-02-09 16:46:02 +0000804 if (F->getBufferSize() == 0) {
805 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
Eli Bendersky7f8e76f2012-11-30 13:51:33 +0000806 return 2;
Chris Lattner1aac1862011-02-09 16:46:02 +0000807 }
808
Chris Lattner88a7e9e2009-07-11 18:58:15 +0000809 // Remove duplicate spaces in the input file if requested.
810 if (!NoCanonicalizeWhiteSpace)
811 F = CanonicalizeInputFile(F);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000812
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000813 SM.AddNewSourceBuffer(F, SMLoc());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000814
Chris Lattnereec96952009-09-27 07:56:52 +0000815 /// VariableTable - This holds all the current filecheck variables.
816 StringMap<StringRef> VariableTable;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000817
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000818 // Check that we have all of the expected strings, in order, in the input
819 // file.
Chris Lattner96077032009-09-20 22:11:44 +0000820 StringRef Buffer = F->getBuffer();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000821
Chris Lattnerf15380b2009-09-20 22:35:26 +0000822 const char *LastMatch = Buffer.data();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000823
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000824 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
Chris Lattner207e1bc2009-08-15 17:41:04 +0000825 const CheckString &CheckStr = CheckStrings[StrNo];
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000826
Chris Lattner96077032009-09-20 22:11:44 +0000827 StringRef SearchFrom = Buffer;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000828
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000829 // Find StrNo in the file.
Chris Lattner9fc66782009-09-24 20:25:55 +0000830 size_t MatchLen = 0;
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000831 size_t MatchPos = CheckStr.Pat.Match(Buffer, MatchLen, VariableTable);
832 Buffer = Buffer.substr(MatchPos);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000833
Chris Lattner5dafafd2009-08-15 18:32:21 +0000834 // If we didn't find a match, reject the input.
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000835 if (MatchPos == StringRef::npos) {
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000836 PrintCheckFailed(SM, CheckStr, SearchFrom, VariableTable);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000837 return 1;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000838 }
Chris Lattner3711b7a2009-09-20 22:42:44 +0000839
840 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
841
Chris Lattner5dafafd2009-08-15 18:32:21 +0000842 // If this check is a "CHECK-NEXT", verify that the previous match was on
843 // the previous line (i.e. that there is one newline between them).
844 if (CheckStr.IsCheckNext) {
845 // Count the number of newlines between the previous match and this one.
Chris Lattnerf15380b2009-09-20 22:35:26 +0000846 assert(LastMatch != F->getBufferStart() &&
847 "CHECK-NEXT can't be the first check in a file");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000848
Chris Lattner3711b7a2009-09-20 22:42:44 +0000849 unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000850 if (NumNewLines == 0) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000851 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
852 CheckPrefix+"-NEXT: is on the same line as previous match");
Chris Lattner96077032009-09-20 22:11:44 +0000853 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000854 SourceMgr::DK_Note, "'next' match was here");
855 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
856 "previous match was here");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000857 return 1;
858 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000859
Chris Lattner5dafafd2009-08-15 18:32:21 +0000860 if (NumNewLines != 1) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000861 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+
862 "-NEXT: is not on the line after the previous match");
Chris Lattner96077032009-09-20 22:11:44 +0000863 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000864 SourceMgr::DK_Note, "'next' match was here");
865 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
866 "previous match was here");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000867 return 1;
868 }
869 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000870
Chris Lattnerf15380b2009-09-20 22:35:26 +0000871 // If this match had "not strings", verify that they don't exist in the
872 // skipped region.
Chris Lattnereec96952009-09-27 07:56:52 +0000873 for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size();
874 ChunkNo != e; ++ChunkNo) {
Chris Lattnera29703e2009-09-24 20:39:13 +0000875 size_t MatchLen = 0;
Chris Lattnereec96952009-09-27 07:56:52 +0000876 size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion,
877 MatchLen,
878 VariableTable);
Chris Lattnerf15380b2009-09-20 22:35:26 +0000879 if (Pos == StringRef::npos) continue;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000880
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000881 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos), SourceMgr::DK_Error,
882 CheckPrefix+"-NOT: string occurred!");
883 SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first, SourceMgr::DK_Note,
884 CheckPrefix+"-NOT: pattern specified here");
Chris Lattnerf15380b2009-09-20 22:35:26 +0000885 return 1;
886 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000887
Chris Lattner5dafafd2009-08-15 18:32:21 +0000888
Chris Lattner81115762009-09-21 02:30:42 +0000889 // Otherwise, everything is good. Step over the matched text and remember
890 // the position after the match as the end of the last match.
Chris Lattner9fc66782009-09-24 20:25:55 +0000891 Buffer = Buffer.substr(MatchLen);
Chris Lattner81115762009-09-21 02:30:42 +0000892 LastMatch = Buffer.data();
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000893 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000894
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000895 return 0;
896}