blob: b4d1f84859cef4bd3e1ef00494c4b5909ec6d372 [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
19#include "llvm/Support/CommandLine.h"
20#include "llvm/Support/MemoryBuffer.h"
21#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner52870082009-09-24 21:47:32 +000022#include "llvm/Support/Regex.h"
Chris Lattner81cb8ca2009-07-08 18:44:05 +000023#include "llvm/Support/SourceMgr.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/System/Signals.h"
Chris Lattnereec96952009-09-27 07:56:52 +000026#include "llvm/ADT/StringMap.h"
27#include <algorithm>
Chris Lattner81cb8ca2009-07-08 18:44:05 +000028using namespace llvm;
29
30static cl::opt<std::string>
31CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
32
33static cl::opt<std::string>
34InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
35 cl::init("-"), cl::value_desc("filename"));
36
37static cl::opt<std::string>
38CheckPrefix("check-prefix", cl::init("CHECK"),
39 cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
40
Chris Lattner88a7e9e2009-07-11 18:58:15 +000041static cl::opt<bool>
42NoCanonicalizeWhiteSpace("strict-whitespace",
43 cl::desc("Do not treat all horizontal whitespace as equivalent"));
44
Chris Lattnera29703e2009-09-24 20:39:13 +000045//===----------------------------------------------------------------------===//
46// Pattern Handling Code.
47//===----------------------------------------------------------------------===//
48
Chris Lattner9fc66782009-09-24 20:25:55 +000049class Pattern {
Chris Lattner94638f02009-09-25 17:29:36 +000050 SMLoc PatternLoc;
51
Chris Lattner5d6a05f2009-09-25 17:23:43 +000052 /// FixedStr - If non-empty, this pattern is a fixed string match with the
53 /// specified fixed string.
Chris Lattner2702e6a2009-09-25 17:09:12 +000054 StringRef FixedStr;
Chris Lattner5d6a05f2009-09-25 17:23:43 +000055
56 /// RegEx - If non-empty, this is a regex pattern.
57 std::string RegExStr;
Chris Lattnereec96952009-09-27 07:56:52 +000058
59 /// VariableUses - Entries in this vector map to uses of a variable in the
60 /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain
61 /// "foobaz" and we'll get an entry in this vector that tells us to insert the
62 /// value of bar at offset 3.
63 std::vector<std::pair<StringRef, unsigned> > VariableUses;
64
65 /// VariableDefs - Entries in this vector map to definitions of a variable in
66 /// the pattern, e.g. "foo[[bar:.*]]baz". In this case, the RegExStr will
67 /// contain "foo(.*)baz" and VariableDefs will contain the pair "bar",1. The
68 /// index indicates what parenthesized value captures the variable value.
69 std::vector<std::pair<StringRef, unsigned> > VariableDefs;
70
Chris Lattner9fc66782009-09-24 20:25:55 +000071public:
72
Chris Lattnera29703e2009-09-24 20:39:13 +000073 Pattern() { }
74
75 bool ParsePattern(StringRef PatternStr, SourceMgr &SM);
Chris Lattner9fc66782009-09-24 20:25:55 +000076
77 /// Match - Match the pattern string against the input buffer Buffer. This
78 /// returns the position that is matched or npos if there is no match. If
79 /// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattnereec96952009-09-27 07:56:52 +000080 ///
81 /// The VariableTable StringMap provides the current values of filecheck
82 /// variables and is updated if this match defines new values.
83 size_t Match(StringRef Buffer, size_t &MatchLen,
84 StringMap<StringRef> &VariableTable) const;
Chris Lattner5d6a05f2009-09-25 17:23:43 +000085
86private:
Chris Lattnereec96952009-09-27 07:56:52 +000087 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
88 bool AddRegExToRegEx(StringRef RegExStr, unsigned &CurParen, SourceMgr &SM);
Chris Lattner9fc66782009-09-24 20:25:55 +000089};
90
Chris Lattnereec96952009-09-27 07:56:52 +000091
Chris Lattnera29703e2009-09-24 20:39:13 +000092bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM) {
Chris Lattner94638f02009-09-25 17:29:36 +000093 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
94
Chris Lattnera29703e2009-09-24 20:39:13 +000095 // Ignore trailing whitespace.
96 while (!PatternStr.empty() &&
97 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
98 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
99
100 // Check that there is something on the line.
101 if (PatternStr.empty()) {
Chris Lattner94638f02009-09-25 17:29:36 +0000102 SM.PrintMessage(PatternLoc, "found empty check string with prefix '" +
103 CheckPrefix+":'", "error");
Chris Lattnera29703e2009-09-24 20:39:13 +0000104 return true;
105 }
Chris Lattner52870082009-09-24 21:47:32 +0000106
Chris Lattner2702e6a2009-09-25 17:09:12 +0000107 // Check to see if this is a fixed string, or if it has regex pieces.
Chris Lattnereec96952009-09-27 07:56:52 +0000108 if (PatternStr.size() < 2 ||
109 (PatternStr.find("{{") == StringRef::npos &&
110 PatternStr.find("[[") == StringRef::npos)) {
Chris Lattner2702e6a2009-09-25 17:09:12 +0000111 FixedStr = PatternStr;
112 return false;
113 }
114
Chris Lattnereec96952009-09-27 07:56:52 +0000115 // Paren value #0 is for the fully matched string. Any new parenthesized
116 // values add from their.
117 unsigned CurParen = 1;
118
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000119 // Otherwise, there is at least one regex piece. Build up the regex pattern
120 // by escaping scary characters in fixed strings, building up one big regex.
Chris Lattner52870082009-09-24 21:47:32 +0000121 while (!PatternStr.empty()) {
Chris Lattnereec96952009-09-27 07:56:52 +0000122 // RegEx matches.
123 if (PatternStr.size() >= 2 &&
124 PatternStr[0] == '{' && PatternStr[1] == '{') {
125
126 // Otherwise, this is the start of a regex match. Scan for the }}.
127 size_t End = PatternStr.find("}}");
128 if (End == StringRef::npos) {
129 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
130 "found start of regex string with no end '}}'", "error");
131 return true;
132 }
133
134 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
135 return true;
136 PatternStr = PatternStr.substr(End+2);
Chris Lattner52870082009-09-24 21:47:32 +0000137 continue;
138 }
139
Chris Lattnereec96952009-09-27 07:56:52 +0000140 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
141 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
142 // second form is [[foo]] which is a reference to foo. The variable name
143 // itself must be of the form "[a-zA-Z][0-9a-zA-Z]*", otherwise we reject
144 // it. This is to catch some common errors.
145 if (PatternStr.size() >= 2 &&
146 PatternStr[0] == '[' && PatternStr[1] == '[') {
147 // Verify that it is terminated properly.
148 size_t End = PatternStr.find("]]");
149 if (End == StringRef::npos) {
150 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
151 "invalid named regex reference, no ]] found", "error");
152 return true;
153 }
154
155 StringRef MatchStr = PatternStr.substr(2, End-2);
156 PatternStr = PatternStr.substr(End+2);
157
158 // Get the regex name (e.g. "foo").
159 size_t NameEnd = MatchStr.find(':');
160 StringRef Name = MatchStr.substr(0, NameEnd);
161
162 if (Name.empty()) {
163 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
164 "invalid name in named regex: empty name", "error");
165 return true;
166 }
167
168 // Verify that the name is well formed.
169 for (unsigned i = 0, e = Name.size(); i != e; ++i)
170 if ((Name[i] < 'a' || Name[i] > 'z') &&
171 (Name[i] < 'A' || Name[i] > 'Z') &&
172 (Name[i] < '0' || Name[i] > '9')) {
173 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
174 "invalid name in named regex", "error");
175 return true;
176 }
177
178 // Name can't start with a digit.
179 if (isdigit(Name[0])) {
180 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
181 "invalid name in named regex", "error");
182 return true;
183 }
184
185 // Handle [[foo]].
186 if (NameEnd == StringRef::npos) {
187 VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
188 continue;
189 }
190
191 // Handle [[foo:.*]].
192 VariableDefs.push_back(std::make_pair(Name, CurParen));
193 RegExStr += '(';
194 ++CurParen;
195
196 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
197 return true;
198
199 RegExStr += ')';
Chris Lattner52870082009-09-24 21:47:32 +0000200 }
201
Chris Lattnereec96952009-09-27 07:56:52 +0000202 // Handle fixed string matches.
203 // Find the end, which is the start of the next regex.
204 size_t FixedMatchEnd = PatternStr.find("{{");
205 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
206 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
207 PatternStr = PatternStr.substr(FixedMatchEnd);
208 continue;
Chris Lattner52870082009-09-24 21:47:32 +0000209 }
Chris Lattneradea46e2009-09-24 20:45:07 +0000210
Chris Lattnera29703e2009-09-24 20:39:13 +0000211 return false;
212}
213
Chris Lattnereec96952009-09-27 07:56:52 +0000214void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000215 // Add the characters from FixedStr to the regex, escaping as needed. This
216 // avoids "leaning toothpicks" in common patterns.
217 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
218 switch (FixedStr[i]) {
219 // These are the special characters matched in "p_ere_exp".
220 case '(':
221 case ')':
222 case '^':
223 case '$':
224 case '|':
225 case '*':
226 case '+':
227 case '?':
228 case '.':
229 case '[':
230 case '\\':
231 case '{':
Chris Lattnereec96952009-09-27 07:56:52 +0000232 TheStr += '\\';
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000233 // FALL THROUGH.
234 default:
Chris Lattnereec96952009-09-27 07:56:52 +0000235 TheStr += FixedStr[i];
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000236 break;
237 }
238 }
239}
240
Chris Lattnereec96952009-09-27 07:56:52 +0000241bool Pattern::AddRegExToRegEx(StringRef RegexStr, unsigned &CurParen,
242 SourceMgr &SM) {
243 Regex R(RegexStr);
244 std::string Error;
245 if (!R.isValid(Error)) {
246 SM.PrintMessage(SMLoc::getFromPointer(RegexStr.data()),
247 "invalid regex: " + Error, "error");
248 return true;
249 }
250
251 RegExStr += RegexStr.str();
252 CurParen += R.getNumMatches();
253 return false;
254}
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000255
Chris Lattner52870082009-09-24 21:47:32 +0000256/// Match - Match the pattern string against the input buffer Buffer. This
257/// returns the position that is matched or npos if there is no match. If
258/// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattnereec96952009-09-27 07:56:52 +0000259size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
260 StringMap<StringRef> &VariableTable) const {
Chris Lattner2702e6a2009-09-25 17:09:12 +0000261 // If this is a fixed string pattern, just match it now.
262 if (!FixedStr.empty()) {
263 MatchLen = FixedStr.size();
264 return Buffer.find(FixedStr);
265 }
Chris Lattnereec96952009-09-27 07:56:52 +0000266
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000267 // Regex match.
Chris Lattnereec96952009-09-27 07:56:52 +0000268
269 // If there are variable uses, we need to create a temporary string with the
270 // actual value.
271 StringRef RegExToMatch = RegExStr;
272 std::string TmpStr;
273 if (!VariableUses.empty()) {
274 TmpStr = RegExStr;
275
276 unsigned InsertOffset = 0;
277 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
278 // Look up the value and escape it so that we can plop it into the regex.
279 std::string Value;
280 AddFixedStringToRegEx(VariableTable[VariableUses[i].first], Value);
281
282 // Plop it into the regex at the adjusted offset.
283 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
284 Value.begin(), Value.end());
285 InsertOffset += Value.size();
286 }
287
288 // Match the newly constructed regex.
289 RegExToMatch = TmpStr;
290 }
291
292
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000293 SmallVector<StringRef, 4> MatchInfo;
Chris Lattnereec96952009-09-27 07:56:52 +0000294 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000295 return StringRef::npos;
Chris Lattner52870082009-09-24 21:47:32 +0000296
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000297 // Successful regex match.
298 assert(!MatchInfo.empty() && "Didn't get any match");
299 StringRef FullMatch = MatchInfo[0];
Chris Lattner52870082009-09-24 21:47:32 +0000300
Chris Lattnereec96952009-09-27 07:56:52 +0000301 // If this defines any variables, remember their values.
302 for (unsigned i = 0, e = VariableDefs.size(); i != e; ++i) {
303 assert(VariableDefs[i].second < MatchInfo.size() &&
304 "Internal paren error");
305 VariableTable[VariableDefs[i].first] = MatchInfo[VariableDefs[i].second];
Chris Lattner94638f02009-09-25 17:29:36 +0000306 }
Chris Lattner94638f02009-09-25 17:29:36 +0000307
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000308 MatchLen = FullMatch.size();
309 return FullMatch.data()-Buffer.data();
Chris Lattner52870082009-09-24 21:47:32 +0000310}
311
Chris Lattnera29703e2009-09-24 20:39:13 +0000312
313//===----------------------------------------------------------------------===//
314// Check Strings.
315//===----------------------------------------------------------------------===//
Chris Lattner9fc66782009-09-24 20:25:55 +0000316
317/// CheckString - This is a check that we found in the input file.
318struct CheckString {
319 /// Pat - The pattern to match.
320 Pattern Pat;
Chris Lattner207e1bc2009-08-15 17:41:04 +0000321
322 /// Loc - The location in the match file that the check string was specified.
323 SMLoc Loc;
324
Chris Lattner5dafafd2009-08-15 18:32:21 +0000325 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
326 /// to a CHECK: directive.
327 bool IsCheckNext;
328
Chris Lattnerf15380b2009-09-20 22:35:26 +0000329 /// NotStrings - These are all of the strings that are disallowed from
330 /// occurring between this match string and the previous one (or start of
331 /// file).
Chris Lattnera29703e2009-09-24 20:39:13 +0000332 std::vector<std::pair<SMLoc, Pattern> > NotStrings;
Chris Lattnerf15380b2009-09-20 22:35:26 +0000333
Chris Lattner9fc66782009-09-24 20:25:55 +0000334 CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
335 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
Chris Lattner207e1bc2009-08-15 17:41:04 +0000336};
337
Chris Lattneradea46e2009-09-24 20:45:07 +0000338/// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
339/// memory buffer, free it, and return a new one.
340static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
341 SmallVector<char, 16> NewFile;
342 NewFile.reserve(MB->getBufferSize());
343
344 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
345 Ptr != End; ++Ptr) {
346 // If C is not a horizontal whitespace, skip it.
347 if (*Ptr != ' ' && *Ptr != '\t') {
348 NewFile.push_back(*Ptr);
349 continue;
350 }
351
352 // Otherwise, add one space and advance over neighboring space.
353 NewFile.push_back(' ');
354 while (Ptr+1 != End &&
355 (Ptr[1] == ' ' || Ptr[1] == '\t'))
356 ++Ptr;
357 }
358
359 // Free the old buffer and return a new one.
360 MemoryBuffer *MB2 =
361 MemoryBuffer::getMemBufferCopy(NewFile.data(),
362 NewFile.data() + NewFile.size(),
363 MB->getBufferIdentifier());
364
365 delete MB;
366 return MB2;
367}
368
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000369
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000370/// ReadCheckFile - Read the check file, which specifies the sequence of
371/// expected strings. The strings are added to the CheckStrings vector.
372static bool ReadCheckFile(SourceMgr &SM,
Chris Lattner207e1bc2009-08-15 17:41:04 +0000373 std::vector<CheckString> &CheckStrings) {
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000374 // Open the check file, and tell SourceMgr about it.
375 std::string ErrorStr;
376 MemoryBuffer *F =
377 MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
378 if (F == 0) {
379 errs() << "Could not open check file '" << CheckFilename << "': "
380 << ErrorStr << '\n';
381 return true;
382 }
Chris Lattneradea46e2009-09-24 20:45:07 +0000383
384 // If we want to canonicalize whitespace, strip excess whitespace from the
385 // buffer containing the CHECK lines.
386 if (!NoCanonicalizeWhiteSpace)
387 F = CanonicalizeInputFile(F);
388
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000389 SM.AddNewSourceBuffer(F, SMLoc());
390
Chris Lattnerd7e25052009-08-15 18:00:42 +0000391 // Find all instances of CheckPrefix followed by : in the file.
Chris Lattner96077032009-09-20 22:11:44 +0000392 StringRef Buffer = F->getBuffer();
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000393
Chris Lattnera29703e2009-09-24 20:39:13 +0000394 std::vector<std::pair<SMLoc, Pattern> > NotMatches;
Chris Lattnerf15380b2009-09-20 22:35:26 +0000395
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000396 while (1) {
397 // See if Prefix occurs in the memory buffer.
Chris Lattner96077032009-09-20 22:11:44 +0000398 Buffer = Buffer.substr(Buffer.find(CheckPrefix));
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000399
400 // If we didn't find a match, we're done.
Chris Lattner96077032009-09-20 22:11:44 +0000401 if (Buffer.empty())
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000402 break;
403
Chris Lattner96077032009-09-20 22:11:44 +0000404 const char *CheckPrefixStart = Buffer.data();
Chris Lattner5dafafd2009-08-15 18:32:21 +0000405
406 // When we find a check prefix, keep track of whether we find CHECK: or
407 // CHECK-NEXT:
Chris Lattnerf15380b2009-09-20 22:35:26 +0000408 bool IsCheckNext = false, IsCheckNot = false;
Chris Lattner5dafafd2009-08-15 18:32:21 +0000409
Chris Lattnerd7e25052009-08-15 18:00:42 +0000410 // Verify that the : is present after the prefix.
Chris Lattner96077032009-09-20 22:11:44 +0000411 if (Buffer[CheckPrefix.size()] == ':') {
412 Buffer = Buffer.substr(CheckPrefix.size()+1);
Chris Lattner96077032009-09-20 22:11:44 +0000413 } else if (Buffer.size() > CheckPrefix.size()+6 &&
414 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
415 Buffer = Buffer.substr(CheckPrefix.size()+7);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000416 IsCheckNext = true;
Chris Lattnerf15380b2009-09-20 22:35:26 +0000417 } else if (Buffer.size() > CheckPrefix.size()+5 &&
418 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
419 Buffer = Buffer.substr(CheckPrefix.size()+6);
420 IsCheckNot = true;
Chris Lattner5dafafd2009-08-15 18:32:21 +0000421 } else {
Chris Lattner96077032009-09-20 22:11:44 +0000422 Buffer = Buffer.substr(1);
Chris Lattnerd7e25052009-08-15 18:00:42 +0000423 continue;
424 }
425
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000426 // Okay, we found the prefix, yay. Remember the rest of the line, but
427 // ignore leading and trailing whitespace.
Chris Lattnerf15380b2009-09-20 22:35:26 +0000428 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000429
430 // Scan ahead to the end of line.
Chris Lattner96077032009-09-20 22:11:44 +0000431 size_t EOL = Buffer.find_first_of("\n\r");
Chris Lattnera29703e2009-09-24 20:39:13 +0000432
433 // Parse the pattern.
434 Pattern P;
435 if (P.ParsePattern(Buffer.substr(0, EOL), SM))
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000436 return true;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000437
Chris Lattnera29703e2009-09-24 20:39:13 +0000438 Buffer = Buffer.substr(EOL);
439
Chris Lattnerf15380b2009-09-20 22:35:26 +0000440
Chris Lattner5dafafd2009-08-15 18:32:21 +0000441 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
442 if (IsCheckNext && CheckStrings.empty()) {
443 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
444 "found '"+CheckPrefix+"-NEXT:' without previous '"+
445 CheckPrefix+ ": line", "error");
446 return true;
447 }
448
Chris Lattnera29703e2009-09-24 20:39:13 +0000449 // Handle CHECK-NOT.
450 if (IsCheckNot) {
451 NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
452 P));
453 continue;
454 }
455
Chris Lattner9fc66782009-09-24 20:25:55 +0000456
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000457 // Okay, add the string we captured to the output vector and move on.
Chris Lattner9fc66782009-09-24 20:25:55 +0000458 CheckStrings.push_back(CheckString(P,
Chris Lattner96077032009-09-20 22:11:44 +0000459 SMLoc::getFromPointer(Buffer.data()),
Chris Lattner5dafafd2009-08-15 18:32:21 +0000460 IsCheckNext));
Chris Lattnerf15380b2009-09-20 22:35:26 +0000461 std::swap(NotMatches, CheckStrings.back().NotStrings);
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000462 }
463
464 if (CheckStrings.empty()) {
Chris Lattnerd7e25052009-08-15 18:00:42 +0000465 errs() << "error: no check strings found with prefix '" << CheckPrefix
466 << ":'\n";
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000467 return true;
468 }
469
Chris Lattnerf15380b2009-09-20 22:35:26 +0000470 if (!NotMatches.empty()) {
471 errs() << "error: '" << CheckPrefix
472 << "-NOT:' not supported after last check line.\n";
473 return true;
474 }
475
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000476 return false;
477}
478
Chris Lattner5dafafd2009-08-15 18:32:21 +0000479static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
Chris Lattner96077032009-09-20 22:11:44 +0000480 StringRef Buffer) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000481 // Otherwise, we have an error, emit an error message.
482 SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
483 "error");
484
485 // Print the "scanning from here" line. If the current position is at the
486 // end of a line, advance to the start of the next line.
Chris Lattner96077032009-09-20 22:11:44 +0000487 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
Chris Lattner5dafafd2009-08-15 18:32:21 +0000488
Chris Lattner96077032009-09-20 22:11:44 +0000489 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
Chris Lattner5dafafd2009-08-15 18:32:21 +0000490 "note");
491}
492
Chris Lattner3711b7a2009-09-20 22:42:44 +0000493/// CountNumNewlinesBetween - Count the number of newlines in the specified
494/// range.
495static unsigned CountNumNewlinesBetween(StringRef Range) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000496 unsigned NumNewLines = 0;
Chris Lattner3711b7a2009-09-20 22:42:44 +0000497 while (1) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000498 // Scan for newline.
Chris Lattner3711b7a2009-09-20 22:42:44 +0000499 Range = Range.substr(Range.find_first_of("\n\r"));
500 if (Range.empty()) return NumNewLines;
Chris Lattner5dafafd2009-08-15 18:32:21 +0000501
502 ++NumNewLines;
503
504 // Handle \n\r and \r\n as a single newline.
Chris Lattner3711b7a2009-09-20 22:42:44 +0000505 if (Range.size() > 1 &&
506 (Range[1] == '\n' || Range[1] == '\r') &&
507 (Range[0] != Range[1]))
508 Range = Range.substr(1);
509 Range = Range.substr(1);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000510 }
Chris Lattner5dafafd2009-08-15 18:32:21 +0000511}
512
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000513int main(int argc, char **argv) {
514 sys::PrintStackTraceOnErrorSignal();
515 PrettyStackTraceProgram X(argc, argv);
516 cl::ParseCommandLineOptions(argc, argv);
517
518 SourceMgr SM;
519
520 // Read the expected strings from the check file.
Chris Lattner207e1bc2009-08-15 17:41:04 +0000521 std::vector<CheckString> CheckStrings;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000522 if (ReadCheckFile(SM, CheckStrings))
523 return 2;
524
525 // Open the file to check and add it to SourceMgr.
526 std::string ErrorStr;
527 MemoryBuffer *F =
528 MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
529 if (F == 0) {
530 errs() << "Could not open input file '" << InputFilename << "': "
531 << ErrorStr << '\n';
532 return true;
533 }
Chris Lattner88a7e9e2009-07-11 18:58:15 +0000534
535 // Remove duplicate spaces in the input file if requested.
536 if (!NoCanonicalizeWhiteSpace)
537 F = CanonicalizeInputFile(F);
538
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000539 SM.AddNewSourceBuffer(F, SMLoc());
540
Chris Lattnereec96952009-09-27 07:56:52 +0000541 /// VariableTable - This holds all the current filecheck variables.
542 StringMap<StringRef> VariableTable;
543
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000544 // Check that we have all of the expected strings, in order, in the input
545 // file.
Chris Lattner96077032009-09-20 22:11:44 +0000546 StringRef Buffer = F->getBuffer();
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000547
Chris Lattnerf15380b2009-09-20 22:35:26 +0000548 const char *LastMatch = Buffer.data();
549
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000550 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
Chris Lattner207e1bc2009-08-15 17:41:04 +0000551 const CheckString &CheckStr = CheckStrings[StrNo];
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000552
Chris Lattner96077032009-09-20 22:11:44 +0000553 StringRef SearchFrom = Buffer;
554
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000555 // Find StrNo in the file.
Chris Lattner9fc66782009-09-24 20:25:55 +0000556 size_t MatchLen = 0;
Chris Lattnereec96952009-09-27 07:56:52 +0000557 Buffer = Buffer.substr(CheckStr.Pat.Match(Buffer, MatchLen, VariableTable));
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000558
Chris Lattner5dafafd2009-08-15 18:32:21 +0000559 // If we didn't find a match, reject the input.
Chris Lattner96077032009-09-20 22:11:44 +0000560 if (Buffer.empty()) {
561 PrintCheckFailed(SM, CheckStr, SearchFrom);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000562 return 1;
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000563 }
Chris Lattner3711b7a2009-09-20 22:42:44 +0000564
565 StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
566
Chris Lattner5dafafd2009-08-15 18:32:21 +0000567 // If this check is a "CHECK-NEXT", verify that the previous match was on
568 // the previous line (i.e. that there is one newline between them).
569 if (CheckStr.IsCheckNext) {
570 // Count the number of newlines between the previous match and this one.
Chris Lattnerf15380b2009-09-20 22:35:26 +0000571 assert(LastMatch != F->getBufferStart() &&
572 "CHECK-NEXT can't be the first check in a file");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000573
Chris Lattner3711b7a2009-09-20 22:42:44 +0000574 unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000575 if (NumNewLines == 0) {
Chris Lattner0b2353f2009-08-16 02:22:31 +0000576 SM.PrintMessage(CheckStr.Loc,
Chris Lattner5dafafd2009-08-15 18:32:21 +0000577 CheckPrefix+"-NEXT: is on the same line as previous match",
578 "error");
Chris Lattner96077032009-09-20 22:11:44 +0000579 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
Chris Lattner0b2353f2009-08-16 02:22:31 +0000580 "'next' match was here", "note");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000581 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
582 "previous match was here", "note");
583 return 1;
584 }
585
586 if (NumNewLines != 1) {
Chris Lattner0b2353f2009-08-16 02:22:31 +0000587 SM.PrintMessage(CheckStr.Loc,
Chris Lattner5dafafd2009-08-15 18:32:21 +0000588 CheckPrefix+
589 "-NEXT: is not on the line after the previous match",
590 "error");
Chris Lattner96077032009-09-20 22:11:44 +0000591 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
Chris Lattner0b2353f2009-08-16 02:22:31 +0000592 "'next' match was here", "note");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000593 SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
594 "previous match was here", "note");
595 return 1;
596 }
597 }
Chris Lattnerf15380b2009-09-20 22:35:26 +0000598
599 // If this match had "not strings", verify that they don't exist in the
600 // skipped region.
Chris Lattnereec96952009-09-27 07:56:52 +0000601 for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size();
602 ChunkNo != e; ++ChunkNo) {
Chris Lattnera29703e2009-09-24 20:39:13 +0000603 size_t MatchLen = 0;
Chris Lattnereec96952009-09-27 07:56:52 +0000604 size_t Pos = CheckStr.NotStrings[ChunkNo].second.Match(SkippedRegion,
605 MatchLen,
606 VariableTable);
Chris Lattnerf15380b2009-09-20 22:35:26 +0000607 if (Pos == StringRef::npos) continue;
608
609 SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
610 CheckPrefix+"-NOT: string occurred!", "error");
Chris Lattner52870082009-09-24 21:47:32 +0000611 SM.PrintMessage(CheckStr.NotStrings[ChunkNo].first,
Chris Lattnerf15380b2009-09-20 22:35:26 +0000612 CheckPrefix+"-NOT: pattern specified here", "note");
613 return 1;
614 }
615
Chris Lattner5dafafd2009-08-15 18:32:21 +0000616
Chris Lattner81115762009-09-21 02:30:42 +0000617 // Otherwise, everything is good. Step over the matched text and remember
618 // the position after the match as the end of the last match.
Chris Lattner9fc66782009-09-24 20:25:55 +0000619 Buffer = Buffer.substr(MatchLen);
Chris Lattner81115762009-09-21 02:30:42 +0000620 LastMatch = Buffer.data();
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000621 }
622
623 return 0;
624}