blob: fb66ac2fceb2b7e199e319701c64e948e017c398 [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>
Chris Lattner81cb8ca2009-07-08 18:44:05 +000032using namespace llvm;
33
34static cl::opt<std::string>
35CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
36
37static cl::opt<std::string>
38InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
39 cl::init("-"), cl::value_desc("filename"));
40
41static cl::opt<std::string>
42CheckPrefix("check-prefix", cl::init("CHECK"),
43 cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
44
Chris Lattner88a7e9e2009-07-11 18:58:15 +000045static cl::opt<bool>
46NoCanonicalizeWhiteSpace("strict-whitespace",
47 cl::desc("Do not treat all horizontal whitespace as equivalent"));
48
Chris Lattnera29703e2009-09-24 20:39:13 +000049//===----------------------------------------------------------------------===//
50// Pattern Handling Code.
51//===----------------------------------------------------------------------===//
52
Chris Lattner9fc66782009-09-24 20:25:55 +000053class Pattern {
Chris Lattner94638f02009-09-25 17:29:36 +000054 SMLoc PatternLoc;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000055
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +000056 /// MatchEOF - When set, this pattern only matches the end of file. This is
57 /// used for trailing CHECK-NOTs.
58 bool MatchEOF;
59
Chris Lattner5d6a05f2009-09-25 17:23:43 +000060 /// FixedStr - If non-empty, this pattern is a fixed string match with the
61 /// specified fixed string.
Chris Lattner2702e6a2009-09-25 17:09:12 +000062 StringRef FixedStr;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000063
Chris Lattner5d6a05f2009-09-25 17:23:43 +000064 /// RegEx - If non-empty, this is a regex pattern.
65 std::string RegExStr;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000066
Alexander Kornienko70a870a2012-11-14 21:07:37 +000067 /// \brief Contains the number of line this pattern is in.
68 unsigned LineNumber;
69
Chris Lattnereec96952009-09-27 07:56:52 +000070 /// VariableUses - Entries in this vector map to uses of a variable in the
71 /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain
72 /// "foobaz" and we'll get an entry in this vector that tells us to insert the
73 /// value of bar at offset 3.
74 std::vector<std::pair<StringRef, unsigned> > VariableUses;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000075
Chris Lattnereec96952009-09-27 07:56:52 +000076 /// VariableDefs - Entries in this vector map to definitions of a variable in
77 /// the pattern, e.g. "foo[[bar:.*]]baz". In this case, the RegExStr will
78 /// contain "foo(.*)baz" and VariableDefs will contain the pair "bar",1. The
79 /// index indicates what parenthesized value captures the variable value.
80 std::vector<std::pair<StringRef, unsigned> > VariableDefs;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000081
Chris Lattner9fc66782009-09-24 20:25:55 +000082public:
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000083
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +000084 Pattern(bool matchEOF = false) : MatchEOF(matchEOF) { }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000085
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +000086 /// ParsePattern - Parse the given string into the Pattern. SM provides the
87 /// SourceMgr used for error reports, and LineNumber is the line number in
88 /// the input file from which the pattern string was read.
89 /// Returns true in case of an error, false otherwise.
Alexander Kornienko70a870a2012-11-14 21:07:37 +000090 bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000091
Chris Lattner9fc66782009-09-24 20:25:55 +000092 /// Match - Match the pattern string against the input buffer Buffer. This
93 /// returns the position that is matched or npos if there is no match. If
94 /// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattnereec96952009-09-27 07:56:52 +000095 ///
96 /// The VariableTable StringMap provides the current values of filecheck
97 /// variables and is updated if this match defines new values.
98 size_t Match(StringRef Buffer, size_t &MatchLen,
99 StringMap<StringRef> &VariableTable) const;
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000100
101 /// PrintFailureInfo - Print additional information about a failure to match
102 /// involving this pattern.
103 void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
104 const StringMap<StringRef> &VariableTable) const;
105
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000106private:
Chris Lattnereec96952009-09-27 07:56:52 +0000107 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
108 bool AddRegExToRegEx(StringRef RegExStr, unsigned &CurParen, SourceMgr &SM);
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000109
110 /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
111 /// matching this pattern at the start of \arg Buffer; a distance of zero
112 /// should correspond to a perfect match.
113 unsigned ComputeMatchDistance(StringRef Buffer,
114 const StringMap<StringRef> &VariableTable) const;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000115
116 /// \brief Evaluates expression and stores the result to \p Value.
117 /// \return true on success. false when the expression has invalid syntax.
118 bool EvaluateExpression(StringRef Expr, std::string &Value) const;
Chris Lattner9fc66782009-09-24 20:25:55 +0000119};
120
Chris Lattnereec96952009-09-27 07:56:52 +0000121
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000122bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
123 unsigned LineNumber) {
124 this->LineNumber = LineNumber;
Chris Lattner94638f02009-09-25 17:29:36 +0000125 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000126
Chris Lattnera29703e2009-09-24 20:39:13 +0000127 // Ignore trailing whitespace.
128 while (!PatternStr.empty() &&
129 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
130 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000131
Chris Lattnera29703e2009-09-24 20:39:13 +0000132 // Check that there is something on the line.
133 if (PatternStr.empty()) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000134 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
135 "found empty check string with prefix '" +
136 CheckPrefix+":'");
Chris Lattnera29703e2009-09-24 20:39:13 +0000137 return true;
138 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000139
Chris Lattner2702e6a2009-09-25 17:09:12 +0000140 // Check to see if this is a fixed string, or if it has regex pieces.
Ted Kremenek4f505172012-09-08 04:32:13 +0000141 if (PatternStr.size() < 2 ||
Chris Lattnereec96952009-09-27 07:56:52 +0000142 (PatternStr.find("{{") == StringRef::npos &&
143 PatternStr.find("[[") == StringRef::npos)) {
Chris Lattner2702e6a2009-09-25 17:09:12 +0000144 FixedStr = PatternStr;
145 return false;
146 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000147
Chris Lattnereec96952009-09-27 07:56:52 +0000148 // Paren value #0 is for the fully matched string. Any new parenthesized
Chris Lattner13a38c42011-04-09 06:18:02 +0000149 // values add from there.
Chris Lattnereec96952009-09-27 07:56:52 +0000150 unsigned CurParen = 1;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000151
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000152 // Otherwise, there is at least one regex piece. Build up the regex pattern
153 // by escaping scary characters in fixed strings, building up one big regex.
Chris Lattner52870082009-09-24 21:47:32 +0000154 while (!PatternStr.empty()) {
Chris Lattnereec96952009-09-27 07:56:52 +0000155 // RegEx matches.
Chris Lattner13a38c42011-04-09 06:18:02 +0000156 if (PatternStr.startswith("{{")) {
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +0000157 // This is the start of a regex match. Scan for the }}.
Chris Lattnereec96952009-09-27 07:56:52 +0000158 size_t End = PatternStr.find("}}");
159 if (End == StringRef::npos) {
160 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000161 SourceMgr::DK_Error,
162 "found start of regex string with no end '}}'");
Chris Lattnereec96952009-09-27 07:56:52 +0000163 return true;
164 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000165
Chris Lattner42e31df2011-04-09 06:37:03 +0000166 // Enclose {{}} patterns in parens just like [[]] even though we're not
167 // capturing the result for any purpose. This is required in case the
168 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
169 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
170 RegExStr += '(';
171 ++CurParen;
172
Chris Lattnereec96952009-09-27 07:56:52 +0000173 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
174 return true;
Chris Lattner42e31df2011-04-09 06:37:03 +0000175 RegExStr += ')';
Chris Lattner13a38c42011-04-09 06:18:02 +0000176
Chris Lattnereec96952009-09-27 07:56:52 +0000177 PatternStr = PatternStr.substr(End+2);
Chris Lattner52870082009-09-24 21:47:32 +0000178 continue;
179 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000180
Chris Lattnereec96952009-09-27 07:56:52 +0000181 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
182 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
183 // second form is [[foo]] which is a reference to foo. The variable name
Daniel Dunbar964ac012009-11-22 22:07:50 +0000184 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
Chris Lattnereec96952009-09-27 07:56:52 +0000185 // it. This is to catch some common errors.
Chris Lattner13a38c42011-04-09 06:18:02 +0000186 if (PatternStr.startswith("[[")) {
Chris Lattnereec96952009-09-27 07:56:52 +0000187 // Verify that it is terminated properly.
188 size_t End = PatternStr.find("]]");
189 if (End == StringRef::npos) {
190 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000191 SourceMgr::DK_Error,
192 "invalid named regex reference, no ]] found");
Chris Lattnereec96952009-09-27 07:56:52 +0000193 return true;
194 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000195
Chris Lattnereec96952009-09-27 07:56:52 +0000196 StringRef MatchStr = PatternStr.substr(2, End-2);
197 PatternStr = PatternStr.substr(End+2);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000198
Chris Lattnereec96952009-09-27 07:56:52 +0000199 // Get the regex name (e.g. "foo").
200 size_t NameEnd = MatchStr.find(':');
201 StringRef Name = MatchStr.substr(0, NameEnd);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000202
Chris Lattnereec96952009-09-27 07:56:52 +0000203 if (Name.empty()) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000204 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
205 "invalid name in named regex: empty name");
Chris Lattnereec96952009-09-27 07:56:52 +0000206 return true;
207 }
208
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000209 // Verify that the name/expression is well formed. FileCheck currently
210 // supports @LINE, @LINE+number, @LINE-number expressions. The check here
211 // is relaxed, more strict check is performed in \c EvaluateExpression.
212 bool IsExpression = false;
213 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
214 if (i == 0 && Name[i] == '@') {
215 if (NameEnd != StringRef::npos) {
216 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
217 SourceMgr::DK_Error,
218 "invalid name in named regex definition");
219 return true;
220 }
221 IsExpression = true;
222 continue;
223 }
224 if (Name[i] != '_' && !isalnum(Name[i]) &&
225 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
Chris Lattnereec96952009-09-27 07:56:52 +0000226 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000227 SourceMgr::DK_Error, "invalid name in named regex");
Chris Lattnereec96952009-09-27 07:56:52 +0000228 return true;
229 }
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000230 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000231
Chris Lattnereec96952009-09-27 07:56:52 +0000232 // Name can't start with a digit.
233 if (isdigit(Name[0])) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000234 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
235 "invalid name in named regex");
Chris Lattnereec96952009-09-27 07:56:52 +0000236 return true;
237 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000238
Chris Lattnereec96952009-09-27 07:56:52 +0000239 // Handle [[foo]].
240 if (NameEnd == StringRef::npos) {
241 VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
242 continue;
243 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000244
Chris Lattnereec96952009-09-27 07:56:52 +0000245 // Handle [[foo:.*]].
246 VariableDefs.push_back(std::make_pair(Name, CurParen));
247 RegExStr += '(';
248 ++CurParen;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000249
Chris Lattnereec96952009-09-27 07:56:52 +0000250 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
251 return true;
252
253 RegExStr += ')';
Chris Lattner52870082009-09-24 21:47:32 +0000254 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000255
Chris Lattnereec96952009-09-27 07:56:52 +0000256 // Handle fixed string matches.
257 // Find the end, which is the start of the next regex.
258 size_t FixedMatchEnd = PatternStr.find("{{");
259 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
260 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
261 PatternStr = PatternStr.substr(FixedMatchEnd);
Chris Lattner52870082009-09-24 21:47:32 +0000262 }
Chris Lattneradea46e2009-09-24 20:45:07 +0000263
Chris Lattnera29703e2009-09-24 20:39:13 +0000264 return false;
265}
266
Chris Lattnereec96952009-09-27 07:56:52 +0000267void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000268 // Add the characters from FixedStr to the regex, escaping as needed. This
269 // avoids "leaning toothpicks" in common patterns.
270 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
271 switch (FixedStr[i]) {
272 // These are the special characters matched in "p_ere_exp".
273 case '(':
274 case ')':
275 case '^':
276 case '$':
277 case '|':
278 case '*':
279 case '+':
280 case '?':
281 case '.':
282 case '[':
283 case '\\':
284 case '{':
Chris Lattnereec96952009-09-27 07:56:52 +0000285 TheStr += '\\';
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000286 // FALL THROUGH.
287 default:
Chris Lattnereec96952009-09-27 07:56:52 +0000288 TheStr += FixedStr[i];
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000289 break;
290 }
291 }
292}
293
Chris Lattnereec96952009-09-27 07:56:52 +0000294bool Pattern::AddRegExToRegEx(StringRef RegexStr, unsigned &CurParen,
295 SourceMgr &SM) {
296 Regex R(RegexStr);
297 std::string Error;
298 if (!R.isValid(Error)) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000299 SM.PrintMessage(SMLoc::getFromPointer(RegexStr.data()), SourceMgr::DK_Error,
300 "invalid regex: " + Error);
Chris Lattnereec96952009-09-27 07:56:52 +0000301 return true;
302 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000303
Chris Lattnereec96952009-09-27 07:56:52 +0000304 RegExStr += RegexStr.str();
305 CurParen += R.getNumMatches();
306 return false;
307}
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000308
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000309bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
310 // The only supported expression is @LINE([\+-]\d+)?
311 if (!Expr.startswith("@LINE"))
312 return false;
313 Expr = Expr.substr(StringRef("@LINE").size());
314 int Offset = 0;
315 if (!Expr.empty()) {
316 if (Expr[0] == '+')
317 Expr = Expr.substr(1);
318 else if (Expr[0] != '-')
319 return false;
320 if (Expr.getAsInteger(10, Offset))
321 return false;
322 }
323 Value = llvm::itostr(LineNumber + Offset);
324 return true;
325}
326
Chris Lattner52870082009-09-24 21:47:32 +0000327/// Match - Match the pattern string against the input buffer Buffer. This
328/// returns the position that is matched or npos if there is no match. If
329/// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattnereec96952009-09-27 07:56:52 +0000330size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
331 StringMap<StringRef> &VariableTable) const {
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000332 // If this is the EOF pattern, match it immediately.
333 if (MatchEOF) {
334 MatchLen = 0;
335 return Buffer.size();
336 }
337
Chris Lattner2702e6a2009-09-25 17:09:12 +0000338 // If this is a fixed string pattern, just match it now.
339 if (!FixedStr.empty()) {
340 MatchLen = FixedStr.size();
341 return Buffer.find(FixedStr);
342 }
Chris Lattnereec96952009-09-27 07:56:52 +0000343
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000344 // Regex match.
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000345
Chris Lattnereec96952009-09-27 07:56:52 +0000346 // If there are variable uses, we need to create a temporary string with the
347 // actual value.
348 StringRef RegExToMatch = RegExStr;
349 std::string TmpStr;
350 if (!VariableUses.empty()) {
351 TmpStr = RegExStr;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000352
Chris Lattnereec96952009-09-27 07:56:52 +0000353 unsigned InsertOffset = 0;
354 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
Chris Lattnereec96952009-09-27 07:56:52 +0000355 std::string Value;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000356
357 if (VariableUses[i].first[0] == '@') {
358 if (!EvaluateExpression(VariableUses[i].first, Value))
359 return StringRef::npos;
360 } else {
361 StringMap<StringRef>::iterator it =
362 VariableTable.find(VariableUses[i].first);
363 // If the variable is undefined, return an error.
364 if (it == VariableTable.end())
365 return StringRef::npos;
366
367 // Look up the value and escape it so that we can plop it into the regex.
368 AddFixedStringToRegEx(it->second, Value);
369 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000370
Chris Lattnereec96952009-09-27 07:56:52 +0000371 // Plop it into the regex at the adjusted offset.
372 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
373 Value.begin(), Value.end());
374 InsertOffset += Value.size();
375 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000376
Chris Lattnereec96952009-09-27 07:56:52 +0000377 // Match the newly constructed regex.
378 RegExToMatch = TmpStr;
379 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000380
381
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000382 SmallVector<StringRef, 4> MatchInfo;
Chris Lattnereec96952009-09-27 07:56:52 +0000383 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000384 return StringRef::npos;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000385
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000386 // Successful regex match.
387 assert(!MatchInfo.empty() && "Didn't get any match");
388 StringRef FullMatch = MatchInfo[0];
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000389
Chris Lattnereec96952009-09-27 07:56:52 +0000390 // If this defines any variables, remember their values.
391 for (unsigned i = 0, e = VariableDefs.size(); i != e; ++i) {
392 assert(VariableDefs[i].second < MatchInfo.size() &&
393 "Internal paren error");
394 VariableTable[VariableDefs[i].first] = MatchInfo[VariableDefs[i].second];
Chris Lattner94638f02009-09-25 17:29:36 +0000395 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000396
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000397 MatchLen = FullMatch.size();
398 return FullMatch.data()-Buffer.data();
Chris Lattner52870082009-09-24 21:47:32 +0000399}
400
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000401unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
402 const StringMap<StringRef> &VariableTable) const {
403 // Just compute the number of matching characters. For regular expressions, we
404 // just compare against the regex itself and hope for the best.
405 //
406 // FIXME: One easy improvement here is have the regex lib generate a single
407 // example regular expression which matches, and use that as the example
408 // string.
409 StringRef ExampleString(FixedStr);
410 if (ExampleString.empty())
411 ExampleString = RegExStr;
412
Daniel Dunbar0806f9f2010-01-30 00:24:06 +0000413 // Only compare up to the first line in the buffer, or the string size.
414 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
415 BufferPrefix = BufferPrefix.split('\n').first;
416 return BufferPrefix.edit_distance(ExampleString);
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000417}
418
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000419void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
420 const StringMap<StringRef> &VariableTable) const{
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000421 // If this was a regular expression using variables, print the current
422 // variable values.
423 if (!VariableUses.empty()) {
424 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000425 SmallString<256> Msg;
426 raw_svector_ostream OS(Msg);
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000427 StringRef Var = VariableUses[i].first;
428 if (Var[0] == '@') {
429 std::string Value;
430 if (EvaluateExpression(Var, Value)) {
431 OS << "with expression \"";
432 OS.write_escaped(Var) << "\" equal to \"";
433 OS.write_escaped(Value) << "\"";
434 } else {
435 OS << "uses incorrect expression \"";
436 OS.write_escaped(Var) << "\"";
437 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000438 } else {
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000439 StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
440
441 // Check for undefined variable references.
442 if (it == VariableTable.end()) {
443 OS << "uses undefined variable \"";
444 OS.write_escaped(Var) << "\"";
445 } else {
446 OS << "with variable \"";
447 OS.write_escaped(Var) << "\" equal to \"";
448 OS.write_escaped(it->second) << "\"";
449 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000450 }
451
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000452 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
453 OS.str());
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000454 }
455 }
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000456
457 // Attempt to find the closest/best fuzzy match. Usually an error happens
458 // because some string in the output didn't exactly match. In these cases, we
459 // would like to show the user a best guess at what "should have" matched, to
460 // save them having to actually check the input manually.
461 size_t NumLinesForward = 0;
462 size_t Best = StringRef::npos;
463 double BestQuality = 0;
464
465 // Use an arbitrary 4k limit on how far we will search.
Dan Gohmane3a1e502010-01-29 21:57:46 +0000466 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000467 if (Buffer[i] == '\n')
468 ++NumLinesForward;
469
Dan Gohmand8a55412010-01-29 21:55:16 +0000470 // Patterns have leading whitespace stripped, so skip whitespace when
471 // looking for something which looks like a pattern.
472 if (Buffer[i] == ' ' || Buffer[i] == '\t')
473 continue;
474
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000475 // Compute the "quality" of this match as an arbitrary combination of the
476 // match distance and the number of lines skipped to get to this match.
477 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
478 double Quality = Distance + (NumLinesForward / 100.);
479
480 if (Quality < BestQuality || Best == StringRef::npos) {
481 Best = i;
482 BestQuality = Quality;
483 }
484 }
485
Daniel Dunbar7a68e0d2010-03-19 18:07:43 +0000486 // Print the "possible intended match here" line if we found something
487 // reasonable and not equal to what we showed in the "scanning from here"
488 // line.
489 if (Best && Best != StringRef::npos && BestQuality < 50) {
490 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000491 SourceMgr::DK_Note, "possible intended match here");
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000492
493 // FIXME: If we wanted to be really friendly we would show why the match
494 // failed, as it can be hard to spot simple one character differences.
495 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000496}
Chris Lattnera29703e2009-09-24 20:39:13 +0000497
498//===----------------------------------------------------------------------===//
499// Check Strings.
500//===----------------------------------------------------------------------===//
Chris Lattner9fc66782009-09-24 20:25:55 +0000501
502/// CheckString - This is a check that we found in the input file.
503struct CheckString {
504 /// Pat - The pattern to match.
505 Pattern Pat;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000506
Chris Lattner207e1bc2009-08-15 17:41:04 +0000507 /// Loc - The location in the match file that the check string was specified.
508 SMLoc Loc;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000509
Chris Lattner5dafafd2009-08-15 18:32:21 +0000510 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
511 /// to a CHECK: directive.
512 bool IsCheckNext;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000513
Chris Lattnerf15380b2009-09-20 22:35:26 +0000514 /// NotStrings - These are all of the strings that are disallowed from
515 /// occurring between this match string and the previous one (or start of
516 /// file).
Chris Lattnera29703e2009-09-24 20:39:13 +0000517 std::vector<std::pair<SMLoc, Pattern> > NotStrings;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000518
Chris Lattner9fc66782009-09-24 20:25:55 +0000519 CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
520 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
Chris Lattner207e1bc2009-08-15 17:41:04 +0000521};
522
Chris Lattneradea46e2009-09-24 20:45:07 +0000523/// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
524/// memory buffer, free it, and return a new one.
525static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
Chris Lattner4c842dd2010-04-05 22:42:30 +0000526 SmallString<128> NewFile;
Chris Lattneradea46e2009-09-24 20:45:07 +0000527 NewFile.reserve(MB->getBufferSize());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000528
Chris Lattneradea46e2009-09-24 20:45:07 +0000529 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
530 Ptr != End; ++Ptr) {
NAKAMURA Takumi9f6e03f2010-11-14 03:28:22 +0000531 // Eliminate trailing dosish \r.
532 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
533 continue;
534 }
535
Dmitri Gribenko9d227af2012-09-21 15:26:34 +0000536 // If current char is not a horizontal whitespace, dump it to output as is.
Chris Lattneradea46e2009-09-24 20:45:07 +0000537 if (*Ptr != ' ' && *Ptr != '\t') {
538 NewFile.push_back(*Ptr);
539 continue;
540 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000541
Chris Lattneradea46e2009-09-24 20:45:07 +0000542 // Otherwise, add one space and advance over neighboring space.
543 NewFile.push_back(' ');
544 while (Ptr+1 != End &&
545 (Ptr[1] == ' ' || Ptr[1] == '\t'))
546 ++Ptr;
547 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000548
Chris Lattneradea46e2009-09-24 20:45:07 +0000549 // Free the old buffer and return a new one.
550 MemoryBuffer *MB2 =
Chris Lattner4c842dd2010-04-05 22:42:30 +0000551 MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000552
Chris Lattneradea46e2009-09-24 20:45:07 +0000553 delete MB;
554 return MB2;
555}
556
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000557
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000558/// ReadCheckFile - Read the check file, which specifies the sequence of
559/// expected strings. The strings are added to the CheckStrings vector.
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +0000560/// Returns true in case of an error, false otherwise.
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000561static bool ReadCheckFile(SourceMgr &SM,
Chris Lattner207e1bc2009-08-15 17:41:04 +0000562 std::vector<CheckString> &CheckStrings) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000563 OwningPtr<MemoryBuffer> File;
564 if (error_code ec =
565 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) {
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000566 errs() << "Could not open check file '" << CheckFilename << "': "
Michael J. Spencer333fb042010-12-09 17:36:48 +0000567 << ec.message() << '\n';
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000568 return true;
569 }
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000570 MemoryBuffer *F = File.take();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000571
Chris Lattneradea46e2009-09-24 20:45:07 +0000572 // If we want to canonicalize whitespace, strip excess whitespace from the
573 // buffer containing the CHECK lines.
574 if (!NoCanonicalizeWhiteSpace)
575 F = CanonicalizeInputFile(F);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000576
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000577 SM.AddNewSourceBuffer(F, SMLoc());
578
Chris Lattnerd7e25052009-08-15 18:00:42 +0000579 // Find all instances of CheckPrefix followed by : in the file.
Chris Lattner96077032009-09-20 22:11:44 +0000580 StringRef Buffer = F->getBuffer();
Chris Lattnera29703e2009-09-24 20:39:13 +0000581 std::vector<std::pair<SMLoc, Pattern> > NotMatches;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000582
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +0000583 // LineNumber keeps track of the line on which CheckPrefix instances are
584 // found.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000585 unsigned LineNumber = 1;
586
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000587 while (1) {
588 // See if Prefix occurs in the memory buffer.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000589 size_t PrefixLoc = Buffer.find(CheckPrefix);
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000590 // If we didn't find a match, we're done.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000591 if (PrefixLoc == StringRef::npos)
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000592 break;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000593
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000594 LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
595
596 Buffer = Buffer.substr(PrefixLoc);
597
Chris Lattner96077032009-09-20 22:11:44 +0000598 const char *CheckPrefixStart = Buffer.data();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000599
Chris Lattner5dafafd2009-08-15 18:32:21 +0000600 // When we find a check prefix, keep track of whether we find CHECK: or
601 // CHECK-NEXT:
Chris Lattnerf15380b2009-09-20 22:35:26 +0000602 bool IsCheckNext = false, IsCheckNot = false;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000603
Chris Lattnerd7e25052009-08-15 18:00:42 +0000604 // Verify that the : is present after the prefix.
Chris Lattner96077032009-09-20 22:11:44 +0000605 if (Buffer[CheckPrefix.size()] == ':') {
606 Buffer = Buffer.substr(CheckPrefix.size()+1);
Chris Lattner96077032009-09-20 22:11:44 +0000607 } else if (Buffer.size() > CheckPrefix.size()+6 &&
608 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Benjamin Kramer30ce40e2012-09-18 20:51:39 +0000609 Buffer = Buffer.substr(CheckPrefix.size()+6);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000610 IsCheckNext = true;
Chris Lattnerf15380b2009-09-20 22:35:26 +0000611 } else if (Buffer.size() > CheckPrefix.size()+5 &&
612 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
Benjamin Kramer30ce40e2012-09-18 20:51:39 +0000613 Buffer = Buffer.substr(CheckPrefix.size()+5);
Chris Lattnerf15380b2009-09-20 22:35:26 +0000614 IsCheckNot = true;
Chris Lattner5dafafd2009-08-15 18:32:21 +0000615 } else {
Chris Lattner96077032009-09-20 22:11:44 +0000616 Buffer = Buffer.substr(1);
Chris Lattnerd7e25052009-08-15 18:00:42 +0000617 continue;
618 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000619
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000620 // Okay, we found the prefix, yay. Remember the rest of the line, but
621 // ignore leading and trailing whitespace.
Chris Lattnerf15380b2009-09-20 22:35:26 +0000622 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000623
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000624 // Scan ahead to the end of line.
Chris Lattner96077032009-09-20 22:11:44 +0000625 size_t EOL = Buffer.find_first_of("\n\r");
Chris Lattnera29703e2009-09-24 20:39:13 +0000626
Dan Gohmane5463432010-01-29 21:53:18 +0000627 // Remember the location of the start of the pattern, for diagnostics.
628 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
629
Chris Lattnera29703e2009-09-24 20:39:13 +0000630 // Parse the pattern.
631 Pattern P;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000632 if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000633 return true;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000634
Chris Lattnera29703e2009-09-24 20:39:13 +0000635 Buffer = Buffer.substr(EOL);
636
Chris Lattner5dafafd2009-08-15 18:32:21 +0000637 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
638 if (IsCheckNext && CheckStrings.empty()) {
639 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000640 SourceMgr::DK_Error,
Chris Lattner5dafafd2009-08-15 18:32:21 +0000641 "found '"+CheckPrefix+"-NEXT:' without previous '"+
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000642 CheckPrefix+ ": line");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000643 return true;
644 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000645
Chris Lattnera29703e2009-09-24 20:39:13 +0000646 // Handle CHECK-NOT.
647 if (IsCheckNot) {
648 NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
649 P));
650 continue;
651 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000652
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000653 // Okay, add the string we captured to the output vector and move on.
Chris Lattner9fc66782009-09-24 20:25:55 +0000654 CheckStrings.push_back(CheckString(P,
Dan Gohmane5463432010-01-29 21:53:18 +0000655 PatternLoc,
Chris Lattner5dafafd2009-08-15 18:32:21 +0000656 IsCheckNext));
Chris Lattnerf15380b2009-09-20 22:35:26 +0000657 std::swap(NotMatches, CheckStrings.back().NotStrings);
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000658 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000659
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000660 // Add an EOF pattern for any trailing CHECK-NOTs.
661 if (!NotMatches.empty()) {
662 CheckStrings.push_back(CheckString(Pattern(true),
663 SMLoc::getFromPointer(Buffer.data()),
664 false));
665 std::swap(NotMatches, CheckStrings.back().NotStrings);
666 }
667
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000668 if (CheckStrings.empty()) {
Chris Lattnerd7e25052009-08-15 18:00:42 +0000669 errs() << "error: no check strings found with prefix '" << CheckPrefix
670 << ":'\n";
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000671 return true;
672 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000673
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000674 return false;
675}
676
Chris Lattner5dafafd2009-08-15 18:32:21 +0000677static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000678 StringRef Buffer,
679 StringMap<StringRef> &VariableTable) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000680 // Otherwise, we have an error, emit an error message.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000681 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
682 "expected string not found in input");
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000683
Chris Lattner5dafafd2009-08-15 18:32:21 +0000684 // Print the "scanning from here" line. If the current position is at the
685 // end of a line, advance to the start of the next line.
Chris Lattner96077032009-09-20 22:11:44 +0000686 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000687
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000688 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
689 "scanning from here");
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000690
691 // Allow the pattern to print additional information if desired.
692 CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000693}
694
Chris Lattner3711b7a2009-09-20 22:42:44 +0000695/// CountNumNewlinesBetween - Count the number of newlines in the specified
696/// range.
697static unsigned CountNumNewlinesBetween(StringRef Range) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000698 unsigned NumNewLines = 0;
Chris Lattner3711b7a2009-09-20 22:42:44 +0000699 while (1) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000700 // Scan for newline.
Chris Lattner3711b7a2009-09-20 22:42:44 +0000701 Range = Range.substr(Range.find_first_of("\n\r"));
702 if (Range.empty()) return NumNewLines;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000703
Chris Lattner5dafafd2009-08-15 18:32:21 +0000704 ++NumNewLines;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000705
Chris Lattner5dafafd2009-08-15 18:32:21 +0000706 // Handle \n\r and \r\n as a single newline.
Chris Lattner3711b7a2009-09-20 22:42:44 +0000707 if (Range.size() > 1 &&
708 (Range[1] == '\n' || Range[1] == '\r') &&
709 (Range[0] != Range[1]))
710 Range = Range.substr(1);
711 Range = Range.substr(1);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000712 }
Chris Lattner5dafafd2009-08-15 18:32:21 +0000713}
714
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000715int main(int argc, char **argv) {
716 sys::PrintStackTraceOnErrorSignal();
717 PrettyStackTraceProgram X(argc, argv);
718 cl::ParseCommandLineOptions(argc, argv);
719
720 SourceMgr SM;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000721
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000722 // Read the expected strings from the check file.
Chris Lattner207e1bc2009-08-15 17:41:04 +0000723 std::vector<CheckString> CheckStrings;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000724 if (ReadCheckFile(SM, CheckStrings))
725 return 2;
726
727 // Open the file to check and add it to SourceMgr.
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000728 OwningPtr<MemoryBuffer> File;
729 if (error_code ec =
730 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000731 errs() << "Could not open input file '" << InputFilename << "': "
Michael J. Spencer333fb042010-12-09 17:36:48 +0000732 << ec.message() << '\n';
Eli Bendersky7f8e76f2012-11-30 13:51:33 +0000733 return 2;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000734 }
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000735 MemoryBuffer *F = File.take();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000736
Chris Lattner1aac1862011-02-09 16:46:02 +0000737 if (F->getBufferSize() == 0) {
738 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
Eli Bendersky7f8e76f2012-11-30 13:51:33 +0000739 return 2;
Chris Lattner1aac1862011-02-09 16:46:02 +0000740 }
741
Chris Lattner88a7e9e2009-07-11 18:58:15 +0000742 // Remove duplicate spaces in the input file if requested.
743 if (!NoCanonicalizeWhiteSpace)
744 F = CanonicalizeInputFile(F);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000745
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000746 SM.AddNewSourceBuffer(F, SMLoc());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000747
Chris Lattnereec96952009-09-27 07:56:52 +0000748 /// VariableTable - This holds all the current filecheck variables.
749 StringMap<StringRef> VariableTable;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000750
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000751 // Check that we have all of the expected strings, in order, in the input
752 // file.
Chris Lattner96077032009-09-20 22:11:44 +0000753 StringRef Buffer = F->getBuffer();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000754
Chris Lattnerf15380b2009-09-20 22:35:26 +0000755 const char *LastMatch = Buffer.data();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000756
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000757 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
Chris Lattner207e1bc2009-08-15 17:41:04 +0000758 const CheckString &CheckStr = CheckStrings[StrNo];
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000759
Chris Lattner96077032009-09-20 22:11:44 +0000760 StringRef SearchFrom = Buffer;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000761
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000762 // Find StrNo in the file.
Chris Lattner9fc66782009-09-24 20:25:55 +0000763 size_t MatchLen = 0;
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000764 size_t MatchPos = CheckStr.Pat.Match(Buffer, MatchLen, VariableTable);
765 Buffer = Buffer.substr(MatchPos);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000766
Chris Lattner5dafafd2009-08-15 18:32:21 +0000767 // If we didn't find a match, reject the input.
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000768 if (MatchPos == StringRef::npos) {
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000769 PrintCheckFailed(SM, CheckStr, SearchFrom, VariableTable);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000770 return 1;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000771 }
Chris Lattner3711b7a2009-09-20 22:42:44 +0000772
773 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
774
Chris Lattner5dafafd2009-08-15 18:32:21 +0000775 // If this check is a "CHECK-NEXT", verify that the previous match was on
776 // the previous line (i.e. that there is one newline between them).
777 if (CheckStr.IsCheckNext) {
778 // Count the number of newlines between the previous match and this one.
Chris Lattnerf15380b2009-09-20 22:35:26 +0000779 assert(LastMatch != F->getBufferStart() &&
780 "CHECK-NEXT can't be the first check in a file");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000781
Chris Lattner3711b7a2009-09-20 22:42:44 +0000782 unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000783 if (NumNewLines == 0) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000784 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
785 CheckPrefix+"-NEXT: is on the same line as previous match");
Chris Lattner96077032009-09-20 22:11:44 +0000786 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000787 SourceMgr::DK_Note, "'next' match was here");
788 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
789 "previous match was here");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000790 return 1;
791 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000792
Chris Lattner5dafafd2009-08-15 18:32:21 +0000793 if (NumNewLines != 1) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000794 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+
795 "-NEXT: is not on the line after the previous match");
Chris Lattner96077032009-09-20 22:11:44 +0000796 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000797 SourceMgr::DK_Note, "'next' match was here");
798 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
799 "previous match was here");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000800 return 1;
801 }
802 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000803
Chris Lattnerf15380b2009-09-20 22:35:26 +0000804 // If this match had "not strings", verify that they don't exist in the
805 // skipped region.
Chris Lattnereec96952009-09-27 07:56:52 +0000806 for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size();
807 ChunkNo != e; ++ChunkNo) {
Chris Lattnera29703e2009-09-24 20:39:13 +0000808 size_t MatchLen = 0;
Chris Lattnereec96952009-09-27 07:56:52 +0000809 size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion,
810 MatchLen,
811 VariableTable);
Chris Lattnerf15380b2009-09-20 22:35:26 +0000812 if (Pos == StringRef::npos) continue;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000813
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000814 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos), SourceMgr::DK_Error,
815 CheckPrefix+"-NOT: string occurred!");
816 SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first, SourceMgr::DK_Note,
817 CheckPrefix+"-NOT: pattern specified here");
Chris Lattnerf15380b2009-09-20 22:35:26 +0000818 return 1;
819 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000820
Chris Lattner5dafafd2009-08-15 18:32:21 +0000821
Chris Lattner81115762009-09-21 02:30:42 +0000822 // Otherwise, everything is good. Step over the matched text and remember
823 // the position after the match as the end of the last match.
Chris Lattner9fc66782009-09-24 20:25:55 +0000824 Buffer = Buffer.substr(MatchLen);
Chris Lattner81115762009-09-21 02:30:42 +0000825 LastMatch = Buffer.data();
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000826 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000827
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000828 return 0;
829}