blob: 5e2d93bf399379d2e0acabbb231f98cec02875d2 [file] [log] [blame]
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// FileCheck does a line-by line check of a file that validates whether it
11// contains the expected content. This is useful for regression tests etc.
12//
13// This program exits with an error status of 2 on error, exit status of 0 if
14// the file matched the expected contents, and exit status of 1 if it did not
15// contain the expected contents.
16//
17//===----------------------------------------------------------------------===//
18
Michael J. Spencer3ff95632010-12-16 03:29:14 +000019#include "llvm/ADT/OwningPtr.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000020#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringMap.h"
Chris Lattner81cb8ca2009-07-08 18:44:05 +000023#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/MemoryBuffer.h"
25#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner52870082009-09-24 21:47:32 +000026#include "llvm/Support/Regex.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000027#include "llvm/Support/Signals.h"
Chris Lattner81cb8ca2009-07-08 18:44:05 +000028#include "llvm/Support/SourceMgr.h"
29#include "llvm/Support/raw_ostream.h"
Michael J. Spencer333fb042010-12-09 17:36:48 +000030#include "llvm/Support/system_error.h"
Chris Lattnereec96952009-09-27 07:56:52 +000031#include <algorithm>
Eli Bendersky9756ca72012-12-01 21:54:48 +000032#include <map>
33#include <string>
34#include <vector>
Chris Lattner81cb8ca2009-07-08 18:44:05 +000035using namespace llvm;
36
37static cl::opt<std::string>
38CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
39
40static cl::opt<std::string>
41InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
42 cl::init("-"), cl::value_desc("filename"));
43
44static cl::opt<std::string>
45CheckPrefix("check-prefix", cl::init("CHECK"),
46 cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
47
Chris Lattner88a7e9e2009-07-11 18:58:15 +000048static cl::opt<bool>
49NoCanonicalizeWhiteSpace("strict-whitespace",
50 cl::desc("Do not treat all horizontal whitespace as equivalent"));
51
Chris Lattnera29703e2009-09-24 20:39:13 +000052//===----------------------------------------------------------------------===//
53// Pattern Handling Code.
54//===----------------------------------------------------------------------===//
55
Chris Lattner9fc66782009-09-24 20:25:55 +000056class Pattern {
Chris Lattner94638f02009-09-25 17:29:36 +000057 SMLoc PatternLoc;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000058
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +000059 /// MatchEOF - When set, this pattern only matches the end of file. This is
60 /// used for trailing CHECK-NOTs.
61 bool MatchEOF;
62
Michael Liao95ab3262013-05-14 20:34:12 +000063 /// MatchNot
64 bool MatchNot;
65
66 /// MatchDag
67 bool MatchDag;
68
Chris Lattner5d6a05f2009-09-25 17:23:43 +000069 /// FixedStr - If non-empty, this pattern is a fixed string match with the
70 /// specified fixed string.
Chris Lattner2702e6a2009-09-25 17:09:12 +000071 StringRef FixedStr;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000072
Chris Lattner5d6a05f2009-09-25 17:23:43 +000073 /// RegEx - If non-empty, this is a regex pattern.
74 std::string RegExStr;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000075
Alexander Kornienko70a870a2012-11-14 21:07:37 +000076 /// \brief Contains the number of line this pattern is in.
77 unsigned LineNumber;
78
Chris Lattnereec96952009-09-27 07:56:52 +000079 /// VariableUses - Entries in this vector map to uses of a variable in the
80 /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain
81 /// "foobaz" and we'll get an entry in this vector that tells us to insert the
82 /// value of bar at offset 3.
83 std::vector<std::pair<StringRef, unsigned> > VariableUses;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000084
Eli Bendersky9756ca72012-12-01 21:54:48 +000085 /// VariableDefs - Maps definitions of variables to their parenthesized
86 /// capture numbers.
87 /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
88 std::map<StringRef, unsigned> VariableDefs;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000089
Chris Lattner9fc66782009-09-24 20:25:55 +000090public:
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000091
Michael Liao95ab3262013-05-14 20:34:12 +000092 Pattern(bool matchEOF = false)
93 : MatchEOF(matchEOF), MatchNot(false), MatchDag(false) { }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +000094
Michael Liao0fc71372013-04-25 21:31:34 +000095 /// getLoc - Return the location in source code.
96 SMLoc getLoc() const { return PatternLoc; }
97
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +000098 /// ParsePattern - Parse the given string into the Pattern. SM provides the
99 /// SourceMgr used for error reports, and LineNumber is the line number in
100 /// the input file from which the pattern string was read.
101 /// Returns true in case of an error, false otherwise.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000102 bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000103
Chris Lattner9fc66782009-09-24 20:25:55 +0000104 /// Match - Match the pattern string against the input buffer Buffer. This
105 /// returns the position that is matched or npos if there is no match. If
106 /// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattnereec96952009-09-27 07:56:52 +0000107 ///
108 /// The VariableTable StringMap provides the current values of filecheck
109 /// variables and is updated if this match defines new values.
110 size_t Match(StringRef Buffer, size_t &MatchLen,
111 StringMap<StringRef> &VariableTable) const;
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000112
113 /// PrintFailureInfo - Print additional information about a failure to match
114 /// involving this pattern.
115 void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
116 const StringMap<StringRef> &VariableTable) const;
117
Michael Liao95ab3262013-05-14 20:34:12 +0000118 void setMatchNot(bool Not) { MatchNot = Not; }
119 bool getMatchNot() const { return MatchNot; }
120
121 void setMatchDag(bool Dag) { MatchDag = Dag; }
122 bool getMatchDag() const { return MatchDag; }
123
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000124private:
Chris Lattnereec96952009-09-27 07:56:52 +0000125 static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
Eli Bendersky9756ca72012-12-01 21:54:48 +0000126 bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
127 void AddBackrefToRegEx(unsigned BackrefNum);
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000128
129 /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
130 /// matching this pattern at the start of \arg Buffer; a distance of zero
131 /// should correspond to a perfect match.
132 unsigned ComputeMatchDistance(StringRef Buffer,
133 const StringMap<StringRef> &VariableTable) const;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000134
135 /// \brief Evaluates expression and stores the result to \p Value.
136 /// \return true on success. false when the expression has invalid syntax.
137 bool EvaluateExpression(StringRef Expr, std::string &Value) const;
Eli Bendersky4db65112012-12-02 16:02:41 +0000138
139 /// \brief Finds the closing sequence of a regex variable usage or
140 /// definition. Str has to point in the beginning of the definition
141 /// (right after the opening sequence).
142 /// \return offset of the closing sequence within Str, or npos if it was not
143 /// found.
144 size_t FindRegexVarEnd(StringRef Str);
Chris Lattner9fc66782009-09-24 20:25:55 +0000145};
146
Chris Lattnereec96952009-09-27 07:56:52 +0000147
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000148bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
149 unsigned LineNumber) {
150 this->LineNumber = LineNumber;
Chris Lattner94638f02009-09-25 17:29:36 +0000151 PatternLoc = SMLoc::getFromPointer(PatternStr.data());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000152
Chris Lattnera29703e2009-09-24 20:39:13 +0000153 // Ignore trailing whitespace.
154 while (!PatternStr.empty() &&
155 (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
156 PatternStr = PatternStr.substr(0, PatternStr.size()-1);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000157
Chris Lattnera29703e2009-09-24 20:39:13 +0000158 // Check that there is something on the line.
159 if (PatternStr.empty()) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000160 SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
161 "found empty check string with prefix '" +
162 CheckPrefix+":'");
Chris Lattnera29703e2009-09-24 20:39:13 +0000163 return true;
164 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000165
Chris Lattner2702e6a2009-09-25 17:09:12 +0000166 // Check to see if this is a fixed string, or if it has regex pieces.
Ted Kremenek4f505172012-09-08 04:32:13 +0000167 if (PatternStr.size() < 2 ||
Chris Lattnereec96952009-09-27 07:56:52 +0000168 (PatternStr.find("{{") == StringRef::npos &&
169 PatternStr.find("[[") == StringRef::npos)) {
Chris Lattner2702e6a2009-09-25 17:09:12 +0000170 FixedStr = PatternStr;
171 return false;
172 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000173
Chris Lattnereec96952009-09-27 07:56:52 +0000174 // Paren value #0 is for the fully matched string. Any new parenthesized
Chris Lattner13a38c42011-04-09 06:18:02 +0000175 // values add from there.
Chris Lattnereec96952009-09-27 07:56:52 +0000176 unsigned CurParen = 1;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000177
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000178 // Otherwise, there is at least one regex piece. Build up the regex pattern
179 // by escaping scary characters in fixed strings, building up one big regex.
Chris Lattner52870082009-09-24 21:47:32 +0000180 while (!PatternStr.empty()) {
Chris Lattnereec96952009-09-27 07:56:52 +0000181 // RegEx matches.
Chris Lattner13a38c42011-04-09 06:18:02 +0000182 if (PatternStr.startswith("{{")) {
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +0000183 // This is the start of a regex match. Scan for the }}.
Chris Lattnereec96952009-09-27 07:56:52 +0000184 size_t End = PatternStr.find("}}");
185 if (End == StringRef::npos) {
186 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000187 SourceMgr::DK_Error,
188 "found start of regex string with no end '}}'");
Chris Lattnereec96952009-09-27 07:56:52 +0000189 return true;
190 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000191
Chris Lattner42e31df2011-04-09 06:37:03 +0000192 // Enclose {{}} patterns in parens just like [[]] even though we're not
193 // capturing the result for any purpose. This is required in case the
194 // expression contains an alternation like: CHECK: abc{{x|z}}def. We
195 // want this to turn into: "abc(x|z)def" not "abcx|zdef".
196 RegExStr += '(';
197 ++CurParen;
198
Chris Lattnereec96952009-09-27 07:56:52 +0000199 if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
200 return true;
Chris Lattner42e31df2011-04-09 06:37:03 +0000201 RegExStr += ')';
Chris Lattner13a38c42011-04-09 06:18:02 +0000202
Chris Lattnereec96952009-09-27 07:56:52 +0000203 PatternStr = PatternStr.substr(End+2);
Chris Lattner52870082009-09-24 21:47:32 +0000204 continue;
205 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000206
Chris Lattnereec96952009-09-27 07:56:52 +0000207 // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
208 // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
209 // second form is [[foo]] which is a reference to foo. The variable name
Daniel Dunbar964ac012009-11-22 22:07:50 +0000210 // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
Chris Lattnereec96952009-09-27 07:56:52 +0000211 // it. This is to catch some common errors.
Chris Lattner13a38c42011-04-09 06:18:02 +0000212 if (PatternStr.startswith("[[")) {
Eli Bendersky4db65112012-12-02 16:02:41 +0000213 // Find the closing bracket pair ending the match. End is going to be an
214 // offset relative to the beginning of the match string.
215 size_t End = FindRegexVarEnd(PatternStr.substr(2));
216
Chris Lattnereec96952009-09-27 07:56:52 +0000217 if (End == StringRef::npos) {
218 SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000219 SourceMgr::DK_Error,
220 "invalid named regex reference, no ]] found");
Chris Lattnereec96952009-09-27 07:56:52 +0000221 return true;
222 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000223
Eli Bendersky4db65112012-12-02 16:02:41 +0000224 StringRef MatchStr = PatternStr.substr(2, End);
225 PatternStr = PatternStr.substr(End+4);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000226
Chris Lattnereec96952009-09-27 07:56:52 +0000227 // Get the regex name (e.g. "foo").
228 size_t NameEnd = MatchStr.find(':');
229 StringRef Name = MatchStr.substr(0, NameEnd);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000230
Chris Lattnereec96952009-09-27 07:56:52 +0000231 if (Name.empty()) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000232 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
233 "invalid name in named regex: empty name");
Chris Lattnereec96952009-09-27 07:56:52 +0000234 return true;
235 }
236
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000237 // Verify that the name/expression is well formed. FileCheck currently
238 // supports @LINE, @LINE+number, @LINE-number expressions. The check here
239 // is relaxed, more strict check is performed in \c EvaluateExpression.
240 bool IsExpression = false;
241 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
242 if (i == 0 && Name[i] == '@') {
243 if (NameEnd != StringRef::npos) {
244 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
245 SourceMgr::DK_Error,
246 "invalid name in named regex definition");
247 return true;
248 }
249 IsExpression = true;
250 continue;
251 }
252 if (Name[i] != '_' && !isalnum(Name[i]) &&
253 (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
Chris Lattnereec96952009-09-27 07:56:52 +0000254 SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000255 SourceMgr::DK_Error, "invalid name in named regex");
Chris Lattnereec96952009-09-27 07:56:52 +0000256 return true;
257 }
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000258 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000259
Chris Lattnereec96952009-09-27 07:56:52 +0000260 // Name can't start with a digit.
Guy Benyei87d0b9e2013-02-12 21:21:59 +0000261 if (isdigit(static_cast<unsigned char>(Name[0]))) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000262 SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
263 "invalid name in named regex");
Chris Lattnereec96952009-09-27 07:56:52 +0000264 return true;
265 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000266
Chris Lattnereec96952009-09-27 07:56:52 +0000267 // Handle [[foo]].
268 if (NameEnd == StringRef::npos) {
Eli Bendersky9756ca72012-12-01 21:54:48 +0000269 // Handle variables that were defined earlier on the same line by
270 // emitting a backreference.
271 if (VariableDefs.find(Name) != VariableDefs.end()) {
272 unsigned VarParenNum = VariableDefs[Name];
273 if (VarParenNum < 1 || VarParenNum > 9) {
274 SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
275 SourceMgr::DK_Error,
276 "Can't back-reference more than 9 variables");
277 return true;
278 }
279 AddBackrefToRegEx(VarParenNum);
280 } else {
281 VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
282 }
Chris Lattnereec96952009-09-27 07:56:52 +0000283 continue;
284 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000285
Chris Lattnereec96952009-09-27 07:56:52 +0000286 // Handle [[foo:.*]].
Eli Bendersky9756ca72012-12-01 21:54:48 +0000287 VariableDefs[Name] = CurParen;
Chris Lattnereec96952009-09-27 07:56:52 +0000288 RegExStr += '(';
289 ++CurParen;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000290
Chris Lattnereec96952009-09-27 07:56:52 +0000291 if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
292 return true;
293
294 RegExStr += ')';
Chris Lattner52870082009-09-24 21:47:32 +0000295 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000296
Chris Lattnereec96952009-09-27 07:56:52 +0000297 // Handle fixed string matches.
298 // Find the end, which is the start of the next regex.
299 size_t FixedMatchEnd = PatternStr.find("{{");
300 FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
301 AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
302 PatternStr = PatternStr.substr(FixedMatchEnd);
Chris Lattner52870082009-09-24 21:47:32 +0000303 }
Chris Lattneradea46e2009-09-24 20:45:07 +0000304
Chris Lattnera29703e2009-09-24 20:39:13 +0000305 return false;
306}
307
Chris Lattnereec96952009-09-27 07:56:52 +0000308void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000309 // Add the characters from FixedStr to the regex, escaping as needed. This
310 // avoids "leaning toothpicks" in common patterns.
311 for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
312 switch (FixedStr[i]) {
313 // These are the special characters matched in "p_ere_exp".
314 case '(':
315 case ')':
316 case '^':
317 case '$':
318 case '|':
319 case '*':
320 case '+':
321 case '?':
322 case '.':
323 case '[':
324 case '\\':
325 case '{':
Chris Lattnereec96952009-09-27 07:56:52 +0000326 TheStr += '\\';
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000327 // FALL THROUGH.
328 default:
Chris Lattnereec96952009-09-27 07:56:52 +0000329 TheStr += FixedStr[i];
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000330 break;
331 }
332 }
333}
334
Eli Bendersky9756ca72012-12-01 21:54:48 +0000335bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
Chris Lattnereec96952009-09-27 07:56:52 +0000336 SourceMgr &SM) {
Eli Bendersky9756ca72012-12-01 21:54:48 +0000337 Regex R(RS);
Chris Lattnereec96952009-09-27 07:56:52 +0000338 std::string Error;
339 if (!R.isValid(Error)) {
Eli Bendersky9756ca72012-12-01 21:54:48 +0000340 SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000341 "invalid regex: " + Error);
Chris Lattnereec96952009-09-27 07:56:52 +0000342 return true;
343 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000344
Eli Bendersky9756ca72012-12-01 21:54:48 +0000345 RegExStr += RS.str();
Chris Lattnereec96952009-09-27 07:56:52 +0000346 CurParen += R.getNumMatches();
347 return false;
348}
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000349
Eli Bendersky9756ca72012-12-01 21:54:48 +0000350void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
351 assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
352 std::string Backref = std::string("\\") +
353 std::string(1, '0' + BackrefNum);
354 RegExStr += Backref;
355}
356
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000357bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
358 // The only supported expression is @LINE([\+-]\d+)?
359 if (!Expr.startswith("@LINE"))
360 return false;
361 Expr = Expr.substr(StringRef("@LINE").size());
362 int Offset = 0;
363 if (!Expr.empty()) {
364 if (Expr[0] == '+')
365 Expr = Expr.substr(1);
366 else if (Expr[0] != '-')
367 return false;
368 if (Expr.getAsInteger(10, Offset))
369 return false;
370 }
371 Value = llvm::itostr(LineNumber + Offset);
372 return true;
373}
374
Chris Lattner52870082009-09-24 21:47:32 +0000375/// Match - Match the pattern string against the input buffer Buffer. This
376/// returns the position that is matched or npos if there is no match. If
377/// there is a match, the size of the matched string is returned in MatchLen.
Chris Lattnereec96952009-09-27 07:56:52 +0000378size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
379 StringMap<StringRef> &VariableTable) const {
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000380 // If this is the EOF pattern, match it immediately.
381 if (MatchEOF) {
382 MatchLen = 0;
383 return Buffer.size();
384 }
385
Chris Lattner2702e6a2009-09-25 17:09:12 +0000386 // If this is a fixed string pattern, just match it now.
387 if (!FixedStr.empty()) {
388 MatchLen = FixedStr.size();
389 return Buffer.find(FixedStr);
390 }
Chris Lattnereec96952009-09-27 07:56:52 +0000391
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000392 // Regex match.
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000393
Chris Lattnereec96952009-09-27 07:56:52 +0000394 // If there are variable uses, we need to create a temporary string with the
395 // actual value.
396 StringRef RegExToMatch = RegExStr;
397 std::string TmpStr;
398 if (!VariableUses.empty()) {
399 TmpStr = RegExStr;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000400
Chris Lattnereec96952009-09-27 07:56:52 +0000401 unsigned InsertOffset = 0;
402 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
Chris Lattnereec96952009-09-27 07:56:52 +0000403 std::string Value;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000404
405 if (VariableUses[i].first[0] == '@') {
406 if (!EvaluateExpression(VariableUses[i].first, Value))
407 return StringRef::npos;
408 } else {
409 StringMap<StringRef>::iterator it =
410 VariableTable.find(VariableUses[i].first);
411 // If the variable is undefined, return an error.
412 if (it == VariableTable.end())
413 return StringRef::npos;
414
415 // Look up the value and escape it so that we can plop it into the regex.
416 AddFixedStringToRegEx(it->second, Value);
417 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000418
Chris Lattnereec96952009-09-27 07:56:52 +0000419 // Plop it into the regex at the adjusted offset.
420 TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
421 Value.begin(), Value.end());
422 InsertOffset += Value.size();
423 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000424
Chris Lattnereec96952009-09-27 07:56:52 +0000425 // Match the newly constructed regex.
426 RegExToMatch = TmpStr;
427 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000428
429
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000430 SmallVector<StringRef, 4> MatchInfo;
Chris Lattnereec96952009-09-27 07:56:52 +0000431 if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000432 return StringRef::npos;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000433
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000434 // Successful regex match.
435 assert(!MatchInfo.empty() && "Didn't get any match");
436 StringRef FullMatch = MatchInfo[0];
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000437
Chris Lattnereec96952009-09-27 07:56:52 +0000438 // If this defines any variables, remember their values.
Eli Bendersky9756ca72012-12-01 21:54:48 +0000439 for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
440 E = VariableDefs.end();
441 I != E; ++I) {
442 assert(I->second < MatchInfo.size() && "Internal paren error");
443 VariableTable[I->first] = MatchInfo[I->second];
Chris Lattner94638f02009-09-25 17:29:36 +0000444 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000445
Chris Lattner5d6a05f2009-09-25 17:23:43 +0000446 MatchLen = FullMatch.size();
447 return FullMatch.data()-Buffer.data();
Chris Lattner52870082009-09-24 21:47:32 +0000448}
449
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000450unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
451 const StringMap<StringRef> &VariableTable) const {
452 // Just compute the number of matching characters. For regular expressions, we
453 // just compare against the regex itself and hope for the best.
454 //
455 // FIXME: One easy improvement here is have the regex lib generate a single
456 // example regular expression which matches, and use that as the example
457 // string.
458 StringRef ExampleString(FixedStr);
459 if (ExampleString.empty())
460 ExampleString = RegExStr;
461
Daniel Dunbar0806f9f2010-01-30 00:24:06 +0000462 // Only compare up to the first line in the buffer, or the string size.
463 StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
464 BufferPrefix = BufferPrefix.split('\n').first;
465 return BufferPrefix.edit_distance(ExampleString);
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000466}
467
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000468void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
469 const StringMap<StringRef> &VariableTable) const{
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000470 // If this was a regular expression using variables, print the current
471 // variable values.
472 if (!VariableUses.empty()) {
473 for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000474 SmallString<256> Msg;
475 raw_svector_ostream OS(Msg);
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000476 StringRef Var = VariableUses[i].first;
477 if (Var[0] == '@') {
478 std::string Value;
479 if (EvaluateExpression(Var, Value)) {
480 OS << "with expression \"";
481 OS.write_escaped(Var) << "\" equal to \"";
482 OS.write_escaped(Value) << "\"";
483 } else {
484 OS << "uses incorrect expression \"";
485 OS.write_escaped(Var) << "\"";
486 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000487 } else {
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000488 StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
489
490 // Check for undefined variable references.
491 if (it == VariableTable.end()) {
492 OS << "uses undefined variable \"";
493 OS.write_escaped(Var) << "\"";
494 } else {
495 OS << "with variable \"";
496 OS.write_escaped(Var) << "\" equal to \"";
497 OS.write_escaped(it->second) << "\"";
498 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000499 }
500
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000501 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
502 OS.str());
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000503 }
504 }
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000505
506 // Attempt to find the closest/best fuzzy match. Usually an error happens
507 // because some string in the output didn't exactly match. In these cases, we
508 // would like to show the user a best guess at what "should have" matched, to
509 // save them having to actually check the input manually.
510 size_t NumLinesForward = 0;
511 size_t Best = StringRef::npos;
512 double BestQuality = 0;
513
514 // Use an arbitrary 4k limit on how far we will search.
Dan Gohmane3a1e502010-01-29 21:57:46 +0000515 for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000516 if (Buffer[i] == '\n')
517 ++NumLinesForward;
518
Dan Gohmand8a55412010-01-29 21:55:16 +0000519 // Patterns have leading whitespace stripped, so skip whitespace when
520 // looking for something which looks like a pattern.
521 if (Buffer[i] == ' ' || Buffer[i] == '\t')
522 continue;
523
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000524 // Compute the "quality" of this match as an arbitrary combination of the
525 // match distance and the number of lines skipped to get to this match.
526 unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
527 double Quality = Distance + (NumLinesForward / 100.);
528
529 if (Quality < BestQuality || Best == StringRef::npos) {
530 Best = i;
531 BestQuality = Quality;
532 }
533 }
534
Daniel Dunbar7a68e0d2010-03-19 18:07:43 +0000535 // Print the "possible intended match here" line if we found something
536 // reasonable and not equal to what we showed in the "scanning from here"
537 // line.
538 if (Best && Best != StringRef::npos && BestQuality < 50) {
539 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000540 SourceMgr::DK_Note, "possible intended match here");
Daniel Dunbaread2dac2009-11-22 22:59:26 +0000541
542 // FIXME: If we wanted to be really friendly we would show why the match
543 // failed, as it can be hard to spot simple one character differences.
544 }
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000545}
Chris Lattnera29703e2009-09-24 20:39:13 +0000546
Eli Bendersky4db65112012-12-02 16:02:41 +0000547size_t Pattern::FindRegexVarEnd(StringRef Str) {
548 // Offset keeps track of the current offset within the input Str
549 size_t Offset = 0;
550 // [...] Nesting depth
551 size_t BracketDepth = 0;
552
553 while (!Str.empty()) {
554 if (Str.startswith("]]") && BracketDepth == 0)
555 return Offset;
556 if (Str[0] == '\\') {
557 // Backslash escapes the next char within regexes, so skip them both.
558 Str = Str.substr(2);
559 Offset += 2;
560 } else {
561 switch (Str[0]) {
562 default:
563 break;
564 case '[':
565 BracketDepth++;
566 break;
567 case ']':
568 assert(BracketDepth > 0 && "Invalid regex");
569 BracketDepth--;
570 break;
571 }
572 Str = Str.substr(1);
573 Offset++;
574 }
575 }
576
577 return StringRef::npos;
578}
579
580
Chris Lattnera29703e2009-09-24 20:39:13 +0000581//===----------------------------------------------------------------------===//
582// Check Strings.
583//===----------------------------------------------------------------------===//
Chris Lattner9fc66782009-09-24 20:25:55 +0000584
585/// CheckString - This is a check that we found in the input file.
586struct CheckString {
587 /// Pat - The pattern to match.
588 Pattern Pat;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000589
Chris Lattner207e1bc2009-08-15 17:41:04 +0000590 /// Loc - The location in the match file that the check string was specified.
591 SMLoc Loc;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000592
Chris Lattner5dafafd2009-08-15 18:32:21 +0000593 /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
594 /// to a CHECK: directive.
595 bool IsCheckNext;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000596
Michael Liao95ab3262013-05-14 20:34:12 +0000597 /// DagNotStrings - These are all of the strings that are disallowed from
Chris Lattnerf15380b2009-09-20 22:35:26 +0000598 /// occurring between this match string and the previous one (or start of
599 /// file).
Michael Liao95ab3262013-05-14 20:34:12 +0000600 std::vector<Pattern> DagNotStrings;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000601
Chris Lattner9fc66782009-09-24 20:25:55 +0000602 CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
603 : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
Michael Liao7efbbd62013-05-14 20:29:52 +0000604
Michael Liao95ab3262013-05-14 20:34:12 +0000605 /// Check - Match check string and its "not strings" and/or "dag strings".
Michael Liao7efbbd62013-05-14 20:29:52 +0000606 size_t Check(const SourceMgr &SM, StringRef Buffer, size_t &MatchLen,
607 StringMap<StringRef> &VariableTable) const;
608
609 /// CheckNext - Verify there is a single line in the given buffer.
610 bool CheckNext(const SourceMgr &SM, StringRef Buffer) const;
611
612 /// CheckNot - Verify there's no "not strings" in the given buffer.
613 bool CheckNot(const SourceMgr &SM, StringRef Buffer,
Michael Liao95ab3262013-05-14 20:34:12 +0000614 const std::vector<const Pattern *> &NotStrings,
Michael Liao7efbbd62013-05-14 20:29:52 +0000615 StringMap<StringRef> &VariableTable) const;
Michael Liao95ab3262013-05-14 20:34:12 +0000616
617 /// CheckDag - Match "dag strings" and their mixed "not strings".
618 size_t CheckDag(const SourceMgr &SM, StringRef Buffer,
619 std::vector<const Pattern *> &NotStrings,
620 StringMap<StringRef> &VariableTable) const;
Chris Lattner207e1bc2009-08-15 17:41:04 +0000621};
622
Guy Benyei4cc74fc2013-02-06 20:40:38 +0000623/// Canonicalize whitespaces in the input file. Line endings are replaced
624/// with UNIX-style '\n'.
625///
626/// \param PreserveHorizontal Don't squash consecutive horizontal whitespace
627/// characters to a single space.
628static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB,
629 bool PreserveHorizontal) {
Chris Lattner4c842dd2010-04-05 22:42:30 +0000630 SmallString<128> NewFile;
Chris Lattneradea46e2009-09-24 20:45:07 +0000631 NewFile.reserve(MB->getBufferSize());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000632
Chris Lattneradea46e2009-09-24 20:45:07 +0000633 for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
634 Ptr != End; ++Ptr) {
NAKAMURA Takumi9f6e03f2010-11-14 03:28:22 +0000635 // Eliminate trailing dosish \r.
636 if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
637 continue;
638 }
639
Michael Liaoc16f8c52013-04-25 18:54:02 +0000640 // If current char is not a horizontal whitespace or if horizontal
Guy Benyei4cc74fc2013-02-06 20:40:38 +0000641 // whitespace canonicalization is disabled, dump it to output as is.
642 if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) {
Chris Lattneradea46e2009-09-24 20:45:07 +0000643 NewFile.push_back(*Ptr);
644 continue;
645 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000646
Chris Lattneradea46e2009-09-24 20:45:07 +0000647 // Otherwise, add one space and advance over neighboring space.
648 NewFile.push_back(' ');
649 while (Ptr+1 != End &&
650 (Ptr[1] == ' ' || Ptr[1] == '\t'))
651 ++Ptr;
652 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000653
Chris Lattneradea46e2009-09-24 20:45:07 +0000654 // Free the old buffer and return a new one.
655 MemoryBuffer *MB2 =
Chris Lattner4c842dd2010-04-05 22:42:30 +0000656 MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000657
Chris Lattneradea46e2009-09-24 20:45:07 +0000658 delete MB;
659 return MB2;
660}
661
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000662
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000663/// ReadCheckFile - Read the check file, which specifies the sequence of
664/// expected strings. The strings are added to the CheckStrings vector.
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +0000665/// Returns true in case of an error, false otherwise.
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000666static bool ReadCheckFile(SourceMgr &SM,
Chris Lattner207e1bc2009-08-15 17:41:04 +0000667 std::vector<CheckString> &CheckStrings) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +0000668 OwningPtr<MemoryBuffer> File;
669 if (error_code ec =
Rafael Espindoladd5af272013-06-25 05:28:34 +0000670 MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) {
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000671 errs() << "Could not open check file '" << CheckFilename << "': "
Michael J. Spencer333fb042010-12-09 17:36:48 +0000672 << ec.message() << '\n';
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000673 return true;
674 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000675
Chris Lattneradea46e2009-09-24 20:45:07 +0000676 // If we want to canonicalize whitespace, strip excess whitespace from the
Guy Benyei4cc74fc2013-02-06 20:40:38 +0000677 // buffer containing the CHECK lines. Remove DOS style line endings.
Benjamin Kramer7cdba152013-03-23 13:56:23 +0000678 MemoryBuffer *F =
679 CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000680
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000681 SM.AddNewSourceBuffer(F, SMLoc());
682
Chris Lattnerd7e25052009-08-15 18:00:42 +0000683 // Find all instances of CheckPrefix followed by : in the file.
Chris Lattner96077032009-09-20 22:11:44 +0000684 StringRef Buffer = F->getBuffer();
Michael Liao95ab3262013-05-14 20:34:12 +0000685 std::vector<Pattern> DagNotMatches;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000686
Eli Bendersky1e5cbcb2012-11-30 14:22:14 +0000687 // LineNumber keeps track of the line on which CheckPrefix instances are
688 // found.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000689 unsigned LineNumber = 1;
690
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000691 while (1) {
692 // See if Prefix occurs in the memory buffer.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000693 size_t PrefixLoc = Buffer.find(CheckPrefix);
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000694 // If we didn't find a match, we're done.
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000695 if (PrefixLoc == StringRef::npos)
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000696 break;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000697
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000698 LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
699
700 Buffer = Buffer.substr(PrefixLoc);
701
Chris Lattner96077032009-09-20 22:11:44 +0000702 const char *CheckPrefixStart = Buffer.data();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000703
Chris Lattner5dafafd2009-08-15 18:32:21 +0000704 // When we find a check prefix, keep track of whether we find CHECK: or
705 // CHECK-NEXT:
Michael Liao95ab3262013-05-14 20:34:12 +0000706 bool IsCheckNext = false, IsCheckNot = false, IsCheckDag = false;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000707
Chris Lattnerd7e25052009-08-15 18:00:42 +0000708 // Verify that the : is present after the prefix.
Chris Lattner96077032009-09-20 22:11:44 +0000709 if (Buffer[CheckPrefix.size()] == ':') {
710 Buffer = Buffer.substr(CheckPrefix.size()+1);
Chris Lattner96077032009-09-20 22:11:44 +0000711 } else if (Buffer.size() > CheckPrefix.size()+6 &&
712 memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Benjamin Kramer30ce40e2012-09-18 20:51:39 +0000713 Buffer = Buffer.substr(CheckPrefix.size()+6);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000714 IsCheckNext = true;
Chris Lattnerf15380b2009-09-20 22:35:26 +0000715 } else if (Buffer.size() > CheckPrefix.size()+5 &&
716 memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
Benjamin Kramer30ce40e2012-09-18 20:51:39 +0000717 Buffer = Buffer.substr(CheckPrefix.size()+5);
Chris Lattnerf15380b2009-09-20 22:35:26 +0000718 IsCheckNot = true;
Michael Liao95ab3262013-05-14 20:34:12 +0000719 } else if (Buffer.size() > CheckPrefix.size()+5 &&
720 memcmp(Buffer.data()+CheckPrefix.size(), "-DAG:", 5) == 0) {
721 Buffer = Buffer.substr(CheckPrefix.size()+5);
722 IsCheckDag = true;
Chris Lattner5dafafd2009-08-15 18:32:21 +0000723 } else {
Chris Lattner96077032009-09-20 22:11:44 +0000724 Buffer = Buffer.substr(1);
Chris Lattnerd7e25052009-08-15 18:00:42 +0000725 continue;
726 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000727
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000728 // Okay, we found the prefix, yay. Remember the rest of the line, but
729 // ignore leading and trailing whitespace.
Chris Lattnerf15380b2009-09-20 22:35:26 +0000730 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000731
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000732 // Scan ahead to the end of line.
Chris Lattner96077032009-09-20 22:11:44 +0000733 size_t EOL = Buffer.find_first_of("\n\r");
Chris Lattnera29703e2009-09-24 20:39:13 +0000734
Dan Gohmane5463432010-01-29 21:53:18 +0000735 // Remember the location of the start of the pattern, for diagnostics.
736 SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
737
Chris Lattnera29703e2009-09-24 20:39:13 +0000738 // Parse the pattern.
739 Pattern P;
Alexander Kornienko70a870a2012-11-14 21:07:37 +0000740 if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000741 return true;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000742
Michael Liao95ab3262013-05-14 20:34:12 +0000743 P.setMatchNot(IsCheckNot);
744 P.setMatchDag(IsCheckDag);
745
Chris Lattnera29703e2009-09-24 20:39:13 +0000746 Buffer = Buffer.substr(EOL);
747
Chris Lattner5dafafd2009-08-15 18:32:21 +0000748 // Verify that CHECK-NEXT lines have at least one CHECK line before them.
749 if (IsCheckNext && CheckStrings.empty()) {
750 SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000751 SourceMgr::DK_Error,
Chris Lattner5dafafd2009-08-15 18:32:21 +0000752 "found '"+CheckPrefix+"-NEXT:' without previous '"+
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000753 CheckPrefix+ ": line");
Chris Lattner5dafafd2009-08-15 18:32:21 +0000754 return true;
755 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000756
Michael Liao95ab3262013-05-14 20:34:12 +0000757 // Handle CHECK-DAG/-NOT.
758 if (IsCheckDag || IsCheckNot) {
759 DagNotMatches.push_back(P);
Chris Lattnera29703e2009-09-24 20:39:13 +0000760 continue;
761 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000762
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000763 // Okay, add the string we captured to the output vector and move on.
Chris Lattner9fc66782009-09-24 20:25:55 +0000764 CheckStrings.push_back(CheckString(P,
Dan Gohmane5463432010-01-29 21:53:18 +0000765 PatternLoc,
Chris Lattner5dafafd2009-08-15 18:32:21 +0000766 IsCheckNext));
Michael Liao95ab3262013-05-14 20:34:12 +0000767 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000768 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000769
Michael Liao95ab3262013-05-14 20:34:12 +0000770 // Add an EOF pattern for any trailing CHECK-DAG/-NOTs.
771 if (!DagNotMatches.empty()) {
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000772 CheckStrings.push_back(CheckString(Pattern(true),
773 SMLoc::getFromPointer(Buffer.data()),
774 false));
Michael Liao95ab3262013-05-14 20:34:12 +0000775 std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
Jakob Stoklund Olesen824c10e2010-10-15 17:47:12 +0000776 }
777
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000778 if (CheckStrings.empty()) {
Chris Lattnerd7e25052009-08-15 18:00:42 +0000779 errs() << "error: no check strings found with prefix '" << CheckPrefix
780 << ":'\n";
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000781 return true;
782 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000783
Chris Lattner81cb8ca2009-07-08 18:44:05 +0000784 return false;
785}
786
Michael Liao95ab3262013-05-14 20:34:12 +0000787static void PrintCheckFailed(const SourceMgr &SM, const SMLoc &Loc,
788 const Pattern &Pat, StringRef Buffer,
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000789 StringMap<StringRef> &VariableTable) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000790 // Otherwise, we have an error, emit an error message.
Michael Liao95ab3262013-05-14 20:34:12 +0000791 SM.PrintMessage(Loc, SourceMgr::DK_Error,
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000792 "expected string not found in input");
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000793
Chris Lattner5dafafd2009-08-15 18:32:21 +0000794 // Print the "scanning from here" line. If the current position is at the
795 // end of a line, advance to the start of the next line.
Chris Lattner96077032009-09-20 22:11:44 +0000796 Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000797
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000798 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
799 "scanning from here");
Daniel Dunbarfafe93c2009-11-22 22:08:06 +0000800
801 // Allow the pattern to print additional information if desired.
Michael Liao95ab3262013-05-14 20:34:12 +0000802 Pat.PrintFailureInfo(SM, Buffer, VariableTable);
803}
804
805static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
806 StringRef Buffer,
807 StringMap<StringRef> &VariableTable) {
808 PrintCheckFailed(SM, CheckStr.Loc, CheckStr.Pat, Buffer, VariableTable);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000809}
810
Chris Lattner3711b7a2009-09-20 22:42:44 +0000811/// CountNumNewlinesBetween - Count the number of newlines in the specified
812/// range.
813static unsigned CountNumNewlinesBetween(StringRef Range) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000814 unsigned NumNewLines = 0;
Chris Lattner3711b7a2009-09-20 22:42:44 +0000815 while (1) {
Chris Lattner5dafafd2009-08-15 18:32:21 +0000816 // Scan for newline.
Chris Lattner3711b7a2009-09-20 22:42:44 +0000817 Range = Range.substr(Range.find_first_of("\n\r"));
818 if (Range.empty()) return NumNewLines;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000819
Chris Lattner5dafafd2009-08-15 18:32:21 +0000820 ++NumNewLines;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +0000821
Chris Lattner5dafafd2009-08-15 18:32:21 +0000822 // Handle \n\r and \r\n as a single newline.
Chris Lattner3711b7a2009-09-20 22:42:44 +0000823 if (Range.size() > 1 &&
824 (Range[1] == '\n' || Range[1] == '\r') &&
825 (Range[0] != Range[1]))
826 Range = Range.substr(1);
827 Range = Range.substr(1);
Chris Lattner5dafafd2009-08-15 18:32:21 +0000828 }
Chris Lattner5dafafd2009-08-15 18:32:21 +0000829}
830
Michael Liao7efbbd62013-05-14 20:29:52 +0000831size_t CheckString::Check(const SourceMgr &SM, StringRef Buffer,
832 size_t &MatchLen,
833 StringMap<StringRef> &VariableTable) const {
Michael Liao95ab3262013-05-14 20:34:12 +0000834 size_t LastPos = 0;
835 std::vector<const Pattern *> NotStrings;
836
837 // Match "dag strings" (with mixed "not strings" if any).
838 LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable);
839 if (LastPos == StringRef::npos)
840 return StringRef::npos;
841
842 // Match itself from the last position after matching CHECK-DAG.
843 StringRef MatchBuffer = Buffer.substr(LastPos);
844 size_t MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
Michael Liao7efbbd62013-05-14 20:29:52 +0000845 if (MatchPos == StringRef::npos) {
Michael Liao95ab3262013-05-14 20:34:12 +0000846 PrintCheckFailed(SM, *this, MatchBuffer, VariableTable);
Michael Liao7efbbd62013-05-14 20:29:52 +0000847 return StringRef::npos;
848 }
Michael Liao95ab3262013-05-14 20:34:12 +0000849 MatchPos += LastPos;
Michael Liao7efbbd62013-05-14 20:29:52 +0000850
Michael Liao95ab3262013-05-14 20:34:12 +0000851 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
Michael Liao7efbbd62013-05-14 20:29:52 +0000852
853 // If this check is a "CHECK-NEXT", verify that the previous match was on
854 // the previous line (i.e. that there is one newline between them).
855 if (CheckNext(SM, SkippedRegion))
856 return StringRef::npos;
857
858 // If this match had "not strings", verify that they don't exist in the
859 // skipped region.
Michael Liao95ab3262013-05-14 20:34:12 +0000860 if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable))
Michael Liao7efbbd62013-05-14 20:29:52 +0000861 return StringRef::npos;
862
863 return MatchPos;
864}
865
866bool CheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
867 if (!IsCheckNext)
868 return false;
869
870 // Count the number of newlines between the previous match and this one.
871 assert(Buffer.data() !=
872 SM.getMemoryBuffer(
873 SM.FindBufferContainingLoc(
874 SMLoc::getFromPointer(Buffer.data())))->getBufferStart() &&
875 "CHECK-NEXT can't be the first check in a file");
876
877 unsigned NumNewLines = CountNumNewlinesBetween(Buffer);
878
879 if (NumNewLines == 0) {
880 SM.PrintMessage(Loc, SourceMgr::DK_Error, CheckPrefix+
881 "-NEXT: is on the same line as previous match");
882 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
883 SourceMgr::DK_Note, "'next' match was here");
884 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
885 "previous match ended here");
886 return true;
887 }
888
889 if (NumNewLines != 1) {
890 SM.PrintMessage(Loc, SourceMgr::DK_Error, CheckPrefix+
891 "-NEXT: is not on the line after the previous match");
892 SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()),
893 SourceMgr::DK_Note, "'next' match was here");
894 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
895 "previous match ended here");
896 return true;
897 }
898
899 return false;
900}
901
902bool CheckString::CheckNot(const SourceMgr &SM, StringRef Buffer,
Michael Liao95ab3262013-05-14 20:34:12 +0000903 const std::vector<const Pattern *> &NotStrings,
Michael Liao7efbbd62013-05-14 20:29:52 +0000904 StringMap<StringRef> &VariableTable) const {
905 for (unsigned ChunkNo = 0, e = NotStrings.size();
906 ChunkNo != e; ++ChunkNo) {
Michael Liao95ab3262013-05-14 20:34:12 +0000907 const Pattern *Pat = NotStrings[ChunkNo];
908 assert(Pat->getMatchNot() && "Expect CHECK-NOT!");
909
Michael Liao7efbbd62013-05-14 20:29:52 +0000910 size_t MatchLen = 0;
Michael Liao95ab3262013-05-14 20:34:12 +0000911 size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);
Michael Liao7efbbd62013-05-14 20:29:52 +0000912
913 if (Pos == StringRef::npos) continue;
914
915 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()+Pos),
916 SourceMgr::DK_Error,
917 CheckPrefix+"-NOT: string occurred!");
Michael Liao95ab3262013-05-14 20:34:12 +0000918 SM.PrintMessage(Pat->getLoc(), SourceMgr::DK_Note,
Michael Liao7efbbd62013-05-14 20:29:52 +0000919 CheckPrefix+"-NOT: pattern specified here");
920 return true;
921 }
922
923 return false;
924}
925
Michael Liao95ab3262013-05-14 20:34:12 +0000926size_t CheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
927 std::vector<const Pattern *> &NotStrings,
928 StringMap<StringRef> &VariableTable) const {
929 if (DagNotStrings.empty())
930 return 0;
931
932 size_t LastPos = 0;
933 size_t StartPos = LastPos;
934
935 for (unsigned ChunkNo = 0, e = DagNotStrings.size();
936 ChunkNo != e; ++ChunkNo) {
937 const Pattern &Pat = DagNotStrings[ChunkNo];
938
939 assert((Pat.getMatchDag() ^ Pat.getMatchNot()) &&
940 "Invalid CHECK-DAG or CHECK-NOT!");
941
942 if (Pat.getMatchNot()) {
943 NotStrings.push_back(&Pat);
944 continue;
945 }
946
947 assert(Pat.getMatchDag() && "Expect CHECK-DAG!");
948
949 size_t MatchLen = 0, MatchPos;
950
951 // CHECK-DAG always matches from the start.
952 StringRef MatchBuffer = Buffer.substr(StartPos);
953 MatchPos = Pat.Match(MatchBuffer, MatchLen, VariableTable);
954 // With a group of CHECK-DAGs, a single mismatching means the match on
955 // that group of CHECK-DAGs fails immediately.
956 if (MatchPos == StringRef::npos) {
957 PrintCheckFailed(SM, Pat.getLoc(), Pat, MatchBuffer, VariableTable);
958 return StringRef::npos;
959 }
960 // Re-calc it as the offset relative to the start of the original string.
961 MatchPos += StartPos;
962
963 if (!NotStrings.empty()) {
964 if (MatchPos < LastPos) {
965 // Reordered?
966 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + MatchPos),
967 SourceMgr::DK_Error,
968 CheckPrefix+"-DAG: found a match of CHECK-DAG"
969 " reordering across a CHECK-NOT");
970 SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + LastPos),
971 SourceMgr::DK_Note,
972 CheckPrefix+"-DAG: the farthest match of CHECK-DAG"
973 " is found here");
974 SM.PrintMessage(NotStrings[0]->getLoc(), SourceMgr::DK_Note,
975 CheckPrefix+"-NOT: the crossed pattern specified"
976 " here");
977 SM.PrintMessage(Pat.getLoc(), SourceMgr::DK_Note,
978 CheckPrefix+"-DAG: the reordered pattern specified"
979 " here");
980 return StringRef::npos;
981 }
982 // All subsequent CHECK-DAGs should be matched from the farthest
983 // position of all precedent CHECK-DAGs (including this one.)
984 StartPos = LastPos;
985 // If there's CHECK-NOTs between two CHECK-DAGs or from CHECK to
986 // CHECK-DAG, verify that there's no 'not' strings occurred in that
987 // region.
988 StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
989 size_t Pos = CheckNot(SM, SkippedRegion, NotStrings, VariableTable);
990 if (Pos != StringRef::npos)
991 return StringRef::npos;
992 // Clear "not strings".
993 NotStrings.clear();
994 }
995
996 // Update the last position with CHECK-DAG matches.
997 LastPos = std::max(MatchPos + MatchLen, LastPos);
998 }
999
1000 return LastPos;
1001}
1002
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001003int main(int argc, char **argv) {
1004 sys::PrintStackTraceOnErrorSignal();
1005 PrettyStackTraceProgram X(argc, argv);
1006 cl::ParseCommandLineOptions(argc, argv);
1007
1008 SourceMgr SM;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +00001009
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001010 // Read the expected strings from the check file.
Chris Lattner207e1bc2009-08-15 17:41:04 +00001011 std::vector<CheckString> CheckStrings;
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001012 if (ReadCheckFile(SM, CheckStrings))
1013 return 2;
1014
1015 // Open the file to check and add it to SourceMgr.
Michael J. Spencer3ff95632010-12-16 03:29:14 +00001016 OwningPtr<MemoryBuffer> File;
1017 if (error_code ec =
Rafael Espindoladd5af272013-06-25 05:28:34 +00001018 MemoryBuffer::getFileOrSTDIN(InputFilename, File)) {
Mikhail Glushenkov7112c862010-08-20 17:38:38 +00001019 errs() << "Could not open input file '" << InputFilename << "': "
Michael J. Spencer333fb042010-12-09 17:36:48 +00001020 << ec.message() << '\n';
Eli Bendersky7f8e76f2012-11-30 13:51:33 +00001021 return 2;
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001022 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +00001023
Benjamin Kramer7cdba152013-03-23 13:56:23 +00001024 if (File->getBufferSize() == 0) {
Chris Lattner1aac1862011-02-09 16:46:02 +00001025 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
Eli Bendersky7f8e76f2012-11-30 13:51:33 +00001026 return 2;
Chris Lattner1aac1862011-02-09 16:46:02 +00001027 }
Benjamin Kramer7cdba152013-03-23 13:56:23 +00001028
Chris Lattner88a7e9e2009-07-11 18:58:15 +00001029 // Remove duplicate spaces in the input file if requested.
Guy Benyei4cc74fc2013-02-06 20:40:38 +00001030 // Remove DOS style line endings.
Benjamin Kramer7cdba152013-03-23 13:56:23 +00001031 MemoryBuffer *F =
1032 CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +00001033
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001034 SM.AddNewSourceBuffer(F, SMLoc());
Mikhail Glushenkov7112c862010-08-20 17:38:38 +00001035
Chris Lattnereec96952009-09-27 07:56:52 +00001036 /// VariableTable - This holds all the current filecheck variables.
1037 StringMap<StringRef> VariableTable;
Mikhail Glushenkov7112c862010-08-20 17:38:38 +00001038
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001039 // Check that we have all of the expected strings, in order, in the input
1040 // file.
Chris Lattner96077032009-09-20 22:11:44 +00001041 StringRef Buffer = F->getBuffer();
Mikhail Glushenkov7112c862010-08-20 17:38:38 +00001042
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001043 for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
Chris Lattner207e1bc2009-08-15 17:41:04 +00001044 const CheckString &CheckStr = CheckStrings[StrNo];
Mikhail Glushenkov7112c862010-08-20 17:38:38 +00001045
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001046 // Find StrNo in the file.
Chris Lattner9fc66782009-09-24 20:25:55 +00001047 size_t MatchLen = 0;
Michael Liao7efbbd62013-05-14 20:29:52 +00001048 size_t MatchPos = CheckStr.Check(SM, Buffer, MatchLen, VariableTable);
Mikhail Glushenkov7112c862010-08-20 17:38:38 +00001049
Michael Liao7efbbd62013-05-14 20:29:52 +00001050 if (MatchPos == StringRef::npos)
Chris Lattner5dafafd2009-08-15 18:32:21 +00001051 return 1;
Chris Lattner3711b7a2009-09-20 22:42:44 +00001052
Michael Liao7efbbd62013-05-14 20:29:52 +00001053 Buffer = Buffer.substr(MatchPos + MatchLen);
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001054 }
Mikhail Glushenkov7112c862010-08-20 17:38:38 +00001055
Chris Lattner81cb8ca2009-07-08 18:44:05 +00001056 return 0;
1057}