blob: 0dc8432dc91183e98b483e117d992d0d118ae159 [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
Alexander Kornienko70a870a2012-11-14 21:07:37 +000086 bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000087
Chris Lattner9fc66782009-09-24 20:25:55 +000088 /// Match - Match the pattern string against the input buffer Buffer. This
89 /// returns the position that is matched or npos if there is no match. If
90 /// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattnereec96952009-09-27 07:56:52 +000091 ///
92 /// The VariableTable StringMap provides the current values of filecheck
93 /// variables and is updated if this match defines new values.
94 size_t Match(StringRef Buffer, size_t &MatchLen,
95 StringMap<StringRef> &VariableTable) const;
Daniel Dunbarfafe93c2009-11-22 22:08:06 +000096
97 /// PrintFailureInfo - Print additional information about a failure to match
98 /// involving this pattern.
99 void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
100 const StringMap<StringRef> &VariableTable) const;
101
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000102private:
Chris Lattnereec96952009-09-27 07:56:52 +0000103 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
104 bool AddRegExToRegEx(StringRef RegExStr, unsigned &CurParen, SourceMgr &SM);
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000105
106 /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
107 /// matching this pattern at the start of \arg Buffer; a distance of zero
108 /// should correspond to a perfect match.
109 unsigned ComputeMatchDistance(StringRef Buffer,
110 const StringMap<StringRef> &VariableTable) const;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000111
112 /// \brief Evaluates expression and stores the result to \p Value.
113 /// \return true on success. false when the expression has invalid syntax.
114 bool EvaluateExpression(StringRef Expr, std::string &Value) const;
Chris Lattner9fc66782009-09-24 20:25:55 +0000115};
116
Chris Lattnereec96952009-09-27 07:56:52 +0000117
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000118bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
119 unsigned LineNumber) {
120 this->LineNumber = LineNumber;
Chris Lattner94638f02009-09-25 17:29:36 +0000121 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000122
Chris Lattnera29703e2009-09-24 20:39:13 +0000123 // Ignore trailing whitespace.
124 while (!PatternStr.empty() &&
125 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
126 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000127
Chris Lattnera29703e2009-09-24 20:39:13 +0000128 // Check that there is something on the line.
129 if (PatternStr.empty()) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000130 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
131 "found empty check string with prefix '" +
132 CheckPrefix+":'");
Chris Lattnera29703e2009-09-24 20:39:13 +0000133 return true;
134 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000135
Chris Lattner2702e6a2009-09-25 17:09:12 +0000136 // Check to see if this is a fixed string, or if it has regex pieces.
Ted Kremenek4f505172012-09-08 04:32:13 +0000137 if (PatternStr.size() < 2 ||
Chris Lattnereec96952009-09-27 07:56:52 +0000138 (PatternStr.find("{{") == StringRef::npos &&
139 PatternStr.find("[[") == StringRef::npos)) {
Chris Lattner2702e6a2009-09-25 17:09:12 +0000140 FixedStr = PatternStr;
141 return false;
142 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000143
Chris Lattnereec96952009-09-27 07:56:52 +0000144 // Paren value #0 is for the fully matched string. Any new parenthesized
Chris Lattner13a38c42011-04-09 06:18:02 +0000145 // values add from there.
Chris Lattnereec96952009-09-27 07:56:52 +0000146 unsigned CurParen = 1;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000147
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000148 // Otherwise, there is at least one regex piece. Build up the regex pattern
149 // by escaping scary characters in fixed strings, building up one big regex.
Chris Lattner52870082009-09-24 21:47:32 +0000150 while (!PatternStr.empty()) {
Chris Lattnereec96952009-09-27 07:56:52 +0000151 // RegEx matches.
Chris Lattner13a38c42011-04-09 06:18:02 +0000152 if (PatternStr.startswith("{{")) {
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000153
Chris Lattnereec96952009-09-27 07:56:52 +0000154 // Otherwise, this is the start of a regex match. Scan for the }}.
155 size_t End = PatternStr.find("}}");
156 if (End == StringRef::npos) {
157 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000158 SourceMgr::DK_Error,
159 "found start of regex string with no end '}}'");
Chris Lattnereec96952009-09-27 07:56:52 +0000160 return true;
161 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000162
Chris Lattner42e31df2011-04-09 06:37:03 +0000163 // Enclose {{}} patterns in parens just like [[]] even though we're not
164 // capturing the result for any purpose. This is required in case the
165 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
166 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
167 RegExStr += '(';
168 ++CurParen;
169
Chris Lattnereec96952009-09-27 07:56:52 +0000170 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
171 return true;
Chris Lattner42e31df2011-04-09 06:37:03 +0000172 RegExStr += ')';
Chris Lattner13a38c42011-04-09 06:18:02 +0000173
Chris Lattnereec96952009-09-27 07:56:52 +0000174 PatternStr = PatternStr.substr(End+2);
Chris Lattner52870082009-09-24 21:47:32 +0000175 continue;
176 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000177
Chris Lattnereec96952009-09-27 07:56:52 +0000178 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
179 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
180 // second form is [[foo]] which is a reference to foo. The variable name
Daniel Dunbar964ac012009-11-22 22:07:50 +0000181 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
Chris Lattnereec96952009-09-27 07:56:52 +0000182 // it. This is to catch some common errors.
Chris Lattner13a38c42011-04-09 06:18:02 +0000183 if (PatternStr.startswith("[[")) {
Chris Lattnereec96952009-09-27 07:56:52 +0000184 // Verify that it is terminated properly.
185 size_t End = PatternStr.find("]]");
186 if (End == StringRef::npos) {
187 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000188 SourceMgr::DK_Error,
189 "invalid named regex reference, no ]] found");
Chris Lattnereec96952009-09-27 07:56:52 +0000190 return true;
191 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000192
Chris Lattnereec96952009-09-27 07:56:52 +0000193 StringRef MatchStr = PatternStr.substr(2, End-2);
194 PatternStr = PatternStr.substr(End+2);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000195
Chris Lattnereec96952009-09-27 07:56:52 +0000196 // Get the regex name (e.g. "foo").
197 size_t NameEnd = MatchStr.find(':');
198 StringRef Name = MatchStr.substr(0, NameEnd);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000199
Chris Lattnereec96952009-09-27 07:56:52 +0000200 if (Name.empty()) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000201 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
202 "invalid name in named regex: empty name");
Chris Lattnereec96952009-09-27 07:56:52 +0000203 return true;
204 }
205
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000206 // Verify that the name/expression is well formed. FileCheck currently
207 // supports @LINE, @LINE+number, @LINE-number expressions. The check here
208 // is relaxed, more strict check is performed in \c EvaluateExpression.
209 bool IsExpression = false;
210 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
211 if (i == 0 && Name[i] == '@') {
212 if (NameEnd != StringRef::npos) {
213 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
214 SourceMgr::DK_Error,
215 "invalid name in named regex definition");
216 return true;
217 }
218 IsExpression = true;
219 continue;
220 }
221 if (Name[i] != '_' && !isalnum(Name[i]) &&
222 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
Chris Lattnereec96952009-09-27 07:56:52 +0000223 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000224 SourceMgr::DK_Error, "invalid name in named regex");
Chris Lattnereec96952009-09-27 07:56:52 +0000225 return true;
226 }
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000227 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000228
Chris Lattnereec96952009-09-27 07:56:52 +0000229 // Name can't start with a digit.
230 if (isdigit(Name[0])) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000231 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
232 "invalid name in named regex");
Chris Lattnereec96952009-09-27 07:56:52 +0000233 return true;
234 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000235
Chris Lattnereec96952009-09-27 07:56:52 +0000236 // Handle [[foo]].
237 if (NameEnd == StringRef::npos) {
238 VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
239 continue;
240 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000241
Chris Lattnereec96952009-09-27 07:56:52 +0000242 // Handle [[foo:.*]].
243 VariableDefs.push_back(std::make_pair(Name, CurParen));
244 RegExStr += '(';
245 ++CurParen;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000246
Chris Lattnereec96952009-09-27 07:56:52 +0000247 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
248 return true;
249
250 RegExStr += ')';
Chris Lattner52870082009-09-24 21:47:32 +0000251 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000252
Chris Lattnereec96952009-09-27 07:56:52 +0000253 // Handle fixed string matches.
254 // Find the end, which is the start of the next regex.
255 size_t FixedMatchEnd = PatternStr.find("{{");
256 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
257 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
258 PatternStr = PatternStr.substr(FixedMatchEnd);
Chris Lattner52870082009-09-24 21:47:32 +0000259 }
Chris Lattneradea46e2009-09-24 20:45:07 +0000260
Chris Lattnera29703e2009-09-24 20:39:13 +0000261 return false;
262}
263
Chris Lattnereec96952009-09-27 07:56:52 +0000264void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000265 // Add the characters from FixedStr to the regex, escaping as needed. This
266 // avoids "leaning toothpicks" in common patterns.
267 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
268 switch (FixedStr[i]) {
269 // These are the special characters matched in "p_ere_exp".
270 case '(':
271 case ')':
272 case '^':
273 case '$':
274 case '|':
275 case '*':
276 case '+':
277 case '?':
278 case '.':
279 case '[':
280 case '\\':
281 case '{':
Chris Lattnereec96952009-09-27 07:56:52 +0000282 TheStr += '\\';
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000283 // FALL THROUGH.
284 default:
Chris Lattnereec96952009-09-27 07:56:52 +0000285 TheStr += FixedStr[i];
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000286 break;
287 }
288 }
289}
290
Chris Lattnereec96952009-09-27 07:56:52 +0000291bool Pattern::AddRegExToRegEx(StringRef RegexStr, unsigned &CurParen,
292 SourceMgr &SM) {
293 Regex R(RegexStr);
294 std::string Error;
295 if (!R.isValid(Error)) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000296 SM.PrintMessage(SMLoc::getFromPointer(RegexStr.data()), SourceMgr::DK_Error,
297 "invalid regex: " + Error);
Chris Lattnereec96952009-09-27 07:56:52 +0000298 return true;
299 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000300
Chris Lattnereec96952009-09-27 07:56:52 +0000301 RegExStr += RegexStr.str();
302 CurParen += R.getNumMatches();
303 return false;
304}
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000305
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000306bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
307 // The only supported expression is @LINE([\+-]\d+)?
308 if (!Expr.startswith("@LINE"))
309 return false;
310 Expr = Expr.substr(StringRef("@LINE").size());
311 int Offset = 0;
312 if (!Expr.empty()) {
313 if (Expr[0] == '+')
314 Expr = Expr.substr(1);
315 else if (Expr[0] != '-')
316 return false;
317 if (Expr.getAsInteger(10, Offset))
318 return false;
319 }
320 Value = llvm::itostr(LineNumber + Offset);
321 return true;
322}
323
Chris Lattner52870082009-09-24 21:47:32 +0000324/// Match - Match the pattern string against the input buffer Buffer. This
325/// returns the position that is matched or npos if there is no match. If
326/// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattnereec96952009-09-27 07:56:52 +0000327size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
328 StringMap<StringRef> &VariableTable) const {
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000329 // If this is the EOF pattern, match it immediately.
330 if (MatchEOF) {
331 MatchLen = 0;
332 return Buffer.size();
333 }
334
Chris Lattner2702e6a2009-09-25 17:09:12 +0000335 // If this is a fixed string pattern, just match it now.
336 if (!FixedStr.empty()) {
337 MatchLen = FixedStr.size();
338 return Buffer.find(FixedStr);
339 }
Chris Lattnereec96952009-09-27 07:56:52 +0000340
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000341 // Regex match.
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000342
Chris Lattnereec96952009-09-27 07:56:52 +0000343 // If there are variable uses, we need to create a temporary string with the
344 // actual value.
345 StringRef RegExToMatch = RegExStr;
346 std::string TmpStr;
347 if (!VariableUses.empty()) {
348 TmpStr = RegExStr;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000349
Chris Lattnereec96952009-09-27 07:56:52 +0000350 unsigned InsertOffset = 0;
351 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
Chris Lattnereec96952009-09-27 07:56:52 +0000352 std::string Value;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000353
354 if (VariableUses[i].first[0] == '@') {
355 if (!EvaluateExpression(VariableUses[i].first, Value))
356 return StringRef::npos;
357 } else {
358 StringMap<StringRef>::iterator it =
359 VariableTable.find(VariableUses[i].first);
360 // If the variable is undefined, return an error.
361 if (it == VariableTable.end())
362 return StringRef::npos;
363
364 // Look up the value and escape it so that we can plop it into the regex.
365 AddFixedStringToRegEx(it->second, Value);
366 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000367
Chris Lattnereec96952009-09-27 07:56:52 +0000368 // Plop it into the regex at the adjusted offset.
369 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
370 Value.begin(), Value.end());
371 InsertOffset += Value.size();
372 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000373
Chris Lattnereec96952009-09-27 07:56:52 +0000374 // Match the newly constructed regex.
375 RegExToMatch = TmpStr;
376 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000377
378
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000379 SmallVector<StringRef, 4> MatchInfo;
Chris Lattnereec96952009-09-27 07:56:52 +0000380 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000381 return StringRef::npos;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000382
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000383 // Successful regex match.
384 assert(!MatchInfo.empty() && "Didn't get any match");
385 StringRef FullMatch = MatchInfo[0];
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000386
Chris Lattnereec96952009-09-27 07:56:52 +0000387 // If this defines any variables, remember their values.
388 for (unsigned i = 0, e = VariableDefs.size(); i != e; ++i) {
389 assert(VariableDefs[i].second < MatchInfo.size() &&
390 "Internal paren error");
391 VariableTable[VariableDefs[i].first] = MatchInfo[VariableDefs[i].second];
Chris Lattner94638f02009-09-25 17:29:36 +0000392 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000393
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000394 MatchLen = FullMatch.size();
395 return FullMatch.data()-Buffer.data();
Chris Lattner52870082009-09-24 21:47:32 +0000396}
397
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000398unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
399 const StringMap<StringRef> &VariableTable) const {
400 // Just compute the number of matching characters. For regular expressions, we
401 // just compare against the regex itself and hope for the best.
402 //
403 // FIXME: One easy improvement here is have the regex lib generate a single
404 // example regular expression which matches, and use that as the example
405 // string.
406 StringRef ExampleString(FixedStr);
407 if (ExampleString.empty())
408 ExampleString = RegExStr;
409
Daniel Dunbar0806f9f2010-01-30 00:24:06 +0000410 // Only compare up to the first line in the buffer, or the string size.
411 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
412 BufferPrefix = BufferPrefix.split('\n').first;
413 return BufferPrefix.edit_distance(ExampleString);
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000414}
415
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000416void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
417 const StringMap<StringRef> &VariableTable) const{
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000418 // If this was a regular expression using variables, print the current
419 // variable values.
420 if (!VariableUses.empty()) {
421 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000422 SmallString<256> Msg;
423 raw_svector_ostream OS(Msg);
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000424 StringRef Var = VariableUses[i].first;
425 if (Var[0] == '@') {
426 std::string Value;
427 if (EvaluateExpression(Var, Value)) {
428 OS << "with expression \"";
429 OS.write_escaped(Var) << "\" equal to \"";
430 OS.write_escaped(Value) << "\"";
431 } else {
432 OS << "uses incorrect expression \"";
433 OS.write_escaped(Var) << "\"";
434 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000435 } else {
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000436 StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
437
438 // Check for undefined variable references.
439 if (it == VariableTable.end()) {
440 OS << "uses undefined variable \"";
441 OS.write_escaped(Var) << "\"";
442 } else {
443 OS << "with variable \"";
444 OS.write_escaped(Var) << "\" equal to \"";
445 OS.write_escaped(it->second) << "\"";
446 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000447 }
448
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000449 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
450 OS.str());
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000451 }
452 }
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000453
454 // Attempt to find the closest/best fuzzy match. Usually an error happens
455 // because some string in the output didn't exactly match. In these cases, we
456 // would like to show the user a best guess at what "should have" matched, to
457 // save them having to actually check the input manually.
458 size_t NumLinesForward = 0;
459 size_t Best = StringRef::npos;
460 double BestQuality = 0;
461
462 // Use an arbitrary 4k limit on how far we will search.
Dan Gohmane3a1e502010-01-29 21:57:46 +0000463 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000464 if (Buffer[i] == '\n')
465 ++NumLinesForward;
466
Dan Gohmand8a55412010-01-29 21:55:16 +0000467 // Patterns have leading whitespace stripped, so skip whitespace when
468 // looking for something which looks like a pattern.
469 if (Buffer[i] == ' ' || Buffer[i] == '\t')
470 continue;
471
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000472 // Compute the "quality" of this match as an arbitrary combination of the
473 // match distance and the number of lines skipped to get to this match.
474 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
475 double Quality = Distance + (NumLinesForward / 100.);
476
477 if (Quality < BestQuality || Best == StringRef::npos) {
478 Best = i;
479 BestQuality = Quality;
480 }
481 }
482
Daniel Dunbar7a68e0d2010-03-19 18:07:43 +0000483 // Print the "possible intended match here" line if we found something
484 // reasonable and not equal to what we showed in the "scanning from here"
485 // line.
486 if (Best && Best != StringRef::npos && BestQuality < 50) {
487 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000488 SourceMgr::DK_Note, "possible intended match here");
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000489
490 // FIXME: If we wanted to be really friendly we would show why the match
491 // failed, as it can be hard to spot simple one character differences.
492 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000493}
Chris Lattnera29703e2009-09-24 20:39:13 +0000494
495//===----------------------------------------------------------------------===//
496// Check Strings.
497//===----------------------------------------------------------------------===//
Chris Lattner9fc66782009-09-24 20:25:55 +0000498
499/// CheckString - This is a check that we found in the input file.
500struct CheckString {
501 /// Pat - The pattern to match.
502 Pattern Pat;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000503
Chris Lattner207e1bc2009-08-15 17:41:04 +0000504 /// Loc - The location in the match file that the check string was specified.
505 SMLoc Loc;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000506
Chris Lattner5dafafd2009-08-15 18:32:21 +0000507 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
508 /// to a CHECK: directive.
509 bool IsCheckNext;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000510
Chris Lattnerf15380b2009-09-20 22:35:26 +0000511 /// NotStrings - These are all of the strings that are disallowed from
512 /// occurring between this match string and the previous one (or start of
513 /// file).
Chris Lattnera29703e2009-09-24 20:39:13 +0000514 std::vector<std::pair<SMLoc, Pattern> > NotStrings;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000515
Chris Lattner9fc66782009-09-24 20:25:55 +0000516 CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
517 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
Chris Lattner207e1bc2009-08-15 17:41:04 +0000518};
519
Chris Lattneradea46e2009-09-24 20:45:07 +0000520/// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
521/// memory buffer, free it, and return a new one.
522static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
Chris Lattner4c842dd2010-04-05 22:42:30 +0000523 SmallString<128> NewFile;
Chris Lattneradea46e2009-09-24 20:45:07 +0000524 NewFile.reserve(MB->getBufferSize());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000525
Chris Lattneradea46e2009-09-24 20:45:07 +0000526 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
527 Ptr != End; ++Ptr) {
NAKAMURA Takumi9f6e03f2010-11-14 03:28:22 +0000528 // Eliminate trailing dosish \r.
529 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
530 continue;
531 }
532
Dmitri Gribenko9d227af2012-09-21 15:26:34 +0000533 // If current char is not a horizontal whitespace, dump it to output as is.
Chris Lattneradea46e2009-09-24 20:45:07 +0000534 if (*Ptr != ' ' && *Ptr != '\t') {
535 NewFile.push_back(*Ptr);
536 continue;
537 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000538
Chris Lattneradea46e2009-09-24 20:45:07 +0000539 // Otherwise, add one space and advance over neighboring space.
540 NewFile.push_back(' ');
541 while (Ptr+1 != End &&
542 (Ptr[1] == ' ' || Ptr[1] == '\t'))
543 ++Ptr;
544 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000545
Chris Lattneradea46e2009-09-24 20:45:07 +0000546 // Free the old buffer and return a new one.
547 MemoryBuffer *MB2 =
Chris Lattner4c842dd2010-04-05 22:42:30 +0000548 MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000549
Chris Lattneradea46e2009-09-24 20:45:07 +0000550 delete MB;
551 return MB2;
552}
553
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000554
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000555/// ReadCheckFile - Read the check file, which specifies the sequence of
556/// expected strings. The strings are added to the CheckStrings vector.
557static bool ReadCheckFile(SourceMgr &SM,
Chris Lattner207e1bc2009-08-15 17:41:04 +0000558 std::vector<CheckString> &CheckStrings) {
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000559 // Open the check file, and tell SourceMgr about it.
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000560 OwningPtr<MemoryBuffer> File;
561 if (error_code ec =
562 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) {
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000563 errs() << "Could not open check file '" << CheckFilename << "': "
Michael J. Spencer333fb042010-12-09 17:36:48 +0000564 << ec.message() << '\n';
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000565 return true;
566 }
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000567 MemoryBuffer *F = File.take();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000568
Chris Lattneradea46e2009-09-24 20:45:07 +0000569 // If we want to canonicalize whitespace, strip excess whitespace from the
570 // buffer containing the CHECK lines.
571 if (!NoCanonicalizeWhiteSpace)
572 F = CanonicalizeInputFile(F);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000573
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000574 SM.AddNewSourceBuffer(F, SMLoc());
575
Chris Lattnerd7e25052009-08-15 18:00:42 +0000576 // Find all instances of CheckPrefix followed by : in the file.
Chris Lattner96077032009-09-20 22:11:44 +0000577 StringRef Buffer = F->getBuffer();
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000578
Chris Lattnera29703e2009-09-24 20:39:13 +0000579 std::vector<std::pair<SMLoc, Pattern> > NotMatches;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000580
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000581 unsigned LineNumber = 1;
582
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000583 while (1) {
584 // See if Prefix occurs in the memory buffer.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000585 size_t PrefixLoc = Buffer.find(CheckPrefix);
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000586 // If we didn't find a match, we're done.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000587 if (PrefixLoc == StringRef::npos)
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000588 break;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000589
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000590 // Recalculate line number.
591 LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
592
593 Buffer = Buffer.substr(PrefixLoc);
594
Chris Lattner96077032009-09-20 22:11:44 +0000595 const char *CheckPrefixStart = Buffer.data();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000596
Chris Lattner5dafafd2009-08-15 18:32:21 +0000597 // When we find a check prefix, keep track of whether we find CHECK: or
598 // CHECK-NEXT:
Chris Lattnerf15380b2009-09-20 22:35:26 +0000599 bool IsCheckNext = false, IsCheckNot = false;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000600
Chris Lattnerd7e25052009-08-15 18:00:42 +0000601 // Verify that the : is present after the prefix.
Chris Lattner96077032009-09-20 22:11:44 +0000602 if (Buffer[CheckPrefix.size()] == ':') {
603 Buffer = Buffer.substr(CheckPrefix.size()+1);
Chris Lattner96077032009-09-20 22:11:44 +0000604 } else if (Buffer.size() > CheckPrefix.size()+6 &&
605 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Benjamin Kramer30ce40e2012-09-18 20:51:39 +0000606 Buffer = Buffer.substr(CheckPrefix.size()+6);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000607 IsCheckNext = true;
Chris Lattnerf15380b2009-09-20 22:35:26 +0000608 } else if (Buffer.size() > CheckPrefix.size()+5 &&
609 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
Benjamin Kramer30ce40e2012-09-18 20:51:39 +0000610 Buffer = Buffer.substr(CheckPrefix.size()+5);
Chris Lattnerf15380b2009-09-20 22:35:26 +0000611 IsCheckNot = true;
Chris Lattner5dafafd2009-08-15 18:32:21 +0000612 } else {
Chris Lattner96077032009-09-20 22:11:44 +0000613 Buffer = Buffer.substr(1);
Chris Lattnerd7e25052009-08-15 18:00:42 +0000614 continue;
615 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000616
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000617 // Okay, we found the prefix, yay. Remember the rest of the line, but
618 // ignore leading and trailing whitespace.
Chris Lattnerf15380b2009-09-20 22:35:26 +0000619 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000620
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000621 // Scan ahead to the end of line.
Chris Lattner96077032009-09-20 22:11:44 +0000622 size_t EOL = Buffer.find_first_of("\n\r");
Chris Lattnera29703e2009-09-24 20:39:13 +0000623
Dan Gohmane5463432010-01-29 21:53:18 +0000624 // Remember the location of the start of the pattern, for diagnostics.
625 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
626
Chris Lattnera29703e2009-09-24 20:39:13 +0000627 // Parse the pattern.
628 Pattern P;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000629 if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000630 return true;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000631
Chris Lattnera29703e2009-09-24 20:39:13 +0000632 Buffer = Buffer.substr(EOL);
633
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000634
Chris Lattner5dafafd2009-08-15 18:32:21 +0000635 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
636 if (IsCheckNext && CheckStrings.empty()) {
637 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000638 SourceMgr::DK_Error,
Chris Lattner5dafafd2009-08-15 18:32:21 +0000639 "found '"+CheckPrefix+"-NEXT:' without previous '"+
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000640 CheckPrefix+ ": line");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000641 return true;
642 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000643
Chris Lattnera29703e2009-09-24 20:39:13 +0000644 // Handle CHECK-NOT.
645 if (IsCheckNot) {
646 NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
647 P));
648 continue;
649 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000650
651
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000652 // Okay, add the string we captured to the output vector and move on.
Chris Lattner9fc66782009-09-24 20:25:55 +0000653 CheckStrings.push_back(CheckString(P,
Dan Gohmane5463432010-01-29 21:53:18 +0000654 PatternLoc,
Chris Lattner5dafafd2009-08-15 18:32:21 +0000655 IsCheckNext));
Chris Lattnerf15380b2009-09-20 22:35:26 +0000656 std::swap(NotMatches, CheckStrings.back().NotStrings);
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000657 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000658
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000659 // Add an EOF pattern for any trailing CHECK-NOTs.
660 if (!NotMatches.empty()) {
661 CheckStrings.push_back(CheckString(Pattern(true),
662 SMLoc::getFromPointer(Buffer.data()),
663 false));
664 std::swap(NotMatches, CheckStrings.back().NotStrings);
665 }
666
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000667 if (CheckStrings.empty()) {
Chris Lattnerd7e25052009-08-15 18:00:42 +0000668 errs() << "error: no check strings found with prefix '" << CheckPrefix
669 << ":'\n";
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000670 return true;
671 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000672
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000673 return false;
674}
675
Chris Lattner5dafafd2009-08-15 18:32:21 +0000676static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000677 StringRef Buffer,
678 StringMap<StringRef> &VariableTable) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000679 // Otherwise, we have an error, emit an error message.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000680 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
681 "expected string not found in input");
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000682
Chris Lattner5dafafd2009-08-15 18:32:21 +0000683 // Print the "scanning from here" line. If the current position is at the
684 // end of a line, advance to the start of the next line.
Chris Lattner96077032009-09-20 22:11:44 +0000685 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000686
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000687 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
688 "scanning from here");
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000689
690 // Allow the pattern to print additional information if desired.
691 CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000692}
693
Chris Lattner3711b7a2009-09-20 22:42:44 +0000694/// CountNumNewlinesBetween - Count the number of newlines in the specified
695/// range.
696static unsigned CountNumNewlinesBetween(StringRef Range) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000697 unsigned NumNewLines = 0;
Chris Lattner3711b7a2009-09-20 22:42:44 +0000698 while (1) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000699 // Scan for newline.
Chris Lattner3711b7a2009-09-20 22:42:44 +0000700 Range = Range.substr(Range.find_first_of("\n\r"));
701 if (Range.empty()) return NumNewLines;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000702
Chris Lattner5dafafd2009-08-15 18:32:21 +0000703 ++NumNewLines;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000704
Chris Lattner5dafafd2009-08-15 18:32:21 +0000705 // Handle \n\r and \r\n as a single newline.
Chris Lattner3711b7a2009-09-20 22:42:44 +0000706 if (Range.size() > 1 &&
707 (Range[1] == '\n' || Range[1] == '\r') &&
708 (Range[0] != Range[1]))
709 Range = Range.substr(1);
710 Range = Range.substr(1);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000711 }
Chris Lattner5dafafd2009-08-15 18:32:21 +0000712}
713
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000714int main(int argc, char **argv) {
715 sys::PrintStackTraceOnErrorSignal();
716 PrettyStackTraceProgram X(argc, argv);
717 cl::ParseCommandLineOptions(argc, argv);
718
719 SourceMgr SM;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000720
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000721 // Read the expected strings from the check file.
Chris Lattner207e1bc2009-08-15 17:41:04 +0000722 std::vector<CheckString> CheckStrings;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000723 if (ReadCheckFile(SM, CheckStrings))
724 return 2;
725
726 // Open the file to check and add it to SourceMgr.
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000727 OwningPtr<MemoryBuffer> File;
728 if (error_code ec =
729 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000730 errs() << "Could not open input file '" << InputFilename << "': "
Michael J. Spencer333fb042010-12-09 17:36:48 +0000731 << ec.message() << '\n';
Eli Bendersky7f8e76f2012-11-30 13:51:33 +0000732 return 2;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000733 }
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000734 MemoryBuffer *F = File.take();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000735
Chris Lattner1aac1862011-02-09 16:46:02 +0000736 if (F->getBufferSize() == 0) {
737 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
Eli Bendersky7f8e76f2012-11-30 13:51:33 +0000738 return 2;
Chris Lattner1aac1862011-02-09 16:46:02 +0000739 }
740
Chris Lattner88a7e9e2009-07-11 18:58:15 +0000741 // Remove duplicate spaces in the input file if requested.
742 if (!NoCanonicalizeWhiteSpace)
743 F = CanonicalizeInputFile(F);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000744
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000745 SM.AddNewSourceBuffer(F, SMLoc());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000746
Chris Lattnereec96952009-09-27 07:56:52 +0000747 /// VariableTable - This holds all the current filecheck variables.
748 StringMap<StringRef> VariableTable;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000749
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000750 // Check that we have all of the expected strings, in order, in the input
751 // file.
Chris Lattner96077032009-09-20 22:11:44 +0000752 StringRef Buffer = F->getBuffer();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000753
Chris Lattnerf15380b2009-09-20 22:35:26 +0000754 const char *LastMatch = Buffer.data();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000755
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000756 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
Chris Lattner207e1bc2009-08-15 17:41:04 +0000757 const CheckString &CheckStr = CheckStrings[StrNo];
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000758
Chris Lattner96077032009-09-20 22:11:44 +0000759 StringRef SearchFrom = Buffer;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000760
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000761 // Find StrNo in the file.
Chris Lattner9fc66782009-09-24 20:25:55 +0000762 size_t MatchLen = 0;
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000763 size_t MatchPos = CheckStr.Pat.Match(Buffer, MatchLen, VariableTable);
764 Buffer = Buffer.substr(MatchPos);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000765
Chris Lattner5dafafd2009-08-15 18:32:21 +0000766 // If we didn't find a match, reject the input.
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000767 if (MatchPos == StringRef::npos) {
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000768 PrintCheckFailed(SM, CheckStr, SearchFrom, VariableTable);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000769 return 1;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000770 }
Chris Lattner3711b7a2009-09-20 22:42:44 +0000771
772 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
773
Chris Lattner5dafafd2009-08-15 18:32:21 +0000774 // If this check is a "CHECK-NEXT", verify that the previous match was on
775 // the previous line (i.e. that there is one newline between them).
776 if (CheckStr.IsCheckNext) {
777 // Count the number of newlines between the previous match and this one.
Chris Lattnerf15380b2009-09-20 22:35:26 +0000778 assert(LastMatch != F->getBufferStart() &&
779 "CHECK-NEXT can't be the first check in a file");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000780
Chris Lattner3711b7a2009-09-20 22:42:44 +0000781 unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000782 if (NumNewLines == 0) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000783 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
784 CheckPrefix+"-NEXT: is on the same line as previous match");
Chris Lattner96077032009-09-20 22:11:44 +0000785 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000786 SourceMgr::DK_Note, "'next' match was here");
787 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
788 "previous match was here");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000789 return 1;
790 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000791
Chris Lattner5dafafd2009-08-15 18:32:21 +0000792 if (NumNewLines != 1) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000793 SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+
794 "-NEXT: is not on the line after the previous match");
Chris Lattner96077032009-09-20 22:11:44 +0000795 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000796 SourceMgr::DK_Note, "'next' match was here");
797 SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
798 "previous match was here");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000799 return 1;
800 }
801 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000802
Chris Lattnerf15380b2009-09-20 22:35:26 +0000803 // If this match had "not strings", verify that they don't exist in the
804 // skipped region.
Chris Lattnereec96952009-09-27 07:56:52 +0000805 for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size();
806 ChunkNo != e; ++ChunkNo) {
Chris Lattnera29703e2009-09-24 20:39:13 +0000807 size_t MatchLen = 0;
Chris Lattnereec96952009-09-27 07:56:52 +0000808 size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion,
809 MatchLen,
810 VariableTable);
Chris Lattnerf15380b2009-09-20 22:35:26 +0000811 if (Pos == StringRef::npos) continue;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000812
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000813 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos), SourceMgr::DK_Error,
814 CheckPrefix+"-NOT: string occurred!");
815 SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first, SourceMgr::DK_Note,
816 CheckPrefix+"-NOT: pattern specified here");
Chris Lattnerf15380b2009-09-20 22:35:26 +0000817 return 1;
818 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000819
Chris Lattner5dafafd2009-08-15 18:32:21 +0000820
Chris Lattner81115762009-09-21 02:30:42 +0000821 // Otherwise, everything is good. Step over the matched text and remember
822 // the position after the match as the end of the last match.
Chris Lattner9fc66782009-09-24 20:25:55 +0000823 Buffer = Buffer.substr(MatchLen);
Chris Lattner81115762009-09-21 02:30:42 +0000824 LastMatch = Buffer.data();
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000825 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000826
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000827 return 0;
828}