blob: f2510d7dfd708dc9b7493e2035316e50e5bbee71 [file] [log] [blame]
Chris Lattneree3c74f2009-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. Spencer39a0ffc2010-12-16 03:29:14 +000019#include "llvm/ADT/OwningPtr.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000020#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringMap.h"
Matt Arsenault13df4622013-11-10 02:04:09 +000023#include "llvm/ADT/StringSet.h"
Chris Lattneree3c74f2009-07-08 18:44:05 +000024#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/MemoryBuffer.h"
26#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerf08d2db2009-09-24 21:47:32 +000027#include "llvm/Support/Regex.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000028#include "llvm/Support/Signals.h"
Chris Lattneree3c74f2009-07-08 18:44:05 +000029#include "llvm/Support/SourceMgr.h"
30#include "llvm/Support/raw_ostream.h"
Michael J. Spencer7b6fef82010-12-09 17:36:48 +000031#include "llvm/Support/system_error.h"
Chris Lattner8879e062009-09-27 07:56:52 +000032#include <algorithm>
Will Dietz981af002013-10-12 00:55:57 +000033#include <cctype>
Eli Benderskye8b8f1b2012-12-01 21:54:48 +000034#include <map>
35#include <string>
36#include <vector>
Chris Lattneree3c74f2009-07-08 18:44:05 +000037using namespace llvm;
38
39static cl::opt<std::string>
40CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
41
42static cl::opt<std::string>
43InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
44 cl::init("-"), cl::value_desc("filename"));
45
Matt Arsenault13df4622013-11-10 02:04:09 +000046static cl::list<std::string>
47CheckPrefixes("check-prefix",
48 cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
Chris Lattneree3c74f2009-07-08 18:44:05 +000049
Chris Lattner2c3e5cd2009-07-11 18:58:15 +000050static cl::opt<bool>
51NoCanonicalizeWhiteSpace("strict-whitespace",
52 cl::desc("Do not treat all horizontal whitespace as equivalent"));
53
Matt Arsenault13df4622013-11-10 02:04:09 +000054typedef cl::list<std::string>::const_iterator prefix_iterator;
55
Chris Lattner74d50732009-09-24 20:39:13 +000056//===----------------------------------------------------------------------===//
57// Pattern Handling Code.
58//===----------------------------------------------------------------------===//
59
Matt Arsenault38820972013-09-17 22:30:02 +000060namespace Check {
61 enum CheckType {
62 CheckNone = 0,
63 CheckPlain,
64 CheckNext,
65 CheckNot,
66 CheckDAG,
67 CheckLabel,
68
69 /// MatchEOF - When set, this pattern only matches the end of file. This is
70 /// used for trailing CHECK-NOTs.
71 CheckEOF
72 };
73}
74
Chris Lattner3b40b442009-09-24 20:25:55 +000075class Pattern {
Chris Lattner0a4c44b2009-09-25 17:29:36 +000076 SMLoc PatternLoc;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +000077
Matt Arsenault38820972013-09-17 22:30:02 +000078 Check::CheckType CheckTy;
Michael Liao91a1b2c2013-05-14 20:34:12 +000079
Chris Lattnerb16ab0c2009-09-25 17:23:43 +000080 /// FixedStr - If non-empty, this pattern is a fixed string match with the
81 /// specified fixed string.
Chris Lattner221460e2009-09-25 17:09:12 +000082 StringRef FixedStr;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +000083
Chris Lattnerb16ab0c2009-09-25 17:23:43 +000084 /// RegEx - If non-empty, this is a regex pattern.
85 std::string RegExStr;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +000086
Alexander Kornienko92987fb2012-11-14 21:07:37 +000087 /// \brief Contains the number of line this pattern is in.
88 unsigned LineNumber;
89
Chris Lattner8879e062009-09-27 07:56:52 +000090 /// VariableUses - Entries in this vector map to uses of a variable in the
91 /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain
92 /// "foobaz" and we'll get an entry in this vector that tells us to insert the
93 /// value of bar at offset 3.
94 std::vector<std::pair<StringRef, unsigned> > VariableUses;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +000095
Eli Benderskye8b8f1b2012-12-01 21:54:48 +000096 /// VariableDefs - Maps definitions of variables to their parenthesized
97 /// capture numbers.
98 /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
99 std::map<StringRef, unsigned> VariableDefs;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000100
Chris Lattner3b40b442009-09-24 20:25:55 +0000101public:
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000102
Matt Arsenault38820972013-09-17 22:30:02 +0000103 Pattern(Check::CheckType Ty)
104 : CheckTy(Ty) { }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000105
Michael Liao0b707eb2013-04-25 21:31:34 +0000106 /// getLoc - Return the location in source code.
107 SMLoc getLoc() const { return PatternLoc; }
108
Matt Arsenault13df4622013-11-10 02:04:09 +0000109 /// ParsePattern - Parse the given string into the Pattern. Prefix provides
110 /// which prefix is being matched, SM provides the SourceMgr used for error
111 /// reports, and LineNumber is the line number in the input file from which
112 /// the pattern string was read. Returns true in case of an error, false
113 /// otherwise.
114 bool ParsePattern(StringRef PatternStr,
115 StringRef Prefix,
116 SourceMgr &SM,
117 unsigned LineNumber);
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000118
Chris Lattner3b40b442009-09-24 20:25:55 +0000119 /// Match - Match the pattern string against the input buffer Buffer. This
120 /// returns the position that is matched or npos if there is no match. If
121 /// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattner8879e062009-09-27 07:56:52 +0000122 ///
123 /// The VariableTable StringMap provides the current values of filecheck
124 /// variables and is updated if this match defines new values.
125 size_t Match(StringRef Buffer, size_t &MatchLen,
126 StringMap<StringRef> &VariableTable) const;
Daniel Dunbare0ef65a2009-11-22 22:08:06 +0000127
128 /// PrintFailureInfo - Print additional information about a failure to match
129 /// involving this pattern.
130 void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
131 const StringMap<StringRef> &VariableTable) const;
132
Stephen Linf8bd2e52013-07-12 14:51:05 +0000133 bool hasVariable() const { return !(VariableUses.empty() &&
134 VariableDefs.empty()); }
135
Matt Arsenault38820972013-09-17 22:30:02 +0000136 Check::CheckType getCheckTy() const { return CheckTy; }
Michael Liao91a1b2c2013-05-14 20:34:12 +0000137
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000138private:
Chris Lattner8879e062009-09-27 07:56:52 +0000139 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
Eli Benderskye8b8f1b2012-12-01 21:54:48 +0000140 bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
141 void AddBackrefToRegEx(unsigned BackrefNum);
Daniel Dunbarfd29d882009-11-22 22:59:26 +0000142
143 /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
144 /// matching this pattern at the start of \arg Buffer; a distance of zero
145 /// should correspond to a perfect match.
146 unsigned ComputeMatchDistance(StringRef Buffer,
147 const StringMap<StringRef> &VariableTable) const;
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000148
149 /// \brief Evaluates expression and stores the result to \p Value.
150 /// \return true on success. false when the expression has invalid syntax.
151 bool EvaluateExpression(StringRef Expr, std::string &Value) const;
Eli Bendersky061d2ba2012-12-02 16:02:41 +0000152
153 /// \brief Finds the closing sequence of a regex variable usage or
154 /// definition. Str has to point in the beginning of the definition
155 /// (right after the opening sequence).
156 /// \return offset of the closing sequence within Str, or npos if it was not
157 /// found.
158 size_t FindRegexVarEnd(StringRef Str);
Chris Lattner3b40b442009-09-24 20:25:55 +0000159};
160
Chris Lattner8879e062009-09-27 07:56:52 +0000161
Matt Arsenault13df4622013-11-10 02:04:09 +0000162bool Pattern::ParsePattern(StringRef PatternStr,
163 StringRef Prefix,
164 SourceMgr &SM,
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000165 unsigned LineNumber) {
166 this->LineNumber = LineNumber;
Chris Lattner0a4c44b2009-09-25 17:29:36 +0000167 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000168
Chris Lattner74d50732009-09-24 20:39:13 +0000169 // Ignore trailing whitespace.
170 while (!PatternStr.empty() &&
171 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
172 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000173
Chris Lattner74d50732009-09-24 20:39:13 +0000174 // Check that there is something on the line.
175 if (PatternStr.empty()) {
Chris Lattner03b80a42011-10-16 05:43:57 +0000176 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
177 "found empty check string with prefix '" +
Matt Arsenault13df4622013-11-10 02:04:09 +0000178 Prefix + ":'");
Chris Lattner74d50732009-09-24 20:39:13 +0000179 return true;
180 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000181
Chris Lattner221460e2009-09-25 17:09:12 +0000182 // Check to see if this is a fixed string, or if it has regex pieces.
Ted Kremenekd9466962012-09-08 04:32:13 +0000183 if (PatternStr.size() < 2 ||
Chris Lattner8879e062009-09-27 07:56:52 +0000184 (PatternStr.find("{{") == StringRef::npos &&
185 PatternStr.find("[[") == StringRef::npos)) {
Chris Lattner221460e2009-09-25 17:09:12 +0000186 FixedStr = PatternStr;
187 return false;
188 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000189
Chris Lattner8879e062009-09-27 07:56:52 +0000190 // Paren value #0 is for the fully matched string. Any new parenthesized
Chris Lattner53e06792011-04-09 06:18:02 +0000191 // values add from there.
Chris Lattner8879e062009-09-27 07:56:52 +0000192 unsigned CurParen = 1;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000193
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000194 // Otherwise, there is at least one regex piece. Build up the regex pattern
195 // by escaping scary characters in fixed strings, building up one big regex.
Chris Lattnerf08d2db2009-09-24 21:47:32 +0000196 while (!PatternStr.empty()) {
Chris Lattner8879e062009-09-27 07:56:52 +0000197 // RegEx matches.
Chris Lattner53e06792011-04-09 06:18:02 +0000198 if (PatternStr.startswith("{{")) {
Eli Bendersky43d50d42012-11-30 14:22:14 +0000199 // This is the start of a regex match. Scan for the }}.
Chris Lattner8879e062009-09-27 07:56:52 +0000200 size_t End = PatternStr.find("}}");
201 if (End == StringRef::npos) {
202 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
Chris Lattner03b80a42011-10-16 05:43:57 +0000203 SourceMgr::DK_Error,
204 "found start of regex string with no end '}}'");
Chris Lattner8879e062009-09-27 07:56:52 +0000205 return true;
206 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000207
Chris Lattnere53c95f2011-04-09 06:37:03 +0000208 // Enclose {{}} patterns in parens just like [[]] even though we're not
209 // capturing the result for any purpose. This is required in case the
210 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
211 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
212 RegExStr += '(';
213 ++CurParen;
214
Chris Lattner8879e062009-09-27 07:56:52 +0000215 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
216 return true;
Chris Lattnere53c95f2011-04-09 06:37:03 +0000217 RegExStr += ')';
Chris Lattner53e06792011-04-09 06:18:02 +0000218
Chris Lattner8879e062009-09-27 07:56:52 +0000219 PatternStr = PatternStr.substr(End+2);
Chris Lattnerf08d2db2009-09-24 21:47:32 +0000220 continue;
221 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000222
Chris Lattner8879e062009-09-27 07:56:52 +0000223 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
224 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
225 // second form is [[foo]] which is a reference to foo. The variable name
Daniel Dunbar57cb7332009-11-22 22:07:50 +0000226 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
Chris Lattner8879e062009-09-27 07:56:52 +0000227 // it. This is to catch some common errors.
Chris Lattner53e06792011-04-09 06:18:02 +0000228 if (PatternStr.startswith("[[")) {
Eli Bendersky061d2ba2012-12-02 16:02:41 +0000229 // Find the closing bracket pair ending the match. End is going to be an
230 // offset relative to the beginning of the match string.
231 size_t End = FindRegexVarEnd(PatternStr.substr(2));
232
Chris Lattner8879e062009-09-27 07:56:52 +0000233 if (End == StringRef::npos) {
234 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
Chris Lattner03b80a42011-10-16 05:43:57 +0000235 SourceMgr::DK_Error,
236 "invalid named regex reference, no ]] found");
Chris Lattner8879e062009-09-27 07:56:52 +0000237 return true;
238 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000239
Eli Bendersky061d2ba2012-12-02 16:02:41 +0000240 StringRef MatchStr = PatternStr.substr(2, End);
241 PatternStr = PatternStr.substr(End+4);
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000242
Chris Lattner8879e062009-09-27 07:56:52 +0000243 // Get the regex name (e.g. "foo").
244 size_t NameEnd = MatchStr.find(':');
245 StringRef Name = MatchStr.substr(0, NameEnd);
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000246
Chris Lattner8879e062009-09-27 07:56:52 +0000247 if (Name.empty()) {
Chris Lattner03b80a42011-10-16 05:43:57 +0000248 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
249 "invalid name in named regex: empty name");
Chris Lattner8879e062009-09-27 07:56:52 +0000250 return true;
251 }
252
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000253 // Verify that the name/expression is well formed. FileCheck currently
254 // supports @LINE, @LINE+number, @LINE-number expressions. The check here
255 // is relaxed, more strict check is performed in \c EvaluateExpression.
256 bool IsExpression = false;
257 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
258 if (i == 0 && Name[i] == '@') {
259 if (NameEnd != StringRef::npos) {
260 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
261 SourceMgr::DK_Error,
262 "invalid name in named regex definition");
263 return true;
264 }
265 IsExpression = true;
266 continue;
267 }
268 if (Name[i] != '_' && !isalnum(Name[i]) &&
269 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
Chris Lattner8879e062009-09-27 07:56:52 +0000270 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
Chris Lattner03b80a42011-10-16 05:43:57 +0000271 SourceMgr::DK_Error, "invalid name in named regex");
Chris Lattner8879e062009-09-27 07:56:52 +0000272 return true;
273 }
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000274 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000275
Chris Lattner8879e062009-09-27 07:56:52 +0000276 // Name can't start with a digit.
Guy Benyei83c74e92013-02-12 21:21:59 +0000277 if (isdigit(static_cast<unsigned char>(Name[0]))) {
Chris Lattner03b80a42011-10-16 05:43:57 +0000278 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
279 "invalid name in named regex");
Chris Lattner8879e062009-09-27 07:56:52 +0000280 return true;
281 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000282
Chris Lattner8879e062009-09-27 07:56:52 +0000283 // Handle [[foo]].
284 if (NameEnd == StringRef::npos) {
Eli Benderskye8b8f1b2012-12-01 21:54:48 +0000285 // Handle variables that were defined earlier on the same line by
286 // emitting a backreference.
287 if (VariableDefs.find(Name) != VariableDefs.end()) {
288 unsigned VarParenNum = VariableDefs[Name];
289 if (VarParenNum < 1 || VarParenNum > 9) {
290 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
291 SourceMgr::DK_Error,
292 "Can't back-reference more than 9 variables");
293 return true;
294 }
295 AddBackrefToRegEx(VarParenNum);
296 } else {
297 VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
298 }
Chris Lattner8879e062009-09-27 07:56:52 +0000299 continue;
300 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000301
Chris Lattner8879e062009-09-27 07:56:52 +0000302 // Handle [[foo:.*]].
Eli Benderskye8b8f1b2012-12-01 21:54:48 +0000303 VariableDefs[Name] = CurParen;
Chris Lattner8879e062009-09-27 07:56:52 +0000304 RegExStr += '(';
305 ++CurParen;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000306
Chris Lattner8879e062009-09-27 07:56:52 +0000307 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
308 return true;
309
310 RegExStr += ')';
Chris Lattnerf08d2db2009-09-24 21:47:32 +0000311 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000312
Chris Lattner8879e062009-09-27 07:56:52 +0000313 // Handle fixed string matches.
314 // Find the end, which is the start of the next regex.
315 size_t FixedMatchEnd = PatternStr.find("{{");
316 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
317 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
318 PatternStr = PatternStr.substr(FixedMatchEnd);
Chris Lattnerf08d2db2009-09-24 21:47:32 +0000319 }
Chris Lattnera2f8fc52009-09-24 20:45:07 +0000320
Chris Lattner74d50732009-09-24 20:39:13 +0000321 return false;
322}
323
Chris Lattner8879e062009-09-27 07:56:52 +0000324void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000325 // Add the characters from FixedStr to the regex, escaping as needed. This
326 // avoids "leaning toothpicks" in common patterns.
327 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
328 switch (FixedStr[i]) {
329 // These are the special characters matched in "p_ere_exp".
330 case '(':
331 case ')':
332 case '^':
333 case '$':
334 case '|':
335 case '*':
336 case '+':
337 case '?':
338 case '.':
339 case '[':
340 case '\\':
341 case '{':
Chris Lattner8879e062009-09-27 07:56:52 +0000342 TheStr += '\\';
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000343 // FALL THROUGH.
344 default:
Chris Lattner8879e062009-09-27 07:56:52 +0000345 TheStr += FixedStr[i];
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000346 break;
347 }
348 }
349}
350
Eli Benderskye8b8f1b2012-12-01 21:54:48 +0000351bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
Chris Lattner8879e062009-09-27 07:56:52 +0000352 SourceMgr &SM) {
Eli Benderskye8b8f1b2012-12-01 21:54:48 +0000353 Regex R(RS);
Chris Lattner8879e062009-09-27 07:56:52 +0000354 std::string Error;
355 if (!R.isValid(Error)) {
Eli Benderskye8b8f1b2012-12-01 21:54:48 +0000356 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
Chris Lattner03b80a42011-10-16 05:43:57 +0000357 "invalid regex: " + Error);
Chris Lattner8879e062009-09-27 07:56:52 +0000358 return true;
359 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000360
Eli Benderskye8b8f1b2012-12-01 21:54:48 +0000361 RegExStr += RS.str();
Chris Lattner8879e062009-09-27 07:56:52 +0000362 CurParen += R.getNumMatches();
363 return false;
364}
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000365
Eli Benderskye8b8f1b2012-12-01 21:54:48 +0000366void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
367 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
368 std::string Backref = std::string("\\") +
369 std::string(1, '0' + BackrefNum);
370 RegExStr += Backref;
371}
372
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000373bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
374 // The only supported expression is @LINE([\+-]\d+)?
375 if (!Expr.startswith("@LINE"))
376 return false;
377 Expr = Expr.substr(StringRef("@LINE").size());
378 int Offset = 0;
379 if (!Expr.empty()) {
380 if (Expr[0] == '+')
381 Expr = Expr.substr(1);
382 else if (Expr[0] != '-')
383 return false;
384 if (Expr.getAsInteger(10, Offset))
385 return false;
386 }
387 Value = llvm::itostr(LineNumber + Offset);
388 return true;
389}
390
Chris Lattnerf08d2db2009-09-24 21:47:32 +0000391/// Match - Match the pattern string against the input buffer Buffer. This
392/// returns the position that is matched or npos if there is no match. If
393/// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattner8879e062009-09-27 07:56:52 +0000394size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
395 StringMap<StringRef> &VariableTable) const {
Jakob Stoklund Oleseneba55822010-10-15 17:47:12 +0000396 // If this is the EOF pattern, match it immediately.
Matt Arsenault38820972013-09-17 22:30:02 +0000397 if (CheckTy == Check::CheckEOF) {
Jakob Stoklund Oleseneba55822010-10-15 17:47:12 +0000398 MatchLen = 0;
399 return Buffer.size();
400 }
401
Chris Lattner221460e2009-09-25 17:09:12 +0000402 // If this is a fixed string pattern, just match it now.
403 if (!FixedStr.empty()) {
404 MatchLen = FixedStr.size();
405 return Buffer.find(FixedStr);
406 }
Chris Lattner8879e062009-09-27 07:56:52 +0000407
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000408 // Regex match.
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000409
Chris Lattner8879e062009-09-27 07:56:52 +0000410 // If there are variable uses, we need to create a temporary string with the
411 // actual value.
412 StringRef RegExToMatch = RegExStr;
413 std::string TmpStr;
414 if (!VariableUses.empty()) {
415 TmpStr = RegExStr;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000416
Chris Lattner8879e062009-09-27 07:56:52 +0000417 unsigned InsertOffset = 0;
418 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
Chris Lattner8879e062009-09-27 07:56:52 +0000419 std::string Value;
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000420
421 if (VariableUses[i].first[0] == '@') {
422 if (!EvaluateExpression(VariableUses[i].first, Value))
423 return StringRef::npos;
424 } else {
425 StringMap<StringRef>::iterator it =
426 VariableTable.find(VariableUses[i].first);
427 // If the variable is undefined, return an error.
428 if (it == VariableTable.end())
429 return StringRef::npos;
430
431 // Look up the value and escape it so that we can plop it into the regex.
432 AddFixedStringToRegEx(it->second, Value);
433 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000434
Chris Lattner8879e062009-09-27 07:56:52 +0000435 // Plop it into the regex at the adjusted offset.
436 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
437 Value.begin(), Value.end());
438 InsertOffset += Value.size();
439 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000440
Chris Lattner8879e062009-09-27 07:56:52 +0000441 // Match the newly constructed regex.
442 RegExToMatch = TmpStr;
443 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000444
445
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000446 SmallVector<StringRef, 4> MatchInfo;
Chris Lattner8879e062009-09-27 07:56:52 +0000447 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000448 return StringRef::npos;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000449
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000450 // Successful regex match.
451 assert(!MatchInfo.empty() && "Didn't get any match");
452 StringRef FullMatch = MatchInfo[0];
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000453
Chris Lattner8879e062009-09-27 07:56:52 +0000454 // If this defines any variables, remember their values.
Eli Benderskye8b8f1b2012-12-01 21:54:48 +0000455 for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
456 E = VariableDefs.end();
457 I != E; ++I) {
458 assert(I->second < MatchInfo.size() && "Internal paren error");
459 VariableTable[I->first] = MatchInfo[I->second];
Chris Lattner0a4c44b2009-09-25 17:29:36 +0000460 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000461
Chris Lattnerb16ab0c2009-09-25 17:23:43 +0000462 MatchLen = FullMatch.size();
463 return FullMatch.data()-Buffer.data();
Chris Lattnerf08d2db2009-09-24 21:47:32 +0000464}
465
Daniel Dunbarfd29d882009-11-22 22:59:26 +0000466unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
467 const StringMap<StringRef> &VariableTable) const {
468 // Just compute the number of matching characters. For regular expressions, we
469 // just compare against the regex itself and hope for the best.
470 //
471 // FIXME: One easy improvement here is have the regex lib generate a single
472 // example regular expression which matches, and use that as the example
473 // string.
474 StringRef ExampleString(FixedStr);
475 if (ExampleString.empty())
476 ExampleString = RegExStr;
477
Daniel Dunbare9aa36c2010-01-30 00:24:06 +0000478 // Only compare up to the first line in the buffer, or the string size.
479 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
480 BufferPrefix = BufferPrefix.split('\n').first;
481 return BufferPrefix.edit_distance(ExampleString);
Daniel Dunbarfd29d882009-11-22 22:59:26 +0000482}
483
Daniel Dunbare0ef65a2009-11-22 22:08:06 +0000484void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
485 const StringMap<StringRef> &VariableTable) const{
Daniel Dunbare0ef65a2009-11-22 22:08:06 +0000486 // If this was a regular expression using variables, print the current
487 // variable values.
488 if (!VariableUses.empty()) {
489 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
Daniel Dunbare0ef65a2009-11-22 22:08:06 +0000490 SmallString<256> Msg;
491 raw_svector_ostream OS(Msg);
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000492 StringRef Var = VariableUses[i].first;
493 if (Var[0] == '@') {
494 std::string Value;
495 if (EvaluateExpression(Var, Value)) {
496 OS << "with expression \"";
497 OS.write_escaped(Var) << "\" equal to \"";
498 OS.write_escaped(Value) << "\"";
499 } else {
500 OS << "uses incorrect expression \"";
501 OS.write_escaped(Var) << "\"";
502 }
Daniel Dunbare0ef65a2009-11-22 22:08:06 +0000503 } else {
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000504 StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
505
506 // Check for undefined variable references.
507 if (it == VariableTable.end()) {
508 OS << "uses undefined variable \"";
509 OS.write_escaped(Var) << "\"";
510 } else {
511 OS << "with variable \"";
512 OS.write_escaped(Var) << "\" equal to \"";
513 OS.write_escaped(it->second) << "\"";
514 }
Daniel Dunbare0ef65a2009-11-22 22:08:06 +0000515 }
516
Chris Lattner03b80a42011-10-16 05:43:57 +0000517 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
518 OS.str());
Daniel Dunbare0ef65a2009-11-22 22:08:06 +0000519 }
520 }
Daniel Dunbarfd29d882009-11-22 22:59:26 +0000521
522 // Attempt to find the closest/best fuzzy match. Usually an error happens
523 // because some string in the output didn't exactly match. In these cases, we
524 // would like to show the user a best guess at what "should have" matched, to
525 // save them having to actually check the input manually.
526 size_t NumLinesForward = 0;
527 size_t Best = StringRef::npos;
528 double BestQuality = 0;
529
530 // Use an arbitrary 4k limit on how far we will search.
Dan Gohman2bf486e2010-01-29 21:57:46 +0000531 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
Daniel Dunbarfd29d882009-11-22 22:59:26 +0000532 if (Buffer[i] == '\n')
533 ++NumLinesForward;
534
Dan Gohmandf22bbf2010-01-29 21:55:16 +0000535 // Patterns have leading whitespace stripped, so skip whitespace when
536 // looking for something which looks like a pattern.
537 if (Buffer[i] == ' ' || Buffer[i] == '\t')
538 continue;
539
Daniel Dunbarfd29d882009-11-22 22:59:26 +0000540 // Compute the "quality" of this match as an arbitrary combination of the
541 // match distance and the number of lines skipped to get to this match.
542 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
543 double Quality = Distance + (NumLinesForward / 100.);
544
545 if (Quality < BestQuality || Best == StringRef::npos) {
546 Best = i;
547 BestQuality = Quality;
548 }
549 }
550
Daniel Dunbarc069cc82010-03-19 18:07:43 +0000551 // Print the "possible intended match here" line if we found something
552 // reasonable and not equal to what we showed in the "scanning from here"
553 // line.
554 if (Best && Best != StringRef::npos && BestQuality < 50) {
555 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
Chris Lattner03b80a42011-10-16 05:43:57 +0000556 SourceMgr::DK_Note, "possible intended match here");
Daniel Dunbarfd29d882009-11-22 22:59:26 +0000557
558 // FIXME: If we wanted to be really friendly we would show why the match
559 // failed, as it can be hard to spot simple one character differences.
560 }
Daniel Dunbare0ef65a2009-11-22 22:08:06 +0000561}
Chris Lattner74d50732009-09-24 20:39:13 +0000562
Eli Bendersky061d2ba2012-12-02 16:02:41 +0000563size_t Pattern::FindRegexVarEnd(StringRef Str) {
564 // Offset keeps track of the current offset within the input Str
565 size_t Offset = 0;
566 // [...] Nesting depth
567 size_t BracketDepth = 0;
568
569 while (!Str.empty()) {
570 if (Str.startswith("]]") && BracketDepth == 0)
571 return Offset;
572 if (Str[0] == '\\') {
573 // Backslash escapes the next char within regexes, so skip them both.
574 Str = Str.substr(2);
575 Offset += 2;
576 } else {
577 switch (Str[0]) {
578 default:
579 break;
580 case '[':
581 BracketDepth++;
582 break;
583 case ']':
584 assert(BracketDepth > 0 && "Invalid regex");
585 BracketDepth--;
586 break;
587 }
588 Str = Str.substr(1);
589 Offset++;
590 }
591 }
592
593 return StringRef::npos;
594}
595
596
Chris Lattner74d50732009-09-24 20:39:13 +0000597//===----------------------------------------------------------------------===//
598// Check Strings.
599//===----------------------------------------------------------------------===//
Chris Lattner3b40b442009-09-24 20:25:55 +0000600
601/// CheckString - This is a check that we found in the input file.
602struct CheckString {
603 /// Pat - The pattern to match.
604 Pattern Pat;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000605
Matt Arsenault13df4622013-11-10 02:04:09 +0000606 /// Prefix - Which prefix name this check matched.
607 StringRef Prefix;
608
Chris Lattner26cccfe2009-08-15 17:41:04 +0000609 /// Loc - The location in the match file that the check string was specified.
610 SMLoc Loc;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000611
Matt Arsenault38820972013-09-17 22:30:02 +0000612 /// CheckTy - Specify what kind of check this is. e.g. CHECK-NEXT: directive,
613 /// as opposed to a CHECK: directive.
614 Check::CheckType CheckTy;
Stephen Linf8bd2e52013-07-12 14:51:05 +0000615
Michael Liao91a1b2c2013-05-14 20:34:12 +0000616 /// DagNotStrings - These are all of the strings that are disallowed from
Chris Lattner236d2d52009-09-20 22:35:26 +0000617 /// occurring between this match string and the previous one (or start of
618 /// file).
Michael Liao91a1b2c2013-05-14 20:34:12 +0000619 std::vector<Pattern> DagNotStrings;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000620
Matt Arsenault13df4622013-11-10 02:04:09 +0000621
622 CheckString(const Pattern &P,
623 StringRef S,
624 SMLoc L,
625 Check::CheckType Ty)
626 : Pat(P), Prefix(S), Loc(L), CheckTy(Ty) {}
Michael Liaodcc7d482013-05-14 20:29:52 +0000627
Michael Liao91a1b2c2013-05-14 20:34:12 +0000628 /// Check - Match check string and its "not strings" and/or "dag strings".
Stephen Line93a3a02013-10-11 18:38:36 +0000629 size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode,
Stephen Linf8bd2e52013-07-12 14:51:05 +0000630 size_t &MatchLen, StringMap<StringRef> &VariableTable) const;
Michael Liaodcc7d482013-05-14 20:29:52 +0000631
632 /// CheckNext - Verify there is a single line in the given buffer.
633 bool CheckNext(const SourceMgr &SM, StringRef Buffer) const;
634
635 /// CheckNot - Verify there's no "not strings" in the given buffer.
636 bool CheckNot(const SourceMgr &SM, StringRef Buffer,
Michael Liao91a1b2c2013-05-14 20:34:12 +0000637 const std::vector<const Pattern *> &NotStrings,
Michael Liaodcc7d482013-05-14 20:29:52 +0000638 StringMap<StringRef> &VariableTable) const;
Michael Liao91a1b2c2013-05-14 20:34:12 +0000639
640 /// CheckDag - Match "dag strings" and their mixed "not strings".
641 size_t CheckDag(const SourceMgr &SM, StringRef Buffer,
642 std::vector<const Pattern *> &NotStrings,
643 StringMap<StringRef> &VariableTable) const;
Chris Lattner26cccfe2009-08-15 17:41:04 +0000644};
645
Guy Benyei5ea04c32013-02-06 20:40:38 +0000646/// Canonicalize whitespaces in the input file. Line endings are replaced
647/// with UNIX-style '\n'.
648///
649/// \param PreserveHorizontal Don't squash consecutive horizontal whitespace
650/// characters to a single space.
651static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB,
652 bool PreserveHorizontal) {
Chris Lattner0e45d242010-04-05 22:42:30 +0000653 SmallString<128> NewFile;
Chris Lattnera2f8fc52009-09-24 20:45:07 +0000654 NewFile.reserve(MB->getBufferSize());
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000655
Chris Lattnera2f8fc52009-09-24 20:45:07 +0000656 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
657 Ptr != End; ++Ptr) {
NAKAMURA Takumifd781bf2010-11-14 03:28:22 +0000658 // Eliminate trailing dosish \r.
659 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
660 continue;
661 }
662
Michael Liao61bed2f2013-04-25 18:54:02 +0000663 // If current char is not a horizontal whitespace or if horizontal
Guy Benyei5ea04c32013-02-06 20:40:38 +0000664 // whitespace canonicalization is disabled, dump it to output as is.
665 if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) {
Chris Lattnera2f8fc52009-09-24 20:45:07 +0000666 NewFile.push_back(*Ptr);
667 continue;
668 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000669
Chris Lattnera2f8fc52009-09-24 20:45:07 +0000670 // Otherwise, add one space and advance over neighboring space.
671 NewFile.push_back(' ');
672 while (Ptr+1 != End &&
673 (Ptr[1] == ' ' || Ptr[1] == '\t'))
674 ++Ptr;
675 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000676
Chris Lattnera2f8fc52009-09-24 20:45:07 +0000677 // Free the old buffer and return a new one.
678 MemoryBuffer *MB2 =
Chris Lattner0e45d242010-04-05 22:42:30 +0000679 MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000680
Chris Lattnera2f8fc52009-09-24 20:45:07 +0000681 delete MB;
682 return MB2;
683}
684
Matt Arsenault38820972013-09-17 22:30:02 +0000685static bool IsPartOfWord(char c) {
686 return (isalnum(c) || c == '-' || c == '_');
687}
688
Matt Arsenault13df4622013-11-10 02:04:09 +0000689// Get the size of the prefix extension.
690static size_t CheckTypeSize(Check::CheckType Ty) {
691 switch (Ty) {
692 case Check::CheckNone:
693 return 0;
694
695 case Check::CheckPlain:
696 return sizeof(":") - 1;
697
698 case Check::CheckNext:
699 return sizeof("-NEXT:") - 1;
700
701 case Check::CheckNot:
702 return sizeof("-NOT:") - 1;
703
704 case Check::CheckDAG:
705 return sizeof("-DAG:") - 1;
706
707 case Check::CheckLabel:
708 return sizeof("-LABEL:") - 1;
709
710 case Check::CheckEOF:
711 llvm_unreachable("Should not be using EOF size");
712 }
713
714 llvm_unreachable("Bad check type");
715}
716
717static Check::CheckType FindCheckType(StringRef Buffer, StringRef Prefix) {
Matt Arsenaultc4d2d472013-09-17 22:45:57 +0000718 char NextChar = Buffer[Prefix.size()];
Matt Arsenault38820972013-09-17 22:30:02 +0000719
720 // Verify that the : is present after the prefix.
Matt Arsenault13df4622013-11-10 02:04:09 +0000721 if (NextChar == ':')
Matt Arsenault38820972013-09-17 22:30:02 +0000722 return Check::CheckPlain;
Matt Arsenault38820972013-09-17 22:30:02 +0000723
Matt Arsenault13df4622013-11-10 02:04:09 +0000724 if (NextChar != '-')
Matt Arsenault38820972013-09-17 22:30:02 +0000725 return Check::CheckNone;
Matt Arsenault38820972013-09-17 22:30:02 +0000726
Matt Arsenaultc4d2d472013-09-17 22:45:57 +0000727 StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
Matt Arsenault13df4622013-11-10 02:04:09 +0000728 if (Rest.startswith("NEXT:"))
Matt Arsenault38820972013-09-17 22:30:02 +0000729 return Check::CheckNext;
Matt Arsenault38820972013-09-17 22:30:02 +0000730
Matt Arsenault13df4622013-11-10 02:04:09 +0000731 if (Rest.startswith("NOT:"))
Matt Arsenault38820972013-09-17 22:30:02 +0000732 return Check::CheckNot;
Matt Arsenault38820972013-09-17 22:30:02 +0000733
Matt Arsenault13df4622013-11-10 02:04:09 +0000734 if (Rest.startswith("DAG:"))
Matt Arsenault38820972013-09-17 22:30:02 +0000735 return Check::CheckDAG;
Matt Arsenault38820972013-09-17 22:30:02 +0000736
Matt Arsenault13df4622013-11-10 02:04:09 +0000737 if (Rest.startswith("LABEL:"))
Matt Arsenault38820972013-09-17 22:30:02 +0000738 return Check::CheckLabel;
Matt Arsenault13df4622013-11-10 02:04:09 +0000739
740 return Check::CheckNone;
741}
742
743// From the given position, find the next character after the word.
744static size_t SkipWord(StringRef Str, size_t Loc) {
745 while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
746 ++Loc;
747 return Loc;
748}
749
750// Try to find the first match in buffer for any prefix. If a valid match is
751// found, return that prefix and set its type and location. If there are almost
752// matches (e.g. the actual prefix string is found, but is not an actual check
753// string), but no valid match, return an empty string and set the position to
754// resume searching from. If no partial matches are found, return an empty
755// string and the location will be StringRef::npos. If one prefix is a substring
756// of another, the maximal match should be found. e.g. if "A" and "AA" are
757// prefixes then AA-CHECK: should match the second one.
758static StringRef FindFirstCandidateMatch(StringRef &Buffer,
759 Check::CheckType &CheckTy,
760 size_t &CheckLoc) {
761 StringRef FirstPrefix;
762 size_t FirstLoc = StringRef::npos;
763 size_t SearchLoc = StringRef::npos;
764 Check::CheckType FirstTy = Check::CheckNone;
765
766 CheckTy = Check::CheckNone;
767 CheckLoc = StringRef::npos;
768
769 for (prefix_iterator I = CheckPrefixes.begin(), E = CheckPrefixes.end();
770 I != E; ++I) {
771 StringRef Prefix(*I);
772 size_t PrefixLoc = Buffer.find(Prefix);
773
774 if (PrefixLoc == StringRef::npos)
775 continue;
776
777 // Track where we are searching for invalid prefixes that look almost right.
778 // We need to only advance to the first partial match on the next attempt
779 // since a partial match could be a substring of a later, valid prefix.
780 // Need to skip to the end of the word, otherwise we could end up
781 // matching a prefix in a substring later.
782 if (PrefixLoc < SearchLoc)
783 SearchLoc = SkipWord(Buffer, PrefixLoc);
784
785 // We only want to find the first match to avoid skipping some.
786 if (PrefixLoc > FirstLoc)
787 continue;
Alexey Samsonova7181a12013-11-13 14:12:52 +0000788 // If one matching check-prefix is a prefix of another, choose the
789 // longer one.
790 if (PrefixLoc == FirstLoc && Prefix.size() < FirstPrefix.size())
791 continue;
Matt Arsenault13df4622013-11-10 02:04:09 +0000792
793 StringRef Rest = Buffer.drop_front(PrefixLoc);
794 // Make sure we have actually found the prefix, and not a word containing
795 // it. This should also prevent matching the wrong prefix when one is a
796 // substring of another.
797 if (PrefixLoc != 0 && IsPartOfWord(Buffer[PrefixLoc - 1]))
798 continue;
799
Matt Arsenault13df4622013-11-10 02:04:09 +0000800 FirstLoc = PrefixLoc;
Alexey Samsonova7181a12013-11-13 14:12:52 +0000801 FirstTy = FindCheckType(Rest, Prefix);
802 FirstPrefix = Prefix;
Matt Arsenault38820972013-09-17 22:30:02 +0000803 }
804
Alexey Samsonova7181a12013-11-13 14:12:52 +0000805 // If the first prefix is invalid, we should continue the search after it.
806 if (FirstTy == Check::CheckNone) {
Matt Arsenault13df4622013-11-10 02:04:09 +0000807 CheckLoc = SearchLoc;
Alexey Samsonova7181a12013-11-13 14:12:52 +0000808 return "";
Matt Arsenault13df4622013-11-10 02:04:09 +0000809 }
810
Alexey Samsonova7181a12013-11-13 14:12:52 +0000811 CheckTy = FirstTy;
812 CheckLoc = FirstLoc;
Matt Arsenault13df4622013-11-10 02:04:09 +0000813 return FirstPrefix;
814}
815
816static StringRef FindFirstMatchingPrefix(StringRef &Buffer,
817 unsigned &LineNumber,
818 Check::CheckType &CheckTy,
819 size_t &CheckLoc) {
820 while (!Buffer.empty()) {
821 StringRef Prefix = FindFirstCandidateMatch(Buffer, CheckTy, CheckLoc);
822 // If we found a real match, we are done.
823 if (!Prefix.empty()) {
824 LineNumber += Buffer.substr(0, CheckLoc).count('\n');
825 return Prefix;
826 }
827
828 // We didn't find any almost matches either, we are also done.
829 if (CheckLoc == StringRef::npos)
830 return StringRef();
831
832 LineNumber += Buffer.substr(0, CheckLoc + 1).count('\n');
833
834 // Advance to the last possible match we found and try again.
835 Buffer = Buffer.drop_front(CheckLoc + 1);
836 }
837
838 return StringRef();
Matt Arsenault38820972013-09-17 22:30:02 +0000839}
Chris Lattneree3c74f2009-07-08 18:44:05 +0000840
Chris Lattneree3c74f2009-07-08 18:44:05 +0000841/// ReadCheckFile - Read the check file, which specifies the sequence of
842/// expected strings. The strings are added to the CheckStrings vector.
Eli Bendersky43d50d42012-11-30 14:22:14 +0000843/// Returns true in case of an error, false otherwise.
Chris Lattneree3c74f2009-07-08 18:44:05 +0000844static bool ReadCheckFile(SourceMgr &SM,
Chris Lattner26cccfe2009-08-15 17:41:04 +0000845 std::vector<CheckString> &CheckStrings) {
Michael J. Spencer39a0ffc2010-12-16 03:29:14 +0000846 OwningPtr<MemoryBuffer> File;
847 if (error_code ec =
Rafael Espindola8c811722013-06-25 05:28:34 +0000848 MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) {
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000849 errs() << "Could not open check file '" << CheckFilename << "': "
Michael J. Spencer7b6fef82010-12-09 17:36:48 +0000850 << ec.message() << '\n';
Chris Lattneree3c74f2009-07-08 18:44:05 +0000851 return true;
852 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000853
Chris Lattnera2f8fc52009-09-24 20:45:07 +0000854 // If we want to canonicalize whitespace, strip excess whitespace from the
Guy Benyei5ea04c32013-02-06 20:40:38 +0000855 // buffer containing the CHECK lines. Remove DOS style line endings.
Benjamin Kramere963d662013-03-23 13:56:23 +0000856 MemoryBuffer *F =
857 CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000858
Chris Lattneree3c74f2009-07-08 18:44:05 +0000859 SM.AddNewSourceBuffer(F, SMLoc());
860
Chris Lattner10f10ce2009-08-15 18:00:42 +0000861 // Find all instances of CheckPrefix followed by : in the file.
Chris Lattnercaa5fc02009-09-20 22:11:44 +0000862 StringRef Buffer = F->getBuffer();
Michael Liao91a1b2c2013-05-14 20:34:12 +0000863 std::vector<Pattern> DagNotMatches;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000864
Eli Bendersky43d50d42012-11-30 14:22:14 +0000865 // LineNumber keeps track of the line on which CheckPrefix instances are
866 // found.
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000867 unsigned LineNumber = 1;
868
Chris Lattneree3c74f2009-07-08 18:44:05 +0000869 while (1) {
Matt Arsenault13df4622013-11-10 02:04:09 +0000870 Check::CheckType CheckTy;
871 size_t PrefixLoc;
872
873 // See if a prefix occurs in the memory buffer.
874 StringRef UsedPrefix = FindFirstMatchingPrefix(Buffer,
875 LineNumber,
876 CheckTy,
877 PrefixLoc);
878 if (UsedPrefix.empty())
Chris Lattneree3c74f2009-07-08 18:44:05 +0000879 break;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000880
Matt Arsenault13df4622013-11-10 02:04:09 +0000881 Buffer = Buffer.drop_front(PrefixLoc);
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000882
Matt Arsenault13df4622013-11-10 02:04:09 +0000883 // Location to use for error messages.
884 const char *UsedPrefixStart = Buffer.data() + (PrefixLoc == 0 ? 0 : 1);
Alexander Kornienko92987fb2012-11-14 21:07:37 +0000885
Matt Arsenault13df4622013-11-10 02:04:09 +0000886 // PrefixLoc is to the start of the prefix. Skip to the end.
887 Buffer = Buffer.drop_front(UsedPrefix.size() + CheckTypeSize(CheckTy));
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000888
Matt Arsenault38820972013-09-17 22:30:02 +0000889 // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
890 // leading and trailing whitespace.
Chris Lattner236d2d52009-09-20 22:35:26 +0000891 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000892
Chris Lattneree3c74f2009-07-08 18:44:05 +0000893 // Scan ahead to the end of line.
Chris Lattnercaa5fc02009-09-20 22:11:44 +0000894 size_t EOL = Buffer.find_first_of("\n\r");
Chris Lattner74d50732009-09-24 20:39:13 +0000895
Dan Gohman838fb092010-01-29 21:53:18 +0000896 // Remember the location of the start of the pattern, for diagnostics.
897 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
898
Chris Lattner74d50732009-09-24 20:39:13 +0000899 // Parse the pattern.
Matt Arsenault38820972013-09-17 22:30:02 +0000900 Pattern P(CheckTy);
Matt Arsenault13df4622013-11-10 02:04:09 +0000901 if (P.ParsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, LineNumber))
Chris Lattneree3c74f2009-07-08 18:44:05 +0000902 return true;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000903
Stephen Linf8bd2e52013-07-12 14:51:05 +0000904 // Verify that CHECK-LABEL lines do not define or use variables
Matt Arsenault38820972013-09-17 22:30:02 +0000905 if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
Matt Arsenault13df4622013-11-10 02:04:09 +0000906 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
Stephen Linf8bd2e52013-07-12 14:51:05 +0000907 SourceMgr::DK_Error,
Matt Arsenault13df4622013-11-10 02:04:09 +0000908 "found '" + UsedPrefix + "-LABEL:'"
909 " with variable definition or use");
Stephen Linf8bd2e52013-07-12 14:51:05 +0000910 return true;
911 }
912
Chris Lattner74d50732009-09-24 20:39:13 +0000913 Buffer = Buffer.substr(EOL);
914
Chris Lattnerda108b42009-08-15 18:32:21 +0000915 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
Matt Arsenault38820972013-09-17 22:30:02 +0000916 if ((CheckTy == Check::CheckNext) && CheckStrings.empty()) {
Matt Arsenault13df4622013-11-10 02:04:09 +0000917 SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
Chris Lattner03b80a42011-10-16 05:43:57 +0000918 SourceMgr::DK_Error,
Matt Arsenault13df4622013-11-10 02:04:09 +0000919 "found '" + UsedPrefix + "-NEXT:' without previous '"
920 + UsedPrefix + ": line");
Chris Lattnerda108b42009-08-15 18:32:21 +0000921 return true;
922 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000923
Michael Liao91a1b2c2013-05-14 20:34:12 +0000924 // Handle CHECK-DAG/-NOT.
Matt Arsenault38820972013-09-17 22:30:02 +0000925 if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
Michael Liao91a1b2c2013-05-14 20:34:12 +0000926 DagNotMatches.push_back(P);
Chris Lattner74d50732009-09-24 20:39:13 +0000927 continue;
928 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000929
Chris Lattneree3c74f2009-07-08 18:44:05 +0000930 // Okay, add the string we captured to the output vector and move on.
Chris Lattner3b40b442009-09-24 20:25:55 +0000931 CheckStrings.push_back(CheckString(P,
Matt Arsenault13df4622013-11-10 02:04:09 +0000932 UsedPrefix,
Dan Gohman838fb092010-01-29 21:53:18 +0000933 PatternLoc,
Matt Arsenault38820972013-09-17 22:30:02 +0000934 CheckTy));
Michael Liao91a1b2c2013-05-14 20:34:12 +0000935 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
Chris Lattneree3c74f2009-07-08 18:44:05 +0000936 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000937
Matt Arsenault13df4622013-11-10 02:04:09 +0000938 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
939 // prefix as a filler for the error message.
Michael Liao91a1b2c2013-05-14 20:34:12 +0000940 if (!DagNotMatches.empty()) {
Matt Arsenault38820972013-09-17 22:30:02 +0000941 CheckStrings.push_back(CheckString(Pattern(Check::CheckEOF),
Matt Arsenault13df4622013-11-10 02:04:09 +0000942 CheckPrefixes[0],
Jakob Stoklund Oleseneba55822010-10-15 17:47:12 +0000943 SMLoc::getFromPointer(Buffer.data()),
Matt Arsenault38820972013-09-17 22:30:02 +0000944 Check::CheckEOF));
Michael Liao91a1b2c2013-05-14 20:34:12 +0000945 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
Jakob Stoklund Oleseneba55822010-10-15 17:47:12 +0000946 }
947
Chris Lattneree3c74f2009-07-08 18:44:05 +0000948 if (CheckStrings.empty()) {
Matt Arsenault13df4622013-11-10 02:04:09 +0000949 errs() << "error: no check strings found with prefix"
950 << (CheckPrefixes.size() > 1 ? "es " : " ");
951 for (size_t I = 0, N = CheckPrefixes.size(); I != N; ++I) {
952 StringRef Prefix(CheckPrefixes[I]);
953 errs() << '\'' << Prefix << ":'";
954 if (I != N - 1)
955 errs() << ", ";
956 }
957
958 errs() << '\n';
Chris Lattneree3c74f2009-07-08 18:44:05 +0000959 return true;
960 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000961
Chris Lattneree3c74f2009-07-08 18:44:05 +0000962 return false;
963}
964
Michael Liao91a1b2c2013-05-14 20:34:12 +0000965static void PrintCheckFailed(const SourceMgr &SM, const SMLoc &Loc,
966 const Pattern &Pat, StringRef Buffer,
Daniel Dunbare0ef65a2009-11-22 22:08:06 +0000967 StringMap<StringRef> &VariableTable) {
Chris Lattnerda108b42009-08-15 18:32:21 +0000968 // Otherwise, we have an error, emit an error message.
Michael Liao91a1b2c2013-05-14 20:34:12 +0000969 SM.PrintMessage(Loc, SourceMgr::DK_Error,
Chris Lattner03b80a42011-10-16 05:43:57 +0000970 "expected string not found in input");
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000971
Chris Lattnerda108b42009-08-15 18:32:21 +0000972 // Print the "scanning from here" line. If the current position is at the
973 // end of a line, advance to the start of the next line.
Chris Lattnercaa5fc02009-09-20 22:11:44 +0000974 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000975
Chris Lattner03b80a42011-10-16 05:43:57 +0000976 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
977 "scanning from here");
Daniel Dunbare0ef65a2009-11-22 22:08:06 +0000978
979 // Allow the pattern to print additional information if desired.
Michael Liao91a1b2c2013-05-14 20:34:12 +0000980 Pat.PrintFailureInfo(SM, Buffer, VariableTable);
981}
982
983static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
984 StringRef Buffer,
985 StringMap<StringRef> &VariableTable) {
986 PrintCheckFailed(SM, CheckStr.Loc, CheckStr.Pat, Buffer, VariableTable);
Chris Lattnerda108b42009-08-15 18:32:21 +0000987}
988
Chris Lattner37183582009-09-20 22:42:44 +0000989/// CountNumNewlinesBetween - Count the number of newlines in the specified
990/// range.
991static unsigned CountNumNewlinesBetween(StringRef Range) {
Chris Lattnerda108b42009-08-15 18:32:21 +0000992 unsigned NumNewLines = 0;
Chris Lattner37183582009-09-20 22:42:44 +0000993 while (1) {
Chris Lattnerda108b42009-08-15 18:32:21 +0000994 // Scan for newline.
Chris Lattner37183582009-09-20 22:42:44 +0000995 Range = Range.substr(Range.find_first_of("\n\r"));
996 if (Range.empty()) return NumNewLines;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000997
Chris Lattnerda108b42009-08-15 18:32:21 +0000998 ++NumNewLines;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +0000999
Chris Lattnerda108b42009-08-15 18:32:21 +00001000 // Handle \n\r and \r\n as a single newline.
Chris Lattner37183582009-09-20 22:42:44 +00001001 if (Range.size() > 1 &&
1002 (Range[1] == '\n' || Range[1] == '\r') &&
1003 (Range[0] != Range[1]))
1004 Range = Range.substr(1);
1005 Range = Range.substr(1);
Chris Lattnerda108b42009-08-15 18:32:21 +00001006 }
Chris Lattnerda108b42009-08-15 18:32:21 +00001007}
1008
Michael Liaodcc7d482013-05-14 20:29:52 +00001009size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer,
Stephen Line93a3a02013-10-11 18:38:36 +00001010 bool IsLabelScanMode, size_t &MatchLen,
Michael Liaodcc7d482013-05-14 20:29:52 +00001011 StringMap<StringRef> &VariableTable) const {
Michael Liao91a1b2c2013-05-14 20:34:12 +00001012 size_t LastPos = 0;
1013 std::vector<const Pattern *> NotStrings;
1014
Stephen Line93a3a02013-10-11 18:38:36 +00001015 // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
1016 // bounds; we have not processed variable definitions within the bounded block
1017 // yet so cannot handle any final CHECK-DAG yet; this is handled when going
1018 // over the block again (including the last CHECK-LABEL) in normal mode.
1019 if (!IsLabelScanMode) {
1020 // Match "dag strings" (with mixed "not strings" if any).
1021 LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable);
1022 if (LastPos == StringRef::npos)
1023 return StringRef::npos;
1024 }
Michael Liao91a1b2c2013-05-14 20:34:12 +00001025
1026 // Match itself from the last position after matching CHECK-DAG.
1027 StringRef MatchBuffer = Buffer.substr(LastPos);
1028 size_t MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
Michael Liaodcc7d482013-05-14 20:29:52 +00001029 if (MatchPos == StringRef::npos) {
Michael Liao91a1b2c2013-05-14 20:34:12 +00001030 PrintCheckFailed(SM, *this, MatchBuffer, VariableTable);
Michael Liaodcc7d482013-05-14 20:29:52 +00001031 return StringRef::npos;
1032 }
Michael Liao91a1b2c2013-05-14 20:34:12 +00001033 MatchPos += LastPos;
Michael Liaodcc7d482013-05-14 20:29:52 +00001034
Stephen Line93a3a02013-10-11 18:38:36 +00001035 // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1036 // or CHECK-NOT
1037 if (!IsLabelScanMode) {
Stephen Linf8bd2e52013-07-12 14:51:05 +00001038 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
Michael Liaodcc7d482013-05-14 20:29:52 +00001039
Stephen Linf8bd2e52013-07-12 14:51:05 +00001040 // If this check is a "CHECK-NEXT", verify that the previous match was on
1041 // the previous line (i.e. that there is one newline between them).
1042 if (CheckNext(SM, SkippedRegion))
1043 return StringRef::npos;
Michael Liaodcc7d482013-05-14 20:29:52 +00001044
Stephen Linf8bd2e52013-07-12 14:51:05 +00001045 // If this match had "not strings", verify that they don't exist in the
1046 // skipped region.
1047 if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
1048 return StringRef::npos;
1049 }
Michael Liaodcc7d482013-05-14 20:29:52 +00001050
1051 return MatchPos;
1052}
1053
1054bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
Matt Arsenault38820972013-09-17 22:30:02 +00001055 if (CheckTy != Check::CheckNext)
Michael Liaodcc7d482013-05-14 20:29:52 +00001056 return false;
1057
1058 // Count the number of newlines between the previous match and this one.
1059 assert(Buffer.data() !=
1060 SM.getMemoryBuffer(
1061 SM.FindBufferContainingLoc(
1062 SMLoc::getFromPointer(Buffer.data())))->getBufferStart() &&
1063 "CHECK-NEXT can't be the first check in a file");
1064
1065 unsigned NumNewLines = CountNumNewlinesBetween(Buffer);
1066
1067 if (NumNewLines == 0) {
Matt Arsenault13df4622013-11-10 02:04:09 +00001068 SM.PrintMessage(Loc, SourceMgr::DK_Error, Prefix +
Michael Liaodcc7d482013-05-14 20:29:52 +00001069 "-NEXT: is on the same line as previous match");
1070 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
1071 SourceMgr::DK_Note, "'next' match was here");
1072 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1073 "previous match ended here");
1074 return true;
1075 }
1076
1077 if (NumNewLines != 1) {
Matt Arsenault13df4622013-11-10 02:04:09 +00001078 SM.PrintMessage(Loc, SourceMgr::DK_Error, Prefix +
Michael Liaodcc7d482013-05-14 20:29:52 +00001079 "-NEXT: is not on the line after the previous match");
1080 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
1081 SourceMgr::DK_Note, "'next' match was here");
1082 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1083 "previous match ended here");
1084 return true;
1085 }
1086
1087 return false;
1088}
1089
1090bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer,
Michael Liao91a1b2c2013-05-14 20:34:12 +00001091 const std::vector<const Pattern *> &NotStrings,
Michael Liaodcc7d482013-05-14 20:29:52 +00001092 StringMap<StringRef> &VariableTable) const {
1093 for (unsigned ChunkNo = 0, e = NotStrings.size();
1094 ChunkNo != e; ++ChunkNo) {
Michael Liao91a1b2c2013-05-14 20:34:12 +00001095 const Pattern *Pat = NotStrings[ChunkNo];
Matt Arsenault38820972013-09-17 22:30:02 +00001096 assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
Michael Liao91a1b2c2013-05-14 20:34:12 +00001097
Michael Liaodcc7d482013-05-14 20:29:52 +00001098 size_t MatchLen = 0;
Michael Liao91a1b2c2013-05-14 20:34:12 +00001099 size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);
Michael Liaodcc7d482013-05-14 20:29:52 +00001100
1101 if (Pos == StringRef::npos) continue;
1102
1103 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos),
1104 SourceMgr::DK_Error,
Matt Arsenault13df4622013-11-10 02:04:09 +00001105 Prefix + "-NOT: string occurred!");
Michael Liao91a1b2c2013-05-14 20:34:12 +00001106 SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note,
Matt Arsenault13df4622013-11-10 02:04:09 +00001107 Prefix + "-NOT: pattern specified here");
Michael Liaodcc7d482013-05-14 20:29:52 +00001108 return true;
1109 }
1110
1111 return false;
1112}
1113
Michael Liao91a1b2c2013-05-14 20:34:12 +00001114size_t CheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1115 std::vector<const Pattern *> &NotStrings,
1116 StringMap<StringRef> &VariableTable) const {
1117 if (DagNotStrings.empty())
1118 return 0;
1119
1120 size_t LastPos = 0;
1121 size_t StartPos = LastPos;
1122
1123 for (unsigned ChunkNo = 0, e = DagNotStrings.size();
1124 ChunkNo != e; ++ChunkNo) {
1125 const Pattern &Pat = DagNotStrings[ChunkNo];
1126
Matt Arsenault38820972013-09-17 22:30:02 +00001127 assert((Pat.getCheckTy() == Check::CheckDAG ||
1128 Pat.getCheckTy() == Check::CheckNot) &&
Michael Liao91a1b2c2013-05-14 20:34:12 +00001129 "Invalid CHECK-DAG or CHECK-NOT!");
1130
Matt Arsenault38820972013-09-17 22:30:02 +00001131 if (Pat.getCheckTy() == Check::CheckNot) {
Michael Liao91a1b2c2013-05-14 20:34:12 +00001132 NotStrings.push_back(&Pat);
1133 continue;
1134 }
1135
Matt Arsenault38820972013-09-17 22:30:02 +00001136 assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
Michael Liao91a1b2c2013-05-14 20:34:12 +00001137
1138 size_t MatchLen = 0, MatchPos;
1139
1140 // CHECK-DAG always matches from the start.
1141 StringRef MatchBuffer = Buffer.substr(StartPos);
1142 MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
1143 // With a group of CHECK-DAGs, a single mismatching means the match on
1144 // that group of CHECK-DAGs fails immediately.
1145 if (MatchPos == StringRef::npos) {
1146 PrintCheckFailed(SM, Pat.getLoc(), Pat, MatchBuffer, VariableTable);
1147 return StringRef::npos;
1148 }
1149 // Re-calc it as the offset relative to the start of the original string.
1150 MatchPos += StartPos;
1151
1152 if (!NotStrings.empty()) {
1153 if (MatchPos < LastPos) {
1154 // Reordered?
1155 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + MatchPos),
1156 SourceMgr::DK_Error,
Matt Arsenault13df4622013-11-10 02:04:09 +00001157 Prefix + "-DAG: found a match of CHECK-DAG"
Michael Liao91a1b2c2013-05-14 20:34:12 +00001158 " reordering across a CHECK-NOT");
1159 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + LastPos),
1160 SourceMgr::DK_Note,
Matt Arsenault13df4622013-11-10 02:04:09 +00001161 Prefix + "-DAG: the farthest match of CHECK-DAG"
Michael Liao91a1b2c2013-05-14 20:34:12 +00001162 " is found here");
1163 SM.PrintMessage(NotStrings[0]->getLoc(), SourceMgr::DK_Note,
Matt Arsenault13df4622013-11-10 02:04:09 +00001164 Prefix + "-NOT: the crossed pattern specified"
Michael Liao91a1b2c2013-05-14 20:34:12 +00001165 " here");
1166 SM.PrintMessage(Pat.getLoc(), SourceMgr::DK_Note,
Matt Arsenault13df4622013-11-10 02:04:09 +00001167 Prefix + "-DAG: the reordered pattern specified"
Michael Liao91a1b2c2013-05-14 20:34:12 +00001168 " here");
1169 return StringRef::npos;
1170 }
1171 // All subsequent CHECK-DAGs should be matched from the farthest
1172 // position of all precedent CHECK-DAGs (including this one.)
1173 StartPos = LastPos;
1174 // If there's CHECK-NOTs between two CHECK-DAGs or from CHECK to
1175 // CHECK-DAG, verify that there's no 'not' strings occurred in that
1176 // region.
1177 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
Tim Northovercf708c32013-08-02 11:32:50 +00001178 if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
Michael Liao91a1b2c2013-05-14 20:34:12 +00001179 return StringRef::npos;
1180 // Clear "not strings".
1181 NotStrings.clear();
1182 }
1183
1184 // Update the last position with CHECK-DAG matches.
1185 LastPos = std::max(MatchPos + MatchLen, LastPos);
1186 }
1187
1188 return LastPos;
1189}
1190
Matt Arsenault13df4622013-11-10 02:04:09 +00001191// A check prefix must contain only alphanumeric, hyphens and underscores.
1192static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1193 Regex Validator("^[a-zA-Z0-9_-]*$");
1194 return Validator.match(CheckPrefix);
1195}
1196
1197static bool ValidateCheckPrefixes() {
1198 StringSet<> PrefixSet;
1199
1200 for (prefix_iterator I = CheckPrefixes.begin(), E = CheckPrefixes.end();
1201 I != E; ++I) {
1202 StringRef Prefix(*I);
1203
1204 if (!PrefixSet.insert(Prefix))
1205 return false;
1206
1207 if (!ValidateCheckPrefix(Prefix))
1208 return false;
1209 }
1210
1211 return true;
1212}
1213
1214// I don't think there's a way to specify an initial value for cl::list,
1215// so if nothing was specified, add the default
1216static void AddCheckPrefixIfNeeded() {
1217 if (CheckPrefixes.empty())
1218 CheckPrefixes.push_back("CHECK");
Rui Ueyamac27351582013-08-12 23:05:59 +00001219}
1220
Chris Lattneree3c74f2009-07-08 18:44:05 +00001221int main(int argc, char **argv) {
1222 sys::PrintStackTraceOnErrorSignal();
1223 PrettyStackTraceProgram X(argc, argv);
1224 cl::ParseCommandLineOptions(argc, argv);
1225
Matt Arsenault13df4622013-11-10 02:04:09 +00001226 if (!ValidateCheckPrefixes()) {
1227 errs() << "Supplied check-prefix is invalid! Prefixes must be unique and "
1228 "start with a letter and contain only alphanumeric characters, "
1229 "hyphens and underscores\n";
Rui Ueyamac27351582013-08-12 23:05:59 +00001230 return 2;
1231 }
1232
Matt Arsenault13df4622013-11-10 02:04:09 +00001233 AddCheckPrefixIfNeeded();
1234
Chris Lattneree3c74f2009-07-08 18:44:05 +00001235 SourceMgr SM;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +00001236
Chris Lattneree3c74f2009-07-08 18:44:05 +00001237 // Read the expected strings from the check file.
Chris Lattner26cccfe2009-08-15 17:41:04 +00001238 std::vector<CheckString> CheckStrings;
Chris Lattneree3c74f2009-07-08 18:44:05 +00001239 if (ReadCheckFile(SM, CheckStrings))
1240 return 2;
1241
1242 // Open the file to check and add it to SourceMgr.
Michael J. Spencer39a0ffc2010-12-16 03:29:14 +00001243 OwningPtr<MemoryBuffer> File;
1244 if (error_code ec =
Rafael Espindola8c811722013-06-25 05:28:34 +00001245 MemoryBuffer::getFileOrSTDIN(InputFilename, File)) {
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +00001246 errs() << "Could not open input file '" << InputFilename << "': "
Michael J. Spencer7b6fef82010-12-09 17:36:48 +00001247 << ec.message() << '\n';
Eli Bendersky8e1c6472012-11-30 13:51:33 +00001248 return 2;
Chris Lattneree3c74f2009-07-08 18:44:05 +00001249 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +00001250
Benjamin Kramere963d662013-03-23 13:56:23 +00001251 if (File->getBufferSize() == 0) {
Chris Lattnerb692bed2011-02-09 16:46:02 +00001252 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
Eli Bendersky8e1c6472012-11-30 13:51:33 +00001253 return 2;
Chris Lattnerb692bed2011-02-09 16:46:02 +00001254 }
Benjamin Kramere963d662013-03-23 13:56:23 +00001255
Chris Lattner2c3e5cd2009-07-11 18:58:15 +00001256 // Remove duplicate spaces in the input file if requested.
Guy Benyei5ea04c32013-02-06 20:40:38 +00001257 // Remove DOS style line endings.
Benjamin Kramere963d662013-03-23 13:56:23 +00001258 MemoryBuffer *F =
1259 CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +00001260
Chris Lattneree3c74f2009-07-08 18:44:05 +00001261 SM.AddNewSourceBuffer(F, SMLoc());
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +00001262
Chris Lattner8879e062009-09-27 07:56:52 +00001263 /// VariableTable - This holds all the current filecheck variables.
1264 StringMap<StringRef> VariableTable;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +00001265
Chris Lattneree3c74f2009-07-08 18:44:05 +00001266 // Check that we have all of the expected strings, in order, in the input
1267 // file.
Chris Lattnercaa5fc02009-09-20 22:11:44 +00001268 StringRef Buffer = F->getBuffer();
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +00001269
Stephen Linf8bd2e52013-07-12 14:51:05 +00001270 bool hasError = false;
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +00001271
Stephen Linf8bd2e52013-07-12 14:51:05 +00001272 unsigned i = 0, j = 0, e = CheckStrings.size();
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +00001273
Stephen Linf8bd2e52013-07-12 14:51:05 +00001274 while (true) {
1275 StringRef CheckRegion;
1276 if (j == e) {
1277 CheckRegion = Buffer;
1278 } else {
1279 const CheckString &CheckLabelStr = CheckStrings[j];
Matt Arsenault38820972013-09-17 22:30:02 +00001280 if (CheckLabelStr.CheckTy != Check::CheckLabel) {
Stephen Linf8bd2e52013-07-12 14:51:05 +00001281 ++j;
1282 continue;
1283 }
Chris Lattner37183582009-09-20 22:42:44 +00001284
Stephen Linf8bd2e52013-07-12 14:51:05 +00001285 // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1286 size_t MatchLabelLen = 0;
Stephen Line93a3a02013-10-11 18:38:36 +00001287 size_t MatchLabelPos = CheckLabelStr.Check(SM, Buffer, true,
Stephen Linf8bd2e52013-07-12 14:51:05 +00001288 MatchLabelLen, VariableTable);
1289 if (MatchLabelPos == StringRef::npos) {
1290 hasError = true;
1291 break;
1292 }
1293
1294 CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1295 Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1296 ++j;
1297 }
1298
1299 for ( ; i != j; ++i) {
1300 const CheckString &CheckStr = CheckStrings[i];
1301
1302 // Check each string within the scanned region, including a second check
1303 // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1304 size_t MatchLen = 0;
Stephen Line93a3a02013-10-11 18:38:36 +00001305 size_t MatchPos = CheckStr.Check(SM, CheckRegion, false, MatchLen,
Stephen Linf8bd2e52013-07-12 14:51:05 +00001306 VariableTable);
1307
1308 if (MatchPos == StringRef::npos) {
1309 hasError = true;
1310 i = j;
1311 break;
1312 }
1313
1314 CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1315 }
1316
1317 if (j == e)
1318 break;
Chris Lattneree3c74f2009-07-08 18:44:05 +00001319 }
Mikhail Glushenkovdefcda22010-08-20 17:38:38 +00001320
Stephen Linf8bd2e52013-07-12 14:51:05 +00001321 return hasError ? 1 : 0;
Chris Lattneree3c74f2009-07-08 18:44:05 +00001322}