1*b5893f02SDimitry Andric //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2*b5893f02SDimitry Andric //
3*b5893f02SDimitry Andric // The LLVM Compiler Infrastructure
4*b5893f02SDimitry Andric //
5*b5893f02SDimitry Andric // This file is distributed under the University of Illinois Open Source
6*b5893f02SDimitry Andric // License. See LICENSE.TXT for details.
7*b5893f02SDimitry Andric //
8*b5893f02SDimitry Andric //===----------------------------------------------------------------------===//
9*b5893f02SDimitry Andric //
10*b5893f02SDimitry Andric // FileCheck does a line-by line check of a file that validates whether it
11*b5893f02SDimitry Andric // contains the expected content. This is useful for regression tests etc.
12*b5893f02SDimitry Andric //
13*b5893f02SDimitry Andric // This file implements most of the API that will be used by the FileCheck utility
14*b5893f02SDimitry Andric // as well as various unittests.
15*b5893f02SDimitry Andric //===----------------------------------------------------------------------===//
16*b5893f02SDimitry Andric
17*b5893f02SDimitry Andric #include "llvm/Support/FileCheck.h"
18*b5893f02SDimitry Andric #include "llvm/ADT/StringSet.h"
19*b5893f02SDimitry Andric #include "llvm/Support/FormatVariadic.h"
20*b5893f02SDimitry Andric #include <cstdint>
21*b5893f02SDimitry Andric #include <list>
22*b5893f02SDimitry Andric #include <map>
23*b5893f02SDimitry Andric #include <tuple>
24*b5893f02SDimitry Andric #include <utility>
25*b5893f02SDimitry Andric
26*b5893f02SDimitry Andric using namespace llvm;
27*b5893f02SDimitry Andric
28*b5893f02SDimitry Andric /// Parses the given string into the Pattern.
29*b5893f02SDimitry Andric ///
30*b5893f02SDimitry Andric /// \p Prefix provides which prefix is being matched, \p SM provides the
31*b5893f02SDimitry Andric /// SourceMgr used for error reports, and \p LineNumber is the line number in
32*b5893f02SDimitry Andric /// the input file from which the pattern string was read. Returns true in
33*b5893f02SDimitry Andric /// case of an error, false otherwise.
ParsePattern(StringRef PatternStr,StringRef Prefix,SourceMgr & SM,unsigned LineNumber,const FileCheckRequest & Req)34*b5893f02SDimitry Andric bool FileCheckPattern::ParsePattern(StringRef PatternStr, StringRef Prefix,
35*b5893f02SDimitry Andric SourceMgr &SM, unsigned LineNumber,
36*b5893f02SDimitry Andric const FileCheckRequest &Req) {
37*b5893f02SDimitry Andric bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
38*b5893f02SDimitry Andric
39*b5893f02SDimitry Andric this->LineNumber = LineNumber;
40*b5893f02SDimitry Andric PatternLoc = SMLoc::getFromPointer(PatternStr.data());
41*b5893f02SDimitry Andric
42*b5893f02SDimitry Andric if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
43*b5893f02SDimitry Andric // Ignore trailing whitespace.
44*b5893f02SDimitry Andric while (!PatternStr.empty() &&
45*b5893f02SDimitry Andric (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
46*b5893f02SDimitry Andric PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
47*b5893f02SDimitry Andric
48*b5893f02SDimitry Andric // Check that there is something on the line.
49*b5893f02SDimitry Andric if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
50*b5893f02SDimitry Andric SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
51*b5893f02SDimitry Andric "found empty check string with prefix '" + Prefix + ":'");
52*b5893f02SDimitry Andric return true;
53*b5893f02SDimitry Andric }
54*b5893f02SDimitry Andric
55*b5893f02SDimitry Andric if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
56*b5893f02SDimitry Andric SM.PrintMessage(
57*b5893f02SDimitry Andric PatternLoc, SourceMgr::DK_Error,
58*b5893f02SDimitry Andric "found non-empty check string for empty check with prefix '" + Prefix +
59*b5893f02SDimitry Andric ":'");
60*b5893f02SDimitry Andric return true;
61*b5893f02SDimitry Andric }
62*b5893f02SDimitry Andric
63*b5893f02SDimitry Andric if (CheckTy == Check::CheckEmpty) {
64*b5893f02SDimitry Andric RegExStr = "(\n$)";
65*b5893f02SDimitry Andric return false;
66*b5893f02SDimitry Andric }
67*b5893f02SDimitry Andric
68*b5893f02SDimitry Andric // Check to see if this is a fixed string, or if it has regex pieces.
69*b5893f02SDimitry Andric if (!MatchFullLinesHere &&
70*b5893f02SDimitry Andric (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
71*b5893f02SDimitry Andric PatternStr.find("[[") == StringRef::npos))) {
72*b5893f02SDimitry Andric FixedStr = PatternStr;
73*b5893f02SDimitry Andric return false;
74*b5893f02SDimitry Andric }
75*b5893f02SDimitry Andric
76*b5893f02SDimitry Andric if (MatchFullLinesHere) {
77*b5893f02SDimitry Andric RegExStr += '^';
78*b5893f02SDimitry Andric if (!Req.NoCanonicalizeWhiteSpace)
79*b5893f02SDimitry Andric RegExStr += " *";
80*b5893f02SDimitry Andric }
81*b5893f02SDimitry Andric
82*b5893f02SDimitry Andric // Paren value #0 is for the fully matched string. Any new parenthesized
83*b5893f02SDimitry Andric // values add from there.
84*b5893f02SDimitry Andric unsigned CurParen = 1;
85*b5893f02SDimitry Andric
86*b5893f02SDimitry Andric // Otherwise, there is at least one regex piece. Build up the regex pattern
87*b5893f02SDimitry Andric // by escaping scary characters in fixed strings, building up one big regex.
88*b5893f02SDimitry Andric while (!PatternStr.empty()) {
89*b5893f02SDimitry Andric // RegEx matches.
90*b5893f02SDimitry Andric if (PatternStr.startswith("{{")) {
91*b5893f02SDimitry Andric // This is the start of a regex match. Scan for the }}.
92*b5893f02SDimitry Andric size_t End = PatternStr.find("}}");
93*b5893f02SDimitry Andric if (End == StringRef::npos) {
94*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
95*b5893f02SDimitry Andric SourceMgr::DK_Error,
96*b5893f02SDimitry Andric "found start of regex string with no end '}}'");
97*b5893f02SDimitry Andric return true;
98*b5893f02SDimitry Andric }
99*b5893f02SDimitry Andric
100*b5893f02SDimitry Andric // Enclose {{}} patterns in parens just like [[]] even though we're not
101*b5893f02SDimitry Andric // capturing the result for any purpose. This is required in case the
102*b5893f02SDimitry Andric // expression contains an alternation like: CHECK: abc{{x|z}}def. We
103*b5893f02SDimitry Andric // want this to turn into: "abc(x|z)def" not "abcx|zdef".
104*b5893f02SDimitry Andric RegExStr += '(';
105*b5893f02SDimitry Andric ++CurParen;
106*b5893f02SDimitry Andric
107*b5893f02SDimitry Andric if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
108*b5893f02SDimitry Andric return true;
109*b5893f02SDimitry Andric RegExStr += ')';
110*b5893f02SDimitry Andric
111*b5893f02SDimitry Andric PatternStr = PatternStr.substr(End + 2);
112*b5893f02SDimitry Andric continue;
113*b5893f02SDimitry Andric }
114*b5893f02SDimitry Andric
115*b5893f02SDimitry Andric // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
116*b5893f02SDimitry Andric // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
117*b5893f02SDimitry Andric // second form is [[foo]] which is a reference to foo. The variable name
118*b5893f02SDimitry Andric // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
119*b5893f02SDimitry Andric // it. This is to catch some common errors.
120*b5893f02SDimitry Andric if (PatternStr.startswith("[[")) {
121*b5893f02SDimitry Andric // Find the closing bracket pair ending the match. End is going to be an
122*b5893f02SDimitry Andric // offset relative to the beginning of the match string.
123*b5893f02SDimitry Andric size_t End = FindRegexVarEnd(PatternStr.substr(2), SM);
124*b5893f02SDimitry Andric
125*b5893f02SDimitry Andric if (End == StringRef::npos) {
126*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
127*b5893f02SDimitry Andric SourceMgr::DK_Error,
128*b5893f02SDimitry Andric "invalid named regex reference, no ]] found");
129*b5893f02SDimitry Andric return true;
130*b5893f02SDimitry Andric }
131*b5893f02SDimitry Andric
132*b5893f02SDimitry Andric StringRef MatchStr = PatternStr.substr(2, End);
133*b5893f02SDimitry Andric PatternStr = PatternStr.substr(End + 4);
134*b5893f02SDimitry Andric
135*b5893f02SDimitry Andric // Get the regex name (e.g. "foo").
136*b5893f02SDimitry Andric size_t NameEnd = MatchStr.find(':');
137*b5893f02SDimitry Andric StringRef Name = MatchStr.substr(0, NameEnd);
138*b5893f02SDimitry Andric
139*b5893f02SDimitry Andric if (Name.empty()) {
140*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
141*b5893f02SDimitry Andric "invalid name in named regex: empty name");
142*b5893f02SDimitry Andric return true;
143*b5893f02SDimitry Andric }
144*b5893f02SDimitry Andric
145*b5893f02SDimitry Andric // Verify that the name/expression is well formed. FileCheck currently
146*b5893f02SDimitry Andric // supports @LINE, @LINE+number, @LINE-number expressions. The check here
147*b5893f02SDimitry Andric // is relaxed, more strict check is performed in \c EvaluateExpression.
148*b5893f02SDimitry Andric bool IsExpression = false;
149*b5893f02SDimitry Andric for (unsigned i = 0, e = Name.size(); i != e; ++i) {
150*b5893f02SDimitry Andric if (i == 0) {
151*b5893f02SDimitry Andric if (Name[i] == '$') // Global vars start with '$'
152*b5893f02SDimitry Andric continue;
153*b5893f02SDimitry Andric if (Name[i] == '@') {
154*b5893f02SDimitry Andric if (NameEnd != StringRef::npos) {
155*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
156*b5893f02SDimitry Andric SourceMgr::DK_Error,
157*b5893f02SDimitry Andric "invalid name in named regex definition");
158*b5893f02SDimitry Andric return true;
159*b5893f02SDimitry Andric }
160*b5893f02SDimitry Andric IsExpression = true;
161*b5893f02SDimitry Andric continue;
162*b5893f02SDimitry Andric }
163*b5893f02SDimitry Andric }
164*b5893f02SDimitry Andric if (Name[i] != '_' && !isalnum(Name[i]) &&
165*b5893f02SDimitry Andric (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
166*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Name.data() + i),
167*b5893f02SDimitry Andric SourceMgr::DK_Error, "invalid name in named regex");
168*b5893f02SDimitry Andric return true;
169*b5893f02SDimitry Andric }
170*b5893f02SDimitry Andric }
171*b5893f02SDimitry Andric
172*b5893f02SDimitry Andric // Name can't start with a digit.
173*b5893f02SDimitry Andric if (isdigit(static_cast<unsigned char>(Name[0]))) {
174*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
175*b5893f02SDimitry Andric "invalid name in named regex");
176*b5893f02SDimitry Andric return true;
177*b5893f02SDimitry Andric }
178*b5893f02SDimitry Andric
179*b5893f02SDimitry Andric // Handle [[foo]].
180*b5893f02SDimitry Andric if (NameEnd == StringRef::npos) {
181*b5893f02SDimitry Andric // Handle variables that were defined earlier on the same line by
182*b5893f02SDimitry Andric // emitting a backreference.
183*b5893f02SDimitry Andric if (VariableDefs.find(Name) != VariableDefs.end()) {
184*b5893f02SDimitry Andric unsigned VarParenNum = VariableDefs[Name];
185*b5893f02SDimitry Andric if (VarParenNum < 1 || VarParenNum > 9) {
186*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
187*b5893f02SDimitry Andric SourceMgr::DK_Error,
188*b5893f02SDimitry Andric "Can't back-reference more than 9 variables");
189*b5893f02SDimitry Andric return true;
190*b5893f02SDimitry Andric }
191*b5893f02SDimitry Andric AddBackrefToRegEx(VarParenNum);
192*b5893f02SDimitry Andric } else {
193*b5893f02SDimitry Andric VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
194*b5893f02SDimitry Andric }
195*b5893f02SDimitry Andric continue;
196*b5893f02SDimitry Andric }
197*b5893f02SDimitry Andric
198*b5893f02SDimitry Andric // Handle [[foo:.*]].
199*b5893f02SDimitry Andric VariableDefs[Name] = CurParen;
200*b5893f02SDimitry Andric RegExStr += '(';
201*b5893f02SDimitry Andric ++CurParen;
202*b5893f02SDimitry Andric
203*b5893f02SDimitry Andric if (AddRegExToRegEx(MatchStr.substr(NameEnd + 1), CurParen, SM))
204*b5893f02SDimitry Andric return true;
205*b5893f02SDimitry Andric
206*b5893f02SDimitry Andric RegExStr += ')';
207*b5893f02SDimitry Andric }
208*b5893f02SDimitry Andric
209*b5893f02SDimitry Andric // Handle fixed string matches.
210*b5893f02SDimitry Andric // Find the end, which is the start of the next regex.
211*b5893f02SDimitry Andric size_t FixedMatchEnd = PatternStr.find("{{");
212*b5893f02SDimitry Andric FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
213*b5893f02SDimitry Andric RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
214*b5893f02SDimitry Andric PatternStr = PatternStr.substr(FixedMatchEnd);
215*b5893f02SDimitry Andric }
216*b5893f02SDimitry Andric
217*b5893f02SDimitry Andric if (MatchFullLinesHere) {
218*b5893f02SDimitry Andric if (!Req.NoCanonicalizeWhiteSpace)
219*b5893f02SDimitry Andric RegExStr += " *";
220*b5893f02SDimitry Andric RegExStr += '$';
221*b5893f02SDimitry Andric }
222*b5893f02SDimitry Andric
223*b5893f02SDimitry Andric return false;
224*b5893f02SDimitry Andric }
225*b5893f02SDimitry Andric
AddRegExToRegEx(StringRef RS,unsigned & CurParen,SourceMgr & SM)226*b5893f02SDimitry Andric bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
227*b5893f02SDimitry Andric Regex R(RS);
228*b5893f02SDimitry Andric std::string Error;
229*b5893f02SDimitry Andric if (!R.isValid(Error)) {
230*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
231*b5893f02SDimitry Andric "invalid regex: " + Error);
232*b5893f02SDimitry Andric return true;
233*b5893f02SDimitry Andric }
234*b5893f02SDimitry Andric
235*b5893f02SDimitry Andric RegExStr += RS.str();
236*b5893f02SDimitry Andric CurParen += R.getNumMatches();
237*b5893f02SDimitry Andric return false;
238*b5893f02SDimitry Andric }
239*b5893f02SDimitry Andric
AddBackrefToRegEx(unsigned BackrefNum)240*b5893f02SDimitry Andric void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
241*b5893f02SDimitry Andric assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
242*b5893f02SDimitry Andric std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
243*b5893f02SDimitry Andric RegExStr += Backref;
244*b5893f02SDimitry Andric }
245*b5893f02SDimitry Andric
246*b5893f02SDimitry Andric /// Evaluates expression and stores the result to \p Value.
247*b5893f02SDimitry Andric ///
248*b5893f02SDimitry Andric /// Returns true on success and false when the expression has invalid syntax.
EvaluateExpression(StringRef Expr,std::string & Value) const249*b5893f02SDimitry Andric bool FileCheckPattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
250*b5893f02SDimitry Andric // The only supported expression is @LINE([\+-]\d+)?
251*b5893f02SDimitry Andric if (!Expr.startswith("@LINE"))
252*b5893f02SDimitry Andric return false;
253*b5893f02SDimitry Andric Expr = Expr.substr(StringRef("@LINE").size());
254*b5893f02SDimitry Andric int Offset = 0;
255*b5893f02SDimitry Andric if (!Expr.empty()) {
256*b5893f02SDimitry Andric if (Expr[0] == '+')
257*b5893f02SDimitry Andric Expr = Expr.substr(1);
258*b5893f02SDimitry Andric else if (Expr[0] != '-')
259*b5893f02SDimitry Andric return false;
260*b5893f02SDimitry Andric if (Expr.getAsInteger(10, Offset))
261*b5893f02SDimitry Andric return false;
262*b5893f02SDimitry Andric }
263*b5893f02SDimitry Andric Value = llvm::itostr(LineNumber + Offset);
264*b5893f02SDimitry Andric return true;
265*b5893f02SDimitry Andric }
266*b5893f02SDimitry Andric
267*b5893f02SDimitry Andric /// Matches the pattern string against the input buffer \p Buffer
268*b5893f02SDimitry Andric ///
269*b5893f02SDimitry Andric /// This returns the position that is matched or npos if there is no match. If
270*b5893f02SDimitry Andric /// there is a match, the size of the matched string is returned in \p
271*b5893f02SDimitry Andric /// MatchLen.
272*b5893f02SDimitry Andric ///
273*b5893f02SDimitry Andric /// The \p VariableTable StringMap provides the current values of filecheck
274*b5893f02SDimitry Andric /// variables and is updated if this match defines new values.
Match(StringRef Buffer,size_t & MatchLen,StringMap<StringRef> & VariableTable) const275*b5893f02SDimitry Andric size_t FileCheckPattern::Match(StringRef Buffer, size_t &MatchLen,
276*b5893f02SDimitry Andric StringMap<StringRef> &VariableTable) const {
277*b5893f02SDimitry Andric // If this is the EOF pattern, match it immediately.
278*b5893f02SDimitry Andric if (CheckTy == Check::CheckEOF) {
279*b5893f02SDimitry Andric MatchLen = 0;
280*b5893f02SDimitry Andric return Buffer.size();
281*b5893f02SDimitry Andric }
282*b5893f02SDimitry Andric
283*b5893f02SDimitry Andric // If this is a fixed string pattern, just match it now.
284*b5893f02SDimitry Andric if (!FixedStr.empty()) {
285*b5893f02SDimitry Andric MatchLen = FixedStr.size();
286*b5893f02SDimitry Andric return Buffer.find(FixedStr);
287*b5893f02SDimitry Andric }
288*b5893f02SDimitry Andric
289*b5893f02SDimitry Andric // Regex match.
290*b5893f02SDimitry Andric
291*b5893f02SDimitry Andric // If there are variable uses, we need to create a temporary string with the
292*b5893f02SDimitry Andric // actual value.
293*b5893f02SDimitry Andric StringRef RegExToMatch = RegExStr;
294*b5893f02SDimitry Andric std::string TmpStr;
295*b5893f02SDimitry Andric if (!VariableUses.empty()) {
296*b5893f02SDimitry Andric TmpStr = RegExStr;
297*b5893f02SDimitry Andric
298*b5893f02SDimitry Andric unsigned InsertOffset = 0;
299*b5893f02SDimitry Andric for (const auto &VariableUse : VariableUses) {
300*b5893f02SDimitry Andric std::string Value;
301*b5893f02SDimitry Andric
302*b5893f02SDimitry Andric if (VariableUse.first[0] == '@') {
303*b5893f02SDimitry Andric if (!EvaluateExpression(VariableUse.first, Value))
304*b5893f02SDimitry Andric return StringRef::npos;
305*b5893f02SDimitry Andric } else {
306*b5893f02SDimitry Andric StringMap<StringRef>::iterator it =
307*b5893f02SDimitry Andric VariableTable.find(VariableUse.first);
308*b5893f02SDimitry Andric // If the variable is undefined, return an error.
309*b5893f02SDimitry Andric if (it == VariableTable.end())
310*b5893f02SDimitry Andric return StringRef::npos;
311*b5893f02SDimitry Andric
312*b5893f02SDimitry Andric // Look up the value and escape it so that we can put it into the regex.
313*b5893f02SDimitry Andric Value += Regex::escape(it->second);
314*b5893f02SDimitry Andric }
315*b5893f02SDimitry Andric
316*b5893f02SDimitry Andric // Plop it into the regex at the adjusted offset.
317*b5893f02SDimitry Andric TmpStr.insert(TmpStr.begin() + VariableUse.second + InsertOffset,
318*b5893f02SDimitry Andric Value.begin(), Value.end());
319*b5893f02SDimitry Andric InsertOffset += Value.size();
320*b5893f02SDimitry Andric }
321*b5893f02SDimitry Andric
322*b5893f02SDimitry Andric // Match the newly constructed regex.
323*b5893f02SDimitry Andric RegExToMatch = TmpStr;
324*b5893f02SDimitry Andric }
325*b5893f02SDimitry Andric
326*b5893f02SDimitry Andric SmallVector<StringRef, 4> MatchInfo;
327*b5893f02SDimitry Andric if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
328*b5893f02SDimitry Andric return StringRef::npos;
329*b5893f02SDimitry Andric
330*b5893f02SDimitry Andric // Successful regex match.
331*b5893f02SDimitry Andric assert(!MatchInfo.empty() && "Didn't get any match");
332*b5893f02SDimitry Andric StringRef FullMatch = MatchInfo[0];
333*b5893f02SDimitry Andric
334*b5893f02SDimitry Andric // If this defines any variables, remember their values.
335*b5893f02SDimitry Andric for (const auto &VariableDef : VariableDefs) {
336*b5893f02SDimitry Andric assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
337*b5893f02SDimitry Andric VariableTable[VariableDef.first] = MatchInfo[VariableDef.second];
338*b5893f02SDimitry Andric }
339*b5893f02SDimitry Andric
340*b5893f02SDimitry Andric // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
341*b5893f02SDimitry Andric // the required preceding newline, which is consumed by the pattern in the
342*b5893f02SDimitry Andric // case of CHECK-EMPTY but not CHECK-NEXT.
343*b5893f02SDimitry Andric size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
344*b5893f02SDimitry Andric MatchLen = FullMatch.size() - MatchStartSkip;
345*b5893f02SDimitry Andric return FullMatch.data() - Buffer.data() + MatchStartSkip;
346*b5893f02SDimitry Andric }
347*b5893f02SDimitry Andric
348*b5893f02SDimitry Andric
349*b5893f02SDimitry Andric /// Computes an arbitrary estimate for the quality of matching this pattern at
350*b5893f02SDimitry Andric /// the start of \p Buffer; a distance of zero should correspond to a perfect
351*b5893f02SDimitry Andric /// match.
352*b5893f02SDimitry Andric unsigned
ComputeMatchDistance(StringRef Buffer,const StringMap<StringRef> & VariableTable) const353*b5893f02SDimitry Andric FileCheckPattern::ComputeMatchDistance(StringRef Buffer,
354*b5893f02SDimitry Andric const StringMap<StringRef> &VariableTable) const {
355*b5893f02SDimitry Andric // Just compute the number of matching characters. For regular expressions, we
356*b5893f02SDimitry Andric // just compare against the regex itself and hope for the best.
357*b5893f02SDimitry Andric //
358*b5893f02SDimitry Andric // FIXME: One easy improvement here is have the regex lib generate a single
359*b5893f02SDimitry Andric // example regular expression which matches, and use that as the example
360*b5893f02SDimitry Andric // string.
361*b5893f02SDimitry Andric StringRef ExampleString(FixedStr);
362*b5893f02SDimitry Andric if (ExampleString.empty())
363*b5893f02SDimitry Andric ExampleString = RegExStr;
364*b5893f02SDimitry Andric
365*b5893f02SDimitry Andric // Only compare up to the first line in the buffer, or the string size.
366*b5893f02SDimitry Andric StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
367*b5893f02SDimitry Andric BufferPrefix = BufferPrefix.split('\n').first;
368*b5893f02SDimitry Andric return BufferPrefix.edit_distance(ExampleString);
369*b5893f02SDimitry Andric }
370*b5893f02SDimitry Andric
PrintVariableUses(const SourceMgr & SM,StringRef Buffer,const StringMap<StringRef> & VariableTable,SMRange MatchRange) const371*b5893f02SDimitry Andric void FileCheckPattern::PrintVariableUses(const SourceMgr &SM, StringRef Buffer,
372*b5893f02SDimitry Andric const StringMap<StringRef> &VariableTable,
373*b5893f02SDimitry Andric SMRange MatchRange) const {
374*b5893f02SDimitry Andric // If this was a regular expression using variables, print the current
375*b5893f02SDimitry Andric // variable values.
376*b5893f02SDimitry Andric if (!VariableUses.empty()) {
377*b5893f02SDimitry Andric for (const auto &VariableUse : VariableUses) {
378*b5893f02SDimitry Andric SmallString<256> Msg;
379*b5893f02SDimitry Andric raw_svector_ostream OS(Msg);
380*b5893f02SDimitry Andric StringRef Var = VariableUse.first;
381*b5893f02SDimitry Andric if (Var[0] == '@') {
382*b5893f02SDimitry Andric std::string Value;
383*b5893f02SDimitry Andric if (EvaluateExpression(Var, Value)) {
384*b5893f02SDimitry Andric OS << "with expression \"";
385*b5893f02SDimitry Andric OS.write_escaped(Var) << "\" equal to \"";
386*b5893f02SDimitry Andric OS.write_escaped(Value) << "\"";
387*b5893f02SDimitry Andric } else {
388*b5893f02SDimitry Andric OS << "uses incorrect expression \"";
389*b5893f02SDimitry Andric OS.write_escaped(Var) << "\"";
390*b5893f02SDimitry Andric }
391*b5893f02SDimitry Andric } else {
392*b5893f02SDimitry Andric StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
393*b5893f02SDimitry Andric
394*b5893f02SDimitry Andric // Check for undefined variable references.
395*b5893f02SDimitry Andric if (it == VariableTable.end()) {
396*b5893f02SDimitry Andric OS << "uses undefined variable \"";
397*b5893f02SDimitry Andric OS.write_escaped(Var) << "\"";
398*b5893f02SDimitry Andric } else {
399*b5893f02SDimitry Andric OS << "with variable \"";
400*b5893f02SDimitry Andric OS.write_escaped(Var) << "\" equal to \"";
401*b5893f02SDimitry Andric OS.write_escaped(it->second) << "\"";
402*b5893f02SDimitry Andric }
403*b5893f02SDimitry Andric }
404*b5893f02SDimitry Andric
405*b5893f02SDimitry Andric if (MatchRange.isValid())
406*b5893f02SDimitry Andric SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
407*b5893f02SDimitry Andric {MatchRange});
408*b5893f02SDimitry Andric else
409*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
410*b5893f02SDimitry Andric SourceMgr::DK_Note, OS.str());
411*b5893f02SDimitry Andric }
412*b5893f02SDimitry Andric }
413*b5893f02SDimitry Andric }
414*b5893f02SDimitry Andric
ProcessMatchResult(FileCheckDiag::MatchType MatchTy,const SourceMgr & SM,SMLoc Loc,Check::FileCheckType CheckTy,StringRef Buffer,size_t Pos,size_t Len,std::vector<FileCheckDiag> * Diags,bool AdjustPrevDiag=false)415*b5893f02SDimitry Andric static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
416*b5893f02SDimitry Andric const SourceMgr &SM, SMLoc Loc,
417*b5893f02SDimitry Andric Check::FileCheckType CheckTy,
418*b5893f02SDimitry Andric StringRef Buffer, size_t Pos, size_t Len,
419*b5893f02SDimitry Andric std::vector<FileCheckDiag> *Diags,
420*b5893f02SDimitry Andric bool AdjustPrevDiag = false) {
421*b5893f02SDimitry Andric SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
422*b5893f02SDimitry Andric SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
423*b5893f02SDimitry Andric SMRange Range(Start, End);
424*b5893f02SDimitry Andric if (Diags) {
425*b5893f02SDimitry Andric if (AdjustPrevDiag)
426*b5893f02SDimitry Andric Diags->rbegin()->MatchTy = MatchTy;
427*b5893f02SDimitry Andric else
428*b5893f02SDimitry Andric Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
429*b5893f02SDimitry Andric }
430*b5893f02SDimitry Andric return Range;
431*b5893f02SDimitry Andric }
432*b5893f02SDimitry Andric
PrintFuzzyMatch(const SourceMgr & SM,StringRef Buffer,const StringMap<StringRef> & VariableTable,std::vector<FileCheckDiag> * Diags) const433*b5893f02SDimitry Andric void FileCheckPattern::PrintFuzzyMatch(
434*b5893f02SDimitry Andric const SourceMgr &SM, StringRef Buffer,
435*b5893f02SDimitry Andric const StringMap<StringRef> &VariableTable,
436*b5893f02SDimitry Andric std::vector<FileCheckDiag> *Diags) const {
437*b5893f02SDimitry Andric // Attempt to find the closest/best fuzzy match. Usually an error happens
438*b5893f02SDimitry Andric // because some string in the output didn't exactly match. In these cases, we
439*b5893f02SDimitry Andric // would like to show the user a best guess at what "should have" matched, to
440*b5893f02SDimitry Andric // save them having to actually check the input manually.
441*b5893f02SDimitry Andric size_t NumLinesForward = 0;
442*b5893f02SDimitry Andric size_t Best = StringRef::npos;
443*b5893f02SDimitry Andric double BestQuality = 0;
444*b5893f02SDimitry Andric
445*b5893f02SDimitry Andric // Use an arbitrary 4k limit on how far we will search.
446*b5893f02SDimitry Andric for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
447*b5893f02SDimitry Andric if (Buffer[i] == '\n')
448*b5893f02SDimitry Andric ++NumLinesForward;
449*b5893f02SDimitry Andric
450*b5893f02SDimitry Andric // Patterns have leading whitespace stripped, so skip whitespace when
451*b5893f02SDimitry Andric // looking for something which looks like a pattern.
452*b5893f02SDimitry Andric if (Buffer[i] == ' ' || Buffer[i] == '\t')
453*b5893f02SDimitry Andric continue;
454*b5893f02SDimitry Andric
455*b5893f02SDimitry Andric // Compute the "quality" of this match as an arbitrary combination of the
456*b5893f02SDimitry Andric // match distance and the number of lines skipped to get to this match.
457*b5893f02SDimitry Andric unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
458*b5893f02SDimitry Andric double Quality = Distance + (NumLinesForward / 100.);
459*b5893f02SDimitry Andric
460*b5893f02SDimitry Andric if (Quality < BestQuality || Best == StringRef::npos) {
461*b5893f02SDimitry Andric Best = i;
462*b5893f02SDimitry Andric BestQuality = Quality;
463*b5893f02SDimitry Andric }
464*b5893f02SDimitry Andric }
465*b5893f02SDimitry Andric
466*b5893f02SDimitry Andric // Print the "possible intended match here" line if we found something
467*b5893f02SDimitry Andric // reasonable and not equal to what we showed in the "scanning from here"
468*b5893f02SDimitry Andric // line.
469*b5893f02SDimitry Andric if (Best && Best != StringRef::npos && BestQuality < 50) {
470*b5893f02SDimitry Andric SMRange MatchRange =
471*b5893f02SDimitry Andric ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
472*b5893f02SDimitry Andric getCheckTy(), Buffer, Best, 0, Diags);
473*b5893f02SDimitry Andric SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
474*b5893f02SDimitry Andric "possible intended match here");
475*b5893f02SDimitry Andric
476*b5893f02SDimitry Andric // FIXME: If we wanted to be really friendly we would show why the match
477*b5893f02SDimitry Andric // failed, as it can be hard to spot simple one character differences.
478*b5893f02SDimitry Andric }
479*b5893f02SDimitry Andric }
480*b5893f02SDimitry Andric
481*b5893f02SDimitry Andric /// Finds the closing sequence of a regex variable usage or definition.
482*b5893f02SDimitry Andric ///
483*b5893f02SDimitry Andric /// \p Str has to point in the beginning of the definition (right after the
484*b5893f02SDimitry Andric /// opening sequence). Returns the offset of the closing sequence within Str,
485*b5893f02SDimitry Andric /// or npos if it was not found.
FindRegexVarEnd(StringRef Str,SourceMgr & SM)486*b5893f02SDimitry Andric size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
487*b5893f02SDimitry Andric // Offset keeps track of the current offset within the input Str
488*b5893f02SDimitry Andric size_t Offset = 0;
489*b5893f02SDimitry Andric // [...] Nesting depth
490*b5893f02SDimitry Andric size_t BracketDepth = 0;
491*b5893f02SDimitry Andric
492*b5893f02SDimitry Andric while (!Str.empty()) {
493*b5893f02SDimitry Andric if (Str.startswith("]]") && BracketDepth == 0)
494*b5893f02SDimitry Andric return Offset;
495*b5893f02SDimitry Andric if (Str[0] == '\\') {
496*b5893f02SDimitry Andric // Backslash escapes the next char within regexes, so skip them both.
497*b5893f02SDimitry Andric Str = Str.substr(2);
498*b5893f02SDimitry Andric Offset += 2;
499*b5893f02SDimitry Andric } else {
500*b5893f02SDimitry Andric switch (Str[0]) {
501*b5893f02SDimitry Andric default:
502*b5893f02SDimitry Andric break;
503*b5893f02SDimitry Andric case '[':
504*b5893f02SDimitry Andric BracketDepth++;
505*b5893f02SDimitry Andric break;
506*b5893f02SDimitry Andric case ']':
507*b5893f02SDimitry Andric if (BracketDepth == 0) {
508*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
509*b5893f02SDimitry Andric SourceMgr::DK_Error,
510*b5893f02SDimitry Andric "missing closing \"]\" for regex variable");
511*b5893f02SDimitry Andric exit(1);
512*b5893f02SDimitry Andric }
513*b5893f02SDimitry Andric BracketDepth--;
514*b5893f02SDimitry Andric break;
515*b5893f02SDimitry Andric }
516*b5893f02SDimitry Andric Str = Str.substr(1);
517*b5893f02SDimitry Andric Offset++;
518*b5893f02SDimitry Andric }
519*b5893f02SDimitry Andric }
520*b5893f02SDimitry Andric
521*b5893f02SDimitry Andric return StringRef::npos;
522*b5893f02SDimitry Andric }
523*b5893f02SDimitry Andric
524*b5893f02SDimitry Andric /// Canonicalize whitespaces in the file. Line endings are replaced with
525*b5893f02SDimitry Andric /// UNIX-style '\n'.
526*b5893f02SDimitry Andric StringRef
CanonicalizeFile(MemoryBuffer & MB,SmallVectorImpl<char> & OutputBuffer)527*b5893f02SDimitry Andric llvm::FileCheck::CanonicalizeFile(MemoryBuffer &MB,
528*b5893f02SDimitry Andric SmallVectorImpl<char> &OutputBuffer) {
529*b5893f02SDimitry Andric OutputBuffer.reserve(MB.getBufferSize());
530*b5893f02SDimitry Andric
531*b5893f02SDimitry Andric for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
532*b5893f02SDimitry Andric Ptr != End; ++Ptr) {
533*b5893f02SDimitry Andric // Eliminate trailing dosish \r.
534*b5893f02SDimitry Andric if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
535*b5893f02SDimitry Andric continue;
536*b5893f02SDimitry Andric }
537*b5893f02SDimitry Andric
538*b5893f02SDimitry Andric // If current char is not a horizontal whitespace or if horizontal
539*b5893f02SDimitry Andric // whitespace canonicalization is disabled, dump it to output as is.
540*b5893f02SDimitry Andric if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
541*b5893f02SDimitry Andric OutputBuffer.push_back(*Ptr);
542*b5893f02SDimitry Andric continue;
543*b5893f02SDimitry Andric }
544*b5893f02SDimitry Andric
545*b5893f02SDimitry Andric // Otherwise, add one space and advance over neighboring space.
546*b5893f02SDimitry Andric OutputBuffer.push_back(' ');
547*b5893f02SDimitry Andric while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
548*b5893f02SDimitry Andric ++Ptr;
549*b5893f02SDimitry Andric }
550*b5893f02SDimitry Andric
551*b5893f02SDimitry Andric // Add a null byte and then return all but that byte.
552*b5893f02SDimitry Andric OutputBuffer.push_back('\0');
553*b5893f02SDimitry Andric return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
554*b5893f02SDimitry Andric }
555*b5893f02SDimitry Andric
FileCheckDiag(const SourceMgr & SM,const Check::FileCheckType & CheckTy,SMLoc CheckLoc,MatchType MatchTy,SMRange InputRange)556*b5893f02SDimitry Andric FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
557*b5893f02SDimitry Andric const Check::FileCheckType &CheckTy,
558*b5893f02SDimitry Andric SMLoc CheckLoc, MatchType MatchTy,
559*b5893f02SDimitry Andric SMRange InputRange)
560*b5893f02SDimitry Andric : CheckTy(CheckTy), MatchTy(MatchTy) {
561*b5893f02SDimitry Andric auto Start = SM.getLineAndColumn(InputRange.Start);
562*b5893f02SDimitry Andric auto End = SM.getLineAndColumn(InputRange.End);
563*b5893f02SDimitry Andric InputStartLine = Start.first;
564*b5893f02SDimitry Andric InputStartCol = Start.second;
565*b5893f02SDimitry Andric InputEndLine = End.first;
566*b5893f02SDimitry Andric InputEndCol = End.second;
567*b5893f02SDimitry Andric Start = SM.getLineAndColumn(CheckLoc);
568*b5893f02SDimitry Andric CheckLine = Start.first;
569*b5893f02SDimitry Andric CheckCol = Start.second;
570*b5893f02SDimitry Andric }
571*b5893f02SDimitry Andric
IsPartOfWord(char c)572*b5893f02SDimitry Andric static bool IsPartOfWord(char c) {
573*b5893f02SDimitry Andric return (isalnum(c) || c == '-' || c == '_');
574*b5893f02SDimitry Andric }
575*b5893f02SDimitry Andric
setCount(int C)576*b5893f02SDimitry Andric Check::FileCheckType &Check::FileCheckType::setCount(int C) {
577*b5893f02SDimitry Andric assert(Count > 0 && "zero and negative counts are not supported");
578*b5893f02SDimitry Andric assert((C == 1 || Kind == CheckPlain) &&
579*b5893f02SDimitry Andric "count supported only for plain CHECK directives");
580*b5893f02SDimitry Andric Count = C;
581*b5893f02SDimitry Andric return *this;
582*b5893f02SDimitry Andric }
583*b5893f02SDimitry Andric
584*b5893f02SDimitry Andric // Get a description of the type.
getDescription(StringRef Prefix) const585*b5893f02SDimitry Andric std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
586*b5893f02SDimitry Andric switch (Kind) {
587*b5893f02SDimitry Andric case Check::CheckNone:
588*b5893f02SDimitry Andric return "invalid";
589*b5893f02SDimitry Andric case Check::CheckPlain:
590*b5893f02SDimitry Andric if (Count > 1)
591*b5893f02SDimitry Andric return Prefix.str() + "-COUNT";
592*b5893f02SDimitry Andric return Prefix;
593*b5893f02SDimitry Andric case Check::CheckNext:
594*b5893f02SDimitry Andric return Prefix.str() + "-NEXT";
595*b5893f02SDimitry Andric case Check::CheckSame:
596*b5893f02SDimitry Andric return Prefix.str() + "-SAME";
597*b5893f02SDimitry Andric case Check::CheckNot:
598*b5893f02SDimitry Andric return Prefix.str() + "-NOT";
599*b5893f02SDimitry Andric case Check::CheckDAG:
600*b5893f02SDimitry Andric return Prefix.str() + "-DAG";
601*b5893f02SDimitry Andric case Check::CheckLabel:
602*b5893f02SDimitry Andric return Prefix.str() + "-LABEL";
603*b5893f02SDimitry Andric case Check::CheckEmpty:
604*b5893f02SDimitry Andric return Prefix.str() + "-EMPTY";
605*b5893f02SDimitry Andric case Check::CheckEOF:
606*b5893f02SDimitry Andric return "implicit EOF";
607*b5893f02SDimitry Andric case Check::CheckBadNot:
608*b5893f02SDimitry Andric return "bad NOT";
609*b5893f02SDimitry Andric case Check::CheckBadCount:
610*b5893f02SDimitry Andric return "bad COUNT";
611*b5893f02SDimitry Andric }
612*b5893f02SDimitry Andric llvm_unreachable("unknown FileCheckType");
613*b5893f02SDimitry Andric }
614*b5893f02SDimitry Andric
615*b5893f02SDimitry Andric static std::pair<Check::FileCheckType, StringRef>
FindCheckType(StringRef Buffer,StringRef Prefix)616*b5893f02SDimitry Andric FindCheckType(StringRef Buffer, StringRef Prefix) {
617*b5893f02SDimitry Andric if (Buffer.size() <= Prefix.size())
618*b5893f02SDimitry Andric return {Check::CheckNone, StringRef()};
619*b5893f02SDimitry Andric
620*b5893f02SDimitry Andric char NextChar = Buffer[Prefix.size()];
621*b5893f02SDimitry Andric
622*b5893f02SDimitry Andric StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
623*b5893f02SDimitry Andric // Verify that the : is present after the prefix.
624*b5893f02SDimitry Andric if (NextChar == ':')
625*b5893f02SDimitry Andric return {Check::CheckPlain, Rest};
626*b5893f02SDimitry Andric
627*b5893f02SDimitry Andric if (NextChar != '-')
628*b5893f02SDimitry Andric return {Check::CheckNone, StringRef()};
629*b5893f02SDimitry Andric
630*b5893f02SDimitry Andric if (Rest.consume_front("COUNT-")) {
631*b5893f02SDimitry Andric int64_t Count;
632*b5893f02SDimitry Andric if (Rest.consumeInteger(10, Count))
633*b5893f02SDimitry Andric // Error happened in parsing integer.
634*b5893f02SDimitry Andric return {Check::CheckBadCount, Rest};
635*b5893f02SDimitry Andric if (Count <= 0 || Count > INT32_MAX)
636*b5893f02SDimitry Andric return {Check::CheckBadCount, Rest};
637*b5893f02SDimitry Andric if (!Rest.consume_front(":"))
638*b5893f02SDimitry Andric return {Check::CheckBadCount, Rest};
639*b5893f02SDimitry Andric return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
640*b5893f02SDimitry Andric }
641*b5893f02SDimitry Andric
642*b5893f02SDimitry Andric if (Rest.consume_front("NEXT:"))
643*b5893f02SDimitry Andric return {Check::CheckNext, Rest};
644*b5893f02SDimitry Andric
645*b5893f02SDimitry Andric if (Rest.consume_front("SAME:"))
646*b5893f02SDimitry Andric return {Check::CheckSame, Rest};
647*b5893f02SDimitry Andric
648*b5893f02SDimitry Andric if (Rest.consume_front("NOT:"))
649*b5893f02SDimitry Andric return {Check::CheckNot, Rest};
650*b5893f02SDimitry Andric
651*b5893f02SDimitry Andric if (Rest.consume_front("DAG:"))
652*b5893f02SDimitry Andric return {Check::CheckDAG, Rest};
653*b5893f02SDimitry Andric
654*b5893f02SDimitry Andric if (Rest.consume_front("LABEL:"))
655*b5893f02SDimitry Andric return {Check::CheckLabel, Rest};
656*b5893f02SDimitry Andric
657*b5893f02SDimitry Andric if (Rest.consume_front("EMPTY:"))
658*b5893f02SDimitry Andric return {Check::CheckEmpty, Rest};
659*b5893f02SDimitry Andric
660*b5893f02SDimitry Andric // You can't combine -NOT with another suffix.
661*b5893f02SDimitry Andric if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
662*b5893f02SDimitry Andric Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
663*b5893f02SDimitry Andric Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
664*b5893f02SDimitry Andric Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
665*b5893f02SDimitry Andric return {Check::CheckBadNot, Rest};
666*b5893f02SDimitry Andric
667*b5893f02SDimitry Andric return {Check::CheckNone, Rest};
668*b5893f02SDimitry Andric }
669*b5893f02SDimitry Andric
670*b5893f02SDimitry Andric // From the given position, find the next character after the word.
SkipWord(StringRef Str,size_t Loc)671*b5893f02SDimitry Andric static size_t SkipWord(StringRef Str, size_t Loc) {
672*b5893f02SDimitry Andric while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
673*b5893f02SDimitry Andric ++Loc;
674*b5893f02SDimitry Andric return Loc;
675*b5893f02SDimitry Andric }
676*b5893f02SDimitry Andric
677*b5893f02SDimitry Andric /// Search the buffer for the first prefix in the prefix regular expression.
678*b5893f02SDimitry Andric ///
679*b5893f02SDimitry Andric /// This searches the buffer using the provided regular expression, however it
680*b5893f02SDimitry Andric /// enforces constraints beyond that:
681*b5893f02SDimitry Andric /// 1) The found prefix must not be a suffix of something that looks like
682*b5893f02SDimitry Andric /// a valid prefix.
683*b5893f02SDimitry Andric /// 2) The found prefix must be followed by a valid check type suffix using \c
684*b5893f02SDimitry Andric /// FindCheckType above.
685*b5893f02SDimitry Andric ///
686*b5893f02SDimitry Andric /// Returns a pair of StringRefs into the Buffer, which combines:
687*b5893f02SDimitry Andric /// - the first match of the regular expression to satisfy these two is
688*b5893f02SDimitry Andric /// returned,
689*b5893f02SDimitry Andric /// otherwise an empty StringRef is returned to indicate failure.
690*b5893f02SDimitry Andric /// - buffer rewound to the location right after parsed suffix, for parsing
691*b5893f02SDimitry Andric /// to continue from
692*b5893f02SDimitry Andric ///
693*b5893f02SDimitry Andric /// If this routine returns a valid prefix, it will also shrink \p Buffer to
694*b5893f02SDimitry Andric /// start at the beginning of the returned prefix, increment \p LineNumber for
695*b5893f02SDimitry Andric /// each new line consumed from \p Buffer, and set \p CheckTy to the type of
696*b5893f02SDimitry Andric /// check found by examining the suffix.
697*b5893f02SDimitry Andric ///
698*b5893f02SDimitry Andric /// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
699*b5893f02SDimitry Andric /// is unspecified.
700*b5893f02SDimitry Andric static std::pair<StringRef, StringRef>
FindFirstMatchingPrefix(Regex & PrefixRE,StringRef & Buffer,unsigned & LineNumber,Check::FileCheckType & CheckTy)701*b5893f02SDimitry Andric FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer,
702*b5893f02SDimitry Andric unsigned &LineNumber, Check::FileCheckType &CheckTy) {
703*b5893f02SDimitry Andric SmallVector<StringRef, 2> Matches;
704*b5893f02SDimitry Andric
705*b5893f02SDimitry Andric while (!Buffer.empty()) {
706*b5893f02SDimitry Andric // Find the first (longest) match using the RE.
707*b5893f02SDimitry Andric if (!PrefixRE.match(Buffer, &Matches))
708*b5893f02SDimitry Andric // No match at all, bail.
709*b5893f02SDimitry Andric return {StringRef(), StringRef()};
710*b5893f02SDimitry Andric
711*b5893f02SDimitry Andric StringRef Prefix = Matches[0];
712*b5893f02SDimitry Andric Matches.clear();
713*b5893f02SDimitry Andric
714*b5893f02SDimitry Andric assert(Prefix.data() >= Buffer.data() &&
715*b5893f02SDimitry Andric Prefix.data() < Buffer.data() + Buffer.size() &&
716*b5893f02SDimitry Andric "Prefix doesn't start inside of buffer!");
717*b5893f02SDimitry Andric size_t Loc = Prefix.data() - Buffer.data();
718*b5893f02SDimitry Andric StringRef Skipped = Buffer.substr(0, Loc);
719*b5893f02SDimitry Andric Buffer = Buffer.drop_front(Loc);
720*b5893f02SDimitry Andric LineNumber += Skipped.count('\n');
721*b5893f02SDimitry Andric
722*b5893f02SDimitry Andric // Check that the matched prefix isn't a suffix of some other check-like
723*b5893f02SDimitry Andric // word.
724*b5893f02SDimitry Andric // FIXME: This is a very ad-hoc check. it would be better handled in some
725*b5893f02SDimitry Andric // other way. Among other things it seems hard to distinguish between
726*b5893f02SDimitry Andric // intentional and unintentional uses of this feature.
727*b5893f02SDimitry Andric if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
728*b5893f02SDimitry Andric // Now extract the type.
729*b5893f02SDimitry Andric StringRef AfterSuffix;
730*b5893f02SDimitry Andric std::tie(CheckTy, AfterSuffix) = FindCheckType(Buffer, Prefix);
731*b5893f02SDimitry Andric
732*b5893f02SDimitry Andric // If we've found a valid check type for this prefix, we're done.
733*b5893f02SDimitry Andric if (CheckTy != Check::CheckNone)
734*b5893f02SDimitry Andric return {Prefix, AfterSuffix};
735*b5893f02SDimitry Andric }
736*b5893f02SDimitry Andric
737*b5893f02SDimitry Andric // If we didn't successfully find a prefix, we need to skip this invalid
738*b5893f02SDimitry Andric // prefix and continue scanning. We directly skip the prefix that was
739*b5893f02SDimitry Andric // matched and any additional parts of that check-like word.
740*b5893f02SDimitry Andric Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
741*b5893f02SDimitry Andric }
742*b5893f02SDimitry Andric
743*b5893f02SDimitry Andric // We ran out of buffer while skipping partial matches so give up.
744*b5893f02SDimitry Andric return {StringRef(), StringRef()};
745*b5893f02SDimitry Andric }
746*b5893f02SDimitry Andric
747*b5893f02SDimitry Andric /// Read the check file, which specifies the sequence of expected strings.
748*b5893f02SDimitry Andric ///
749*b5893f02SDimitry Andric /// The strings are added to the CheckStrings vector. Returns true in case of
750*b5893f02SDimitry Andric /// an error, false otherwise.
ReadCheckFile(SourceMgr & SM,StringRef Buffer,Regex & PrefixRE,std::vector<FileCheckString> & CheckStrings)751*b5893f02SDimitry Andric bool llvm::FileCheck::ReadCheckFile(SourceMgr &SM, StringRef Buffer,
752*b5893f02SDimitry Andric Regex &PrefixRE,
753*b5893f02SDimitry Andric std::vector<FileCheckString> &CheckStrings) {
754*b5893f02SDimitry Andric std::vector<FileCheckPattern> ImplicitNegativeChecks;
755*b5893f02SDimitry Andric for (const auto &PatternString : Req.ImplicitCheckNot) {
756*b5893f02SDimitry Andric // Create a buffer with fake command line content in order to display the
757*b5893f02SDimitry Andric // command line option responsible for the specific implicit CHECK-NOT.
758*b5893f02SDimitry Andric std::string Prefix = "-implicit-check-not='";
759*b5893f02SDimitry Andric std::string Suffix = "'";
760*b5893f02SDimitry Andric std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
761*b5893f02SDimitry Andric Prefix + PatternString + Suffix, "command line");
762*b5893f02SDimitry Andric
763*b5893f02SDimitry Andric StringRef PatternInBuffer =
764*b5893f02SDimitry Andric CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
765*b5893f02SDimitry Andric SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
766*b5893f02SDimitry Andric
767*b5893f02SDimitry Andric ImplicitNegativeChecks.push_back(FileCheckPattern(Check::CheckNot));
768*b5893f02SDimitry Andric ImplicitNegativeChecks.back().ParsePattern(PatternInBuffer,
769*b5893f02SDimitry Andric "IMPLICIT-CHECK", SM, 0, Req);
770*b5893f02SDimitry Andric }
771*b5893f02SDimitry Andric
772*b5893f02SDimitry Andric std::vector<FileCheckPattern> DagNotMatches = ImplicitNegativeChecks;
773*b5893f02SDimitry Andric
774*b5893f02SDimitry Andric // LineNumber keeps track of the line on which CheckPrefix instances are
775*b5893f02SDimitry Andric // found.
776*b5893f02SDimitry Andric unsigned LineNumber = 1;
777*b5893f02SDimitry Andric
778*b5893f02SDimitry Andric while (1) {
779*b5893f02SDimitry Andric Check::FileCheckType CheckTy;
780*b5893f02SDimitry Andric
781*b5893f02SDimitry Andric // See if a prefix occurs in the memory buffer.
782*b5893f02SDimitry Andric StringRef UsedPrefix;
783*b5893f02SDimitry Andric StringRef AfterSuffix;
784*b5893f02SDimitry Andric std::tie(UsedPrefix, AfterSuffix) =
785*b5893f02SDimitry Andric FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, CheckTy);
786*b5893f02SDimitry Andric if (UsedPrefix.empty())
787*b5893f02SDimitry Andric break;
788*b5893f02SDimitry Andric assert(UsedPrefix.data() == Buffer.data() &&
789*b5893f02SDimitry Andric "Failed to move Buffer's start forward, or pointed prefix outside "
790*b5893f02SDimitry Andric "of the buffer!");
791*b5893f02SDimitry Andric assert(AfterSuffix.data() >= Buffer.data() &&
792*b5893f02SDimitry Andric AfterSuffix.data() < Buffer.data() + Buffer.size() &&
793*b5893f02SDimitry Andric "Parsing after suffix doesn't start inside of buffer!");
794*b5893f02SDimitry Andric
795*b5893f02SDimitry Andric // Location to use for error messages.
796*b5893f02SDimitry Andric const char *UsedPrefixStart = UsedPrefix.data();
797*b5893f02SDimitry Andric
798*b5893f02SDimitry Andric // Skip the buffer to the end of parsed suffix (or just prefix, if no good
799*b5893f02SDimitry Andric // suffix was processed).
800*b5893f02SDimitry Andric Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
801*b5893f02SDimitry Andric : AfterSuffix;
802*b5893f02SDimitry Andric
803*b5893f02SDimitry Andric // Complain about useful-looking but unsupported suffixes.
804*b5893f02SDimitry Andric if (CheckTy == Check::CheckBadNot) {
805*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
806*b5893f02SDimitry Andric "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
807*b5893f02SDimitry Andric return true;
808*b5893f02SDimitry Andric }
809*b5893f02SDimitry Andric
810*b5893f02SDimitry Andric // Complain about invalid count specification.
811*b5893f02SDimitry Andric if (CheckTy == Check::CheckBadCount) {
812*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
813*b5893f02SDimitry Andric "invalid count in -COUNT specification on prefix '" +
814*b5893f02SDimitry Andric UsedPrefix + "'");
815*b5893f02SDimitry Andric return true;
816*b5893f02SDimitry Andric }
817*b5893f02SDimitry Andric
818*b5893f02SDimitry Andric // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
819*b5893f02SDimitry Andric // leading whitespace.
820*b5893f02SDimitry Andric if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
821*b5893f02SDimitry Andric Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
822*b5893f02SDimitry Andric
823*b5893f02SDimitry Andric // Scan ahead to the end of line.
824*b5893f02SDimitry Andric size_t EOL = Buffer.find_first_of("\n\r");
825*b5893f02SDimitry Andric
826*b5893f02SDimitry Andric // Remember the location of the start of the pattern, for diagnostics.
827*b5893f02SDimitry Andric SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
828*b5893f02SDimitry Andric
829*b5893f02SDimitry Andric // Parse the pattern.
830*b5893f02SDimitry Andric FileCheckPattern P(CheckTy);
831*b5893f02SDimitry Andric if (P.ParsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, LineNumber, Req))
832*b5893f02SDimitry Andric return true;
833*b5893f02SDimitry Andric
834*b5893f02SDimitry Andric // Verify that CHECK-LABEL lines do not define or use variables
835*b5893f02SDimitry Andric if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
836*b5893f02SDimitry Andric SM.PrintMessage(
837*b5893f02SDimitry Andric SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
838*b5893f02SDimitry Andric "found '" + UsedPrefix + "-LABEL:'"
839*b5893f02SDimitry Andric " with variable definition or use");
840*b5893f02SDimitry Andric return true;
841*b5893f02SDimitry Andric }
842*b5893f02SDimitry Andric
843*b5893f02SDimitry Andric Buffer = Buffer.substr(EOL);
844*b5893f02SDimitry Andric
845*b5893f02SDimitry Andric // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
846*b5893f02SDimitry Andric if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
847*b5893f02SDimitry Andric CheckTy == Check::CheckEmpty) &&
848*b5893f02SDimitry Andric CheckStrings.empty()) {
849*b5893f02SDimitry Andric StringRef Type = CheckTy == Check::CheckNext
850*b5893f02SDimitry Andric ? "NEXT"
851*b5893f02SDimitry Andric : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
852*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
853*b5893f02SDimitry Andric SourceMgr::DK_Error,
854*b5893f02SDimitry Andric "found '" + UsedPrefix + "-" + Type +
855*b5893f02SDimitry Andric "' without previous '" + UsedPrefix + ": line");
856*b5893f02SDimitry Andric return true;
857*b5893f02SDimitry Andric }
858*b5893f02SDimitry Andric
859*b5893f02SDimitry Andric // Handle CHECK-DAG/-NOT.
860*b5893f02SDimitry Andric if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
861*b5893f02SDimitry Andric DagNotMatches.push_back(P);
862*b5893f02SDimitry Andric continue;
863*b5893f02SDimitry Andric }
864*b5893f02SDimitry Andric
865*b5893f02SDimitry Andric // Okay, add the string we captured to the output vector and move on.
866*b5893f02SDimitry Andric CheckStrings.emplace_back(P, UsedPrefix, PatternLoc);
867*b5893f02SDimitry Andric std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
868*b5893f02SDimitry Andric DagNotMatches = ImplicitNegativeChecks;
869*b5893f02SDimitry Andric }
870*b5893f02SDimitry Andric
871*b5893f02SDimitry Andric // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
872*b5893f02SDimitry Andric // prefix as a filler for the error message.
873*b5893f02SDimitry Andric if (!DagNotMatches.empty()) {
874*b5893f02SDimitry Andric CheckStrings.emplace_back(FileCheckPattern(Check::CheckEOF), *Req.CheckPrefixes.begin(),
875*b5893f02SDimitry Andric SMLoc::getFromPointer(Buffer.data()));
876*b5893f02SDimitry Andric std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
877*b5893f02SDimitry Andric }
878*b5893f02SDimitry Andric
879*b5893f02SDimitry Andric if (CheckStrings.empty()) {
880*b5893f02SDimitry Andric errs() << "error: no check strings found with prefix"
881*b5893f02SDimitry Andric << (Req.CheckPrefixes.size() > 1 ? "es " : " ");
882*b5893f02SDimitry Andric auto I = Req.CheckPrefixes.begin();
883*b5893f02SDimitry Andric auto E = Req.CheckPrefixes.end();
884*b5893f02SDimitry Andric if (I != E) {
885*b5893f02SDimitry Andric errs() << "\'" << *I << ":'";
886*b5893f02SDimitry Andric ++I;
887*b5893f02SDimitry Andric }
888*b5893f02SDimitry Andric for (; I != E; ++I)
889*b5893f02SDimitry Andric errs() << ", \'" << *I << ":'";
890*b5893f02SDimitry Andric
891*b5893f02SDimitry Andric errs() << '\n';
892*b5893f02SDimitry Andric return true;
893*b5893f02SDimitry Andric }
894*b5893f02SDimitry Andric
895*b5893f02SDimitry Andric return false;
896*b5893f02SDimitry Andric }
897*b5893f02SDimitry Andric
PrintMatch(bool ExpectedMatch,const SourceMgr & SM,StringRef Prefix,SMLoc Loc,const FileCheckPattern & Pat,int MatchedCount,StringRef Buffer,StringMap<StringRef> & VariableTable,size_t MatchPos,size_t MatchLen,const FileCheckRequest & Req,std::vector<FileCheckDiag> * Diags)898*b5893f02SDimitry Andric static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
899*b5893f02SDimitry Andric StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat,
900*b5893f02SDimitry Andric int MatchedCount, StringRef Buffer,
901*b5893f02SDimitry Andric StringMap<StringRef> &VariableTable, size_t MatchPos,
902*b5893f02SDimitry Andric size_t MatchLen, const FileCheckRequest &Req,
903*b5893f02SDimitry Andric std::vector<FileCheckDiag> *Diags) {
904*b5893f02SDimitry Andric if (ExpectedMatch) {
905*b5893f02SDimitry Andric if (!Req.Verbose)
906*b5893f02SDimitry Andric return;
907*b5893f02SDimitry Andric if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
908*b5893f02SDimitry Andric return;
909*b5893f02SDimitry Andric }
910*b5893f02SDimitry Andric SMRange MatchRange = ProcessMatchResult(
911*b5893f02SDimitry Andric ExpectedMatch ? FileCheckDiag::MatchFoundAndExpected
912*b5893f02SDimitry Andric : FileCheckDiag::MatchFoundButExcluded,
913*b5893f02SDimitry Andric SM, Loc, Pat.getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
914*b5893f02SDimitry Andric std::string Message = formatv("{0}: {1} string found in input",
915*b5893f02SDimitry Andric Pat.getCheckTy().getDescription(Prefix),
916*b5893f02SDimitry Andric (ExpectedMatch ? "expected" : "excluded"))
917*b5893f02SDimitry Andric .str();
918*b5893f02SDimitry Andric if (Pat.getCount() > 1)
919*b5893f02SDimitry Andric Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
920*b5893f02SDimitry Andric
921*b5893f02SDimitry Andric SM.PrintMessage(
922*b5893f02SDimitry Andric Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
923*b5893f02SDimitry Andric SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
924*b5893f02SDimitry Andric {MatchRange});
925*b5893f02SDimitry Andric Pat.PrintVariableUses(SM, Buffer, VariableTable, MatchRange);
926*b5893f02SDimitry Andric }
927*b5893f02SDimitry Andric
PrintMatch(bool ExpectedMatch,const SourceMgr & SM,const FileCheckString & CheckStr,int MatchedCount,StringRef Buffer,StringMap<StringRef> & VariableTable,size_t MatchPos,size_t MatchLen,FileCheckRequest & Req,std::vector<FileCheckDiag> * Diags)928*b5893f02SDimitry Andric static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
929*b5893f02SDimitry Andric const FileCheckString &CheckStr, int MatchedCount,
930*b5893f02SDimitry Andric StringRef Buffer, StringMap<StringRef> &VariableTable,
931*b5893f02SDimitry Andric size_t MatchPos, size_t MatchLen, FileCheckRequest &Req,
932*b5893f02SDimitry Andric std::vector<FileCheckDiag> *Diags) {
933*b5893f02SDimitry Andric PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
934*b5893f02SDimitry Andric MatchedCount, Buffer, VariableTable, MatchPos, MatchLen, Req,
935*b5893f02SDimitry Andric Diags);
936*b5893f02SDimitry Andric }
937*b5893f02SDimitry Andric
PrintNoMatch(bool ExpectedMatch,const SourceMgr & SM,StringRef Prefix,SMLoc Loc,const FileCheckPattern & Pat,int MatchedCount,StringRef Buffer,StringMap<StringRef> & VariableTable,bool VerboseVerbose,std::vector<FileCheckDiag> * Diags)938*b5893f02SDimitry Andric static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
939*b5893f02SDimitry Andric StringRef Prefix, SMLoc Loc,
940*b5893f02SDimitry Andric const FileCheckPattern &Pat, int MatchedCount,
941*b5893f02SDimitry Andric StringRef Buffer, StringMap<StringRef> &VariableTable,
942*b5893f02SDimitry Andric bool VerboseVerbose,
943*b5893f02SDimitry Andric std::vector<FileCheckDiag> *Diags) {
944*b5893f02SDimitry Andric if (!ExpectedMatch && !VerboseVerbose)
945*b5893f02SDimitry Andric return;
946*b5893f02SDimitry Andric
947*b5893f02SDimitry Andric // Otherwise, we have an error, emit an error message.
948*b5893f02SDimitry Andric std::string Message = formatv("{0}: {1} string not found in input",
949*b5893f02SDimitry Andric Pat.getCheckTy().getDescription(Prefix),
950*b5893f02SDimitry Andric (ExpectedMatch ? "expected" : "excluded"))
951*b5893f02SDimitry Andric .str();
952*b5893f02SDimitry Andric if (Pat.getCount() > 1)
953*b5893f02SDimitry Andric Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
954*b5893f02SDimitry Andric
955*b5893f02SDimitry Andric SM.PrintMessage(
956*b5893f02SDimitry Andric Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
957*b5893f02SDimitry Andric
958*b5893f02SDimitry Andric // Print the "scanning from here" line. If the current position is at the
959*b5893f02SDimitry Andric // end of a line, advance to the start of the next line.
960*b5893f02SDimitry Andric Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
961*b5893f02SDimitry Andric SMRange SearchRange = ProcessMatchResult(
962*b5893f02SDimitry Andric ExpectedMatch ? FileCheckDiag::MatchNoneButExpected
963*b5893f02SDimitry Andric : FileCheckDiag::MatchNoneAndExcluded,
964*b5893f02SDimitry Andric SM, Loc, Pat.getCheckTy(), Buffer, 0, Buffer.size(), Diags);
965*b5893f02SDimitry Andric SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
966*b5893f02SDimitry Andric
967*b5893f02SDimitry Andric // Allow the pattern to print additional information if desired.
968*b5893f02SDimitry Andric Pat.PrintVariableUses(SM, Buffer, VariableTable);
969*b5893f02SDimitry Andric
970*b5893f02SDimitry Andric if (ExpectedMatch)
971*b5893f02SDimitry Andric Pat.PrintFuzzyMatch(SM, Buffer, VariableTable, Diags);
972*b5893f02SDimitry Andric }
973*b5893f02SDimitry Andric
PrintNoMatch(bool ExpectedMatch,const SourceMgr & SM,const FileCheckString & CheckStr,int MatchedCount,StringRef Buffer,StringMap<StringRef> & VariableTable,bool VerboseVerbose,std::vector<FileCheckDiag> * Diags)974*b5893f02SDimitry Andric static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
975*b5893f02SDimitry Andric const FileCheckString &CheckStr, int MatchedCount,
976*b5893f02SDimitry Andric StringRef Buffer, StringMap<StringRef> &VariableTable,
977*b5893f02SDimitry Andric bool VerboseVerbose,
978*b5893f02SDimitry Andric std::vector<FileCheckDiag> *Diags) {
979*b5893f02SDimitry Andric PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
980*b5893f02SDimitry Andric MatchedCount, Buffer, VariableTable, VerboseVerbose, Diags);
981*b5893f02SDimitry Andric }
982*b5893f02SDimitry Andric
983*b5893f02SDimitry Andric /// Count the number of newlines in the specified range.
CountNumNewlinesBetween(StringRef Range,const char * & FirstNewLine)984*b5893f02SDimitry Andric static unsigned CountNumNewlinesBetween(StringRef Range,
985*b5893f02SDimitry Andric const char *&FirstNewLine) {
986*b5893f02SDimitry Andric unsigned NumNewLines = 0;
987*b5893f02SDimitry Andric while (1) {
988*b5893f02SDimitry Andric // Scan for newline.
989*b5893f02SDimitry Andric Range = Range.substr(Range.find_first_of("\n\r"));
990*b5893f02SDimitry Andric if (Range.empty())
991*b5893f02SDimitry Andric return NumNewLines;
992*b5893f02SDimitry Andric
993*b5893f02SDimitry Andric ++NumNewLines;
994*b5893f02SDimitry Andric
995*b5893f02SDimitry Andric // Handle \n\r and \r\n as a single newline.
996*b5893f02SDimitry Andric if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
997*b5893f02SDimitry Andric (Range[0] != Range[1]))
998*b5893f02SDimitry Andric Range = Range.substr(1);
999*b5893f02SDimitry Andric Range = Range.substr(1);
1000*b5893f02SDimitry Andric
1001*b5893f02SDimitry Andric if (NumNewLines == 1)
1002*b5893f02SDimitry Andric FirstNewLine = Range.begin();
1003*b5893f02SDimitry Andric }
1004*b5893f02SDimitry Andric }
1005*b5893f02SDimitry Andric
1006*b5893f02SDimitry Andric /// Match check string and its "not strings" and/or "dag strings".
Check(const SourceMgr & SM,StringRef Buffer,bool IsLabelScanMode,size_t & MatchLen,StringMap<StringRef> & VariableTable,FileCheckRequest & Req,std::vector<FileCheckDiag> * Diags) const1007*b5893f02SDimitry Andric size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
1008*b5893f02SDimitry Andric bool IsLabelScanMode, size_t &MatchLen,
1009*b5893f02SDimitry Andric StringMap<StringRef> &VariableTable,
1010*b5893f02SDimitry Andric FileCheckRequest &Req,
1011*b5893f02SDimitry Andric std::vector<FileCheckDiag> *Diags) const {
1012*b5893f02SDimitry Andric size_t LastPos = 0;
1013*b5893f02SDimitry Andric std::vector<const FileCheckPattern *> NotStrings;
1014*b5893f02SDimitry Andric
1015*b5893f02SDimitry Andric // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
1016*b5893f02SDimitry Andric // bounds; we have not processed variable definitions within the bounded block
1017*b5893f02SDimitry Andric // yet so cannot handle any final CHECK-DAG yet; this is handled when going
1018*b5893f02SDimitry Andric // over the block again (including the last CHECK-LABEL) in normal mode.
1019*b5893f02SDimitry Andric if (!IsLabelScanMode) {
1020*b5893f02SDimitry Andric // Match "dag strings" (with mixed "not strings" if any).
1021*b5893f02SDimitry Andric LastPos = CheckDag(SM, Buffer, NotStrings, VariableTable, Req, Diags);
1022*b5893f02SDimitry Andric if (LastPos == StringRef::npos)
1023*b5893f02SDimitry Andric return StringRef::npos;
1024*b5893f02SDimitry Andric }
1025*b5893f02SDimitry Andric
1026*b5893f02SDimitry Andric // Match itself from the last position after matching CHECK-DAG.
1027*b5893f02SDimitry Andric size_t LastMatchEnd = LastPos;
1028*b5893f02SDimitry Andric size_t FirstMatchPos = 0;
1029*b5893f02SDimitry Andric // Go match the pattern Count times. Majority of patterns only match with
1030*b5893f02SDimitry Andric // count 1 though.
1031*b5893f02SDimitry Andric assert(Pat.getCount() != 0 && "pattern count can not be zero");
1032*b5893f02SDimitry Andric for (int i = 1; i <= Pat.getCount(); i++) {
1033*b5893f02SDimitry Andric StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
1034*b5893f02SDimitry Andric size_t CurrentMatchLen;
1035*b5893f02SDimitry Andric // get a match at current start point
1036*b5893f02SDimitry Andric size_t MatchPos = Pat.Match(MatchBuffer, CurrentMatchLen, VariableTable);
1037*b5893f02SDimitry Andric if (i == 1)
1038*b5893f02SDimitry Andric FirstMatchPos = LastPos + MatchPos;
1039*b5893f02SDimitry Andric
1040*b5893f02SDimitry Andric // report
1041*b5893f02SDimitry Andric if (MatchPos == StringRef::npos) {
1042*b5893f02SDimitry Andric PrintNoMatch(true, SM, *this, i, MatchBuffer, VariableTable,
1043*b5893f02SDimitry Andric Req.VerboseVerbose, Diags);
1044*b5893f02SDimitry Andric return StringRef::npos;
1045*b5893f02SDimitry Andric }
1046*b5893f02SDimitry Andric PrintMatch(true, SM, *this, i, MatchBuffer, VariableTable, MatchPos,
1047*b5893f02SDimitry Andric CurrentMatchLen, Req, Diags);
1048*b5893f02SDimitry Andric
1049*b5893f02SDimitry Andric // move start point after the match
1050*b5893f02SDimitry Andric LastMatchEnd += MatchPos + CurrentMatchLen;
1051*b5893f02SDimitry Andric }
1052*b5893f02SDimitry Andric // Full match len counts from first match pos.
1053*b5893f02SDimitry Andric MatchLen = LastMatchEnd - FirstMatchPos;
1054*b5893f02SDimitry Andric
1055*b5893f02SDimitry Andric // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1056*b5893f02SDimitry Andric // or CHECK-NOT
1057*b5893f02SDimitry Andric if (!IsLabelScanMode) {
1058*b5893f02SDimitry Andric size_t MatchPos = FirstMatchPos - LastPos;
1059*b5893f02SDimitry Andric StringRef MatchBuffer = Buffer.substr(LastPos);
1060*b5893f02SDimitry Andric StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1061*b5893f02SDimitry Andric
1062*b5893f02SDimitry Andric // If this check is a "CHECK-NEXT", verify that the previous match was on
1063*b5893f02SDimitry Andric // the previous line (i.e. that there is one newline between them).
1064*b5893f02SDimitry Andric if (CheckNext(SM, SkippedRegion)) {
1065*b5893f02SDimitry Andric ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
1066*b5893f02SDimitry Andric Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
1067*b5893f02SDimitry Andric Diags, Req.Verbose);
1068*b5893f02SDimitry Andric return StringRef::npos;
1069*b5893f02SDimitry Andric }
1070*b5893f02SDimitry Andric
1071*b5893f02SDimitry Andric // If this check is a "CHECK-SAME", verify that the previous match was on
1072*b5893f02SDimitry Andric // the same line (i.e. that there is no newline between them).
1073*b5893f02SDimitry Andric if (CheckSame(SM, SkippedRegion)) {
1074*b5893f02SDimitry Andric ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
1075*b5893f02SDimitry Andric Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
1076*b5893f02SDimitry Andric Diags, Req.Verbose);
1077*b5893f02SDimitry Andric return StringRef::npos;
1078*b5893f02SDimitry Andric }
1079*b5893f02SDimitry Andric
1080*b5893f02SDimitry Andric // If this match had "not strings", verify that they don't exist in the
1081*b5893f02SDimitry Andric // skipped region.
1082*b5893f02SDimitry Andric if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable, Req, Diags))
1083*b5893f02SDimitry Andric return StringRef::npos;
1084*b5893f02SDimitry Andric }
1085*b5893f02SDimitry Andric
1086*b5893f02SDimitry Andric return FirstMatchPos;
1087*b5893f02SDimitry Andric }
1088*b5893f02SDimitry Andric
1089*b5893f02SDimitry Andric /// Verify there is a single line in the given buffer.
CheckNext(const SourceMgr & SM,StringRef Buffer) const1090*b5893f02SDimitry Andric bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1091*b5893f02SDimitry Andric if (Pat.getCheckTy() != Check::CheckNext &&
1092*b5893f02SDimitry Andric Pat.getCheckTy() != Check::CheckEmpty)
1093*b5893f02SDimitry Andric return false;
1094*b5893f02SDimitry Andric
1095*b5893f02SDimitry Andric Twine CheckName =
1096*b5893f02SDimitry Andric Prefix +
1097*b5893f02SDimitry Andric Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
1098*b5893f02SDimitry Andric
1099*b5893f02SDimitry Andric // Count the number of newlines between the previous match and this one.
1100*b5893f02SDimitry Andric assert(Buffer.data() !=
1101*b5893f02SDimitry Andric SM.getMemoryBuffer(SM.FindBufferContainingLoc(
1102*b5893f02SDimitry Andric SMLoc::getFromPointer(Buffer.data())))
1103*b5893f02SDimitry Andric ->getBufferStart() &&
1104*b5893f02SDimitry Andric "CHECK-NEXT and CHECK-EMPTY can't be the first check in a file");
1105*b5893f02SDimitry Andric
1106*b5893f02SDimitry Andric const char *FirstNewLine = nullptr;
1107*b5893f02SDimitry Andric unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1108*b5893f02SDimitry Andric
1109*b5893f02SDimitry Andric if (NumNewLines == 0) {
1110*b5893f02SDimitry Andric SM.PrintMessage(Loc, SourceMgr::DK_Error,
1111*b5893f02SDimitry Andric CheckName + ": is on the same line as previous match");
1112*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1113*b5893f02SDimitry Andric "'next' match was here");
1114*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1115*b5893f02SDimitry Andric "previous match ended here");
1116*b5893f02SDimitry Andric return true;
1117*b5893f02SDimitry Andric }
1118*b5893f02SDimitry Andric
1119*b5893f02SDimitry Andric if (NumNewLines != 1) {
1120*b5893f02SDimitry Andric SM.PrintMessage(Loc, SourceMgr::DK_Error,
1121*b5893f02SDimitry Andric CheckName +
1122*b5893f02SDimitry Andric ": is not on the line after the previous match");
1123*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1124*b5893f02SDimitry Andric "'next' match was here");
1125*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1126*b5893f02SDimitry Andric "previous match ended here");
1127*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
1128*b5893f02SDimitry Andric "non-matching line after previous match is here");
1129*b5893f02SDimitry Andric return true;
1130*b5893f02SDimitry Andric }
1131*b5893f02SDimitry Andric
1132*b5893f02SDimitry Andric return false;
1133*b5893f02SDimitry Andric }
1134*b5893f02SDimitry Andric
1135*b5893f02SDimitry Andric /// Verify there is no newline in the given buffer.
CheckSame(const SourceMgr & SM,StringRef Buffer) const1136*b5893f02SDimitry Andric bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
1137*b5893f02SDimitry Andric if (Pat.getCheckTy() != Check::CheckSame)
1138*b5893f02SDimitry Andric return false;
1139*b5893f02SDimitry Andric
1140*b5893f02SDimitry Andric // Count the number of newlines between the previous match and this one.
1141*b5893f02SDimitry Andric assert(Buffer.data() !=
1142*b5893f02SDimitry Andric SM.getMemoryBuffer(SM.FindBufferContainingLoc(
1143*b5893f02SDimitry Andric SMLoc::getFromPointer(Buffer.data())))
1144*b5893f02SDimitry Andric ->getBufferStart() &&
1145*b5893f02SDimitry Andric "CHECK-SAME can't be the first check in a file");
1146*b5893f02SDimitry Andric
1147*b5893f02SDimitry Andric const char *FirstNewLine = nullptr;
1148*b5893f02SDimitry Andric unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1149*b5893f02SDimitry Andric
1150*b5893f02SDimitry Andric if (NumNewLines != 0) {
1151*b5893f02SDimitry Andric SM.PrintMessage(Loc, SourceMgr::DK_Error,
1152*b5893f02SDimitry Andric Prefix +
1153*b5893f02SDimitry Andric "-SAME: is not on the same line as the previous match");
1154*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
1155*b5893f02SDimitry Andric "'next' match was here");
1156*b5893f02SDimitry Andric SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
1157*b5893f02SDimitry Andric "previous match ended here");
1158*b5893f02SDimitry Andric return true;
1159*b5893f02SDimitry Andric }
1160*b5893f02SDimitry Andric
1161*b5893f02SDimitry Andric return false;
1162*b5893f02SDimitry Andric }
1163*b5893f02SDimitry Andric
1164*b5893f02SDimitry Andric /// Verify there's no "not strings" in the given buffer.
CheckNot(const SourceMgr & SM,StringRef Buffer,const std::vector<const FileCheckPattern * > & NotStrings,StringMap<StringRef> & VariableTable,const FileCheckRequest & Req,std::vector<FileCheckDiag> * Diags) const1165*b5893f02SDimitry Andric bool FileCheckString::CheckNot(
1166*b5893f02SDimitry Andric const SourceMgr &SM, StringRef Buffer,
1167*b5893f02SDimitry Andric const std::vector<const FileCheckPattern *> &NotStrings,
1168*b5893f02SDimitry Andric StringMap<StringRef> &VariableTable, const FileCheckRequest &Req,
1169*b5893f02SDimitry Andric std::vector<FileCheckDiag> *Diags) const {
1170*b5893f02SDimitry Andric for (const FileCheckPattern *Pat : NotStrings) {
1171*b5893f02SDimitry Andric assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1172*b5893f02SDimitry Andric
1173*b5893f02SDimitry Andric size_t MatchLen = 0;
1174*b5893f02SDimitry Andric size_t Pos = Pat->Match(Buffer, MatchLen, VariableTable);
1175*b5893f02SDimitry Andric
1176*b5893f02SDimitry Andric if (Pos == StringRef::npos) {
1177*b5893f02SDimitry Andric PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
1178*b5893f02SDimitry Andric VariableTable, Req.VerboseVerbose, Diags);
1179*b5893f02SDimitry Andric continue;
1180*b5893f02SDimitry Andric }
1181*b5893f02SDimitry Andric
1182*b5893f02SDimitry Andric PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, VariableTable,
1183*b5893f02SDimitry Andric Pos, MatchLen, Req, Diags);
1184*b5893f02SDimitry Andric
1185*b5893f02SDimitry Andric return true;
1186*b5893f02SDimitry Andric }
1187*b5893f02SDimitry Andric
1188*b5893f02SDimitry Andric return false;
1189*b5893f02SDimitry Andric }
1190*b5893f02SDimitry Andric
1191*b5893f02SDimitry Andric /// Match "dag strings" and their mixed "not strings".
1192*b5893f02SDimitry Andric size_t
CheckDag(const SourceMgr & SM,StringRef Buffer,std::vector<const FileCheckPattern * > & NotStrings,StringMap<StringRef> & VariableTable,const FileCheckRequest & Req,std::vector<FileCheckDiag> * Diags) const1193*b5893f02SDimitry Andric FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
1194*b5893f02SDimitry Andric std::vector<const FileCheckPattern *> &NotStrings,
1195*b5893f02SDimitry Andric StringMap<StringRef> &VariableTable,
1196*b5893f02SDimitry Andric const FileCheckRequest &Req,
1197*b5893f02SDimitry Andric std::vector<FileCheckDiag> *Diags) const {
1198*b5893f02SDimitry Andric if (DagNotStrings.empty())
1199*b5893f02SDimitry Andric return 0;
1200*b5893f02SDimitry Andric
1201*b5893f02SDimitry Andric // The start of the search range.
1202*b5893f02SDimitry Andric size_t StartPos = 0;
1203*b5893f02SDimitry Andric
1204*b5893f02SDimitry Andric struct MatchRange {
1205*b5893f02SDimitry Andric size_t Pos;
1206*b5893f02SDimitry Andric size_t End;
1207*b5893f02SDimitry Andric };
1208*b5893f02SDimitry Andric // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
1209*b5893f02SDimitry Andric // ranges are erased from this list once they are no longer in the search
1210*b5893f02SDimitry Andric // range.
1211*b5893f02SDimitry Andric std::list<MatchRange> MatchRanges;
1212*b5893f02SDimitry Andric
1213*b5893f02SDimitry Andric // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
1214*b5893f02SDimitry Andric // group, so we don't use a range-based for loop here.
1215*b5893f02SDimitry Andric for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
1216*b5893f02SDimitry Andric PatItr != PatEnd; ++PatItr) {
1217*b5893f02SDimitry Andric const FileCheckPattern &Pat = *PatItr;
1218*b5893f02SDimitry Andric assert((Pat.getCheckTy() == Check::CheckDAG ||
1219*b5893f02SDimitry Andric Pat.getCheckTy() == Check::CheckNot) &&
1220*b5893f02SDimitry Andric "Invalid CHECK-DAG or CHECK-NOT!");
1221*b5893f02SDimitry Andric
1222*b5893f02SDimitry Andric if (Pat.getCheckTy() == Check::CheckNot) {
1223*b5893f02SDimitry Andric NotStrings.push_back(&Pat);
1224*b5893f02SDimitry Andric continue;
1225*b5893f02SDimitry Andric }
1226*b5893f02SDimitry Andric
1227*b5893f02SDimitry Andric assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1228*b5893f02SDimitry Andric
1229*b5893f02SDimitry Andric // CHECK-DAG always matches from the start.
1230*b5893f02SDimitry Andric size_t MatchLen = 0, MatchPos = StartPos;
1231*b5893f02SDimitry Andric
1232*b5893f02SDimitry Andric // Search for a match that doesn't overlap a previous match in this
1233*b5893f02SDimitry Andric // CHECK-DAG group.
1234*b5893f02SDimitry Andric for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
1235*b5893f02SDimitry Andric StringRef MatchBuffer = Buffer.substr(MatchPos);
1236*b5893f02SDimitry Andric size_t MatchPosBuf = Pat.Match(MatchBuffer, MatchLen, VariableTable);
1237*b5893f02SDimitry Andric // With a group of CHECK-DAGs, a single mismatching means the match on
1238*b5893f02SDimitry Andric // that group of CHECK-DAGs fails immediately.
1239*b5893f02SDimitry Andric if (MatchPosBuf == StringRef::npos) {
1240*b5893f02SDimitry Andric PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
1241*b5893f02SDimitry Andric VariableTable, Req.VerboseVerbose, Diags);
1242*b5893f02SDimitry Andric return StringRef::npos;
1243*b5893f02SDimitry Andric }
1244*b5893f02SDimitry Andric // Re-calc it as the offset relative to the start of the original string.
1245*b5893f02SDimitry Andric MatchPos += MatchPosBuf;
1246*b5893f02SDimitry Andric if (Req.VerboseVerbose)
1247*b5893f02SDimitry Andric PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer,
1248*b5893f02SDimitry Andric VariableTable, MatchPos, MatchLen, Req, Diags);
1249*b5893f02SDimitry Andric MatchRange M{MatchPos, MatchPos + MatchLen};
1250*b5893f02SDimitry Andric if (Req.AllowDeprecatedDagOverlap) {
1251*b5893f02SDimitry Andric // We don't need to track all matches in this mode, so we just maintain
1252*b5893f02SDimitry Andric // one match range that encompasses the current CHECK-DAG group's
1253*b5893f02SDimitry Andric // matches.
1254*b5893f02SDimitry Andric if (MatchRanges.empty())
1255*b5893f02SDimitry Andric MatchRanges.insert(MatchRanges.end(), M);
1256*b5893f02SDimitry Andric else {
1257*b5893f02SDimitry Andric auto Block = MatchRanges.begin();
1258*b5893f02SDimitry Andric Block->Pos = std::min(Block->Pos, M.Pos);
1259*b5893f02SDimitry Andric Block->End = std::max(Block->End, M.End);
1260*b5893f02SDimitry Andric }
1261*b5893f02SDimitry Andric break;
1262*b5893f02SDimitry Andric }
1263*b5893f02SDimitry Andric // Iterate previous matches until overlapping match or insertion point.
1264*b5893f02SDimitry Andric bool Overlap = false;
1265*b5893f02SDimitry Andric for (; MI != ME; ++MI) {
1266*b5893f02SDimitry Andric if (M.Pos < MI->End) {
1267*b5893f02SDimitry Andric // !Overlap => New match has no overlap and is before this old match.
1268*b5893f02SDimitry Andric // Overlap => New match overlaps this old match.
1269*b5893f02SDimitry Andric Overlap = MI->Pos < M.End;
1270*b5893f02SDimitry Andric break;
1271*b5893f02SDimitry Andric }
1272*b5893f02SDimitry Andric }
1273*b5893f02SDimitry Andric if (!Overlap) {
1274*b5893f02SDimitry Andric // Insert non-overlapping match into list.
1275*b5893f02SDimitry Andric MatchRanges.insert(MI, M);
1276*b5893f02SDimitry Andric break;
1277*b5893f02SDimitry Andric }
1278*b5893f02SDimitry Andric if (Req.VerboseVerbose) {
1279*b5893f02SDimitry Andric SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
1280*b5893f02SDimitry Andric SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
1281*b5893f02SDimitry Andric SMRange OldRange(OldStart, OldEnd);
1282*b5893f02SDimitry Andric SM.PrintMessage(OldStart, SourceMgr::DK_Note,
1283*b5893f02SDimitry Andric "match discarded, overlaps earlier DAG match here",
1284*b5893f02SDimitry Andric {OldRange});
1285*b5893f02SDimitry Andric if (Diags)
1286*b5893f02SDimitry Andric Diags->rbegin()->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
1287*b5893f02SDimitry Andric }
1288*b5893f02SDimitry Andric MatchPos = MI->End;
1289*b5893f02SDimitry Andric }
1290*b5893f02SDimitry Andric if (!Req.VerboseVerbose)
1291*b5893f02SDimitry Andric PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, VariableTable,
1292*b5893f02SDimitry Andric MatchPos, MatchLen, Req, Diags);
1293*b5893f02SDimitry Andric
1294*b5893f02SDimitry Andric // Handle the end of a CHECK-DAG group.
1295*b5893f02SDimitry Andric if (std::next(PatItr) == PatEnd ||
1296*b5893f02SDimitry Andric std::next(PatItr)->getCheckTy() == Check::CheckNot) {
1297*b5893f02SDimitry Andric if (!NotStrings.empty()) {
1298*b5893f02SDimitry Andric // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
1299*b5893f02SDimitry Andric // CHECK-DAG, verify that there are no 'not' strings occurred in that
1300*b5893f02SDimitry Andric // region.
1301*b5893f02SDimitry Andric StringRef SkippedRegion =
1302*b5893f02SDimitry Andric Buffer.slice(StartPos, MatchRanges.begin()->Pos);
1303*b5893f02SDimitry Andric if (CheckNot(SM, SkippedRegion, NotStrings, VariableTable, Req, Diags))
1304*b5893f02SDimitry Andric return StringRef::npos;
1305*b5893f02SDimitry Andric // Clear "not strings".
1306*b5893f02SDimitry Andric NotStrings.clear();
1307*b5893f02SDimitry Andric }
1308*b5893f02SDimitry Andric // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
1309*b5893f02SDimitry Andric // end of this CHECK-DAG group's match range.
1310*b5893f02SDimitry Andric StartPos = MatchRanges.rbegin()->End;
1311*b5893f02SDimitry Andric // Don't waste time checking for (impossible) overlaps before that.
1312*b5893f02SDimitry Andric MatchRanges.clear();
1313*b5893f02SDimitry Andric }
1314*b5893f02SDimitry Andric }
1315*b5893f02SDimitry Andric
1316*b5893f02SDimitry Andric return StartPos;
1317*b5893f02SDimitry Andric }
1318*b5893f02SDimitry Andric
1319*b5893f02SDimitry Andric // A check prefix must contain only alphanumeric, hyphens and underscores.
ValidateCheckPrefix(StringRef CheckPrefix)1320*b5893f02SDimitry Andric static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1321*b5893f02SDimitry Andric Regex Validator("^[a-zA-Z0-9_-]*$");
1322*b5893f02SDimitry Andric return Validator.match(CheckPrefix);
1323*b5893f02SDimitry Andric }
1324*b5893f02SDimitry Andric
ValidateCheckPrefixes()1325*b5893f02SDimitry Andric bool llvm::FileCheck::ValidateCheckPrefixes() {
1326*b5893f02SDimitry Andric StringSet<> PrefixSet;
1327*b5893f02SDimitry Andric
1328*b5893f02SDimitry Andric for (StringRef Prefix : Req.CheckPrefixes) {
1329*b5893f02SDimitry Andric // Reject empty prefixes.
1330*b5893f02SDimitry Andric if (Prefix == "")
1331*b5893f02SDimitry Andric return false;
1332*b5893f02SDimitry Andric
1333*b5893f02SDimitry Andric if (!PrefixSet.insert(Prefix).second)
1334*b5893f02SDimitry Andric return false;
1335*b5893f02SDimitry Andric
1336*b5893f02SDimitry Andric if (!ValidateCheckPrefix(Prefix))
1337*b5893f02SDimitry Andric return false;
1338*b5893f02SDimitry Andric }
1339*b5893f02SDimitry Andric
1340*b5893f02SDimitry Andric return true;
1341*b5893f02SDimitry Andric }
1342*b5893f02SDimitry Andric
1343*b5893f02SDimitry Andric // Combines the check prefixes into a single regex so that we can efficiently
1344*b5893f02SDimitry Andric // scan for any of the set.
1345*b5893f02SDimitry Andric //
1346*b5893f02SDimitry Andric // The semantics are that the longest-match wins which matches our regex
1347*b5893f02SDimitry Andric // library.
buildCheckPrefixRegex()1348*b5893f02SDimitry Andric Regex llvm::FileCheck::buildCheckPrefixRegex() {
1349*b5893f02SDimitry Andric // I don't think there's a way to specify an initial value for cl::list,
1350*b5893f02SDimitry Andric // so if nothing was specified, add the default
1351*b5893f02SDimitry Andric if (Req.CheckPrefixes.empty())
1352*b5893f02SDimitry Andric Req.CheckPrefixes.push_back("CHECK");
1353*b5893f02SDimitry Andric
1354*b5893f02SDimitry Andric // We already validated the contents of CheckPrefixes so just concatenate
1355*b5893f02SDimitry Andric // them as alternatives.
1356*b5893f02SDimitry Andric SmallString<32> PrefixRegexStr;
1357*b5893f02SDimitry Andric for (StringRef Prefix : Req.CheckPrefixes) {
1358*b5893f02SDimitry Andric if (Prefix != Req.CheckPrefixes.front())
1359*b5893f02SDimitry Andric PrefixRegexStr.push_back('|');
1360*b5893f02SDimitry Andric
1361*b5893f02SDimitry Andric PrefixRegexStr.append(Prefix);
1362*b5893f02SDimitry Andric }
1363*b5893f02SDimitry Andric
1364*b5893f02SDimitry Andric return Regex(PrefixRegexStr);
1365*b5893f02SDimitry Andric }
1366*b5893f02SDimitry Andric
1367*b5893f02SDimitry Andric // Remove local variables from \p VariableTable. Global variables
1368*b5893f02SDimitry Andric // (start with '$') are preserved.
ClearLocalVars(StringMap<StringRef> & VariableTable)1369*b5893f02SDimitry Andric static void ClearLocalVars(StringMap<StringRef> &VariableTable) {
1370*b5893f02SDimitry Andric SmallVector<StringRef, 16> LocalVars;
1371*b5893f02SDimitry Andric for (const auto &Var : VariableTable)
1372*b5893f02SDimitry Andric if (Var.first()[0] != '$')
1373*b5893f02SDimitry Andric LocalVars.push_back(Var.first());
1374*b5893f02SDimitry Andric
1375*b5893f02SDimitry Andric for (const auto &Var : LocalVars)
1376*b5893f02SDimitry Andric VariableTable.erase(Var);
1377*b5893f02SDimitry Andric }
1378*b5893f02SDimitry Andric
1379*b5893f02SDimitry Andric /// Check the input to FileCheck provided in the \p Buffer against the \p
1380*b5893f02SDimitry Andric /// CheckStrings read from the check file.
1381*b5893f02SDimitry Andric ///
1382*b5893f02SDimitry Andric /// Returns false if the input fails to satisfy the checks.
CheckInput(SourceMgr & SM,StringRef Buffer,ArrayRef<FileCheckString> CheckStrings,std::vector<FileCheckDiag> * Diags)1383*b5893f02SDimitry Andric bool llvm::FileCheck::CheckInput(SourceMgr &SM, StringRef Buffer,
1384*b5893f02SDimitry Andric ArrayRef<FileCheckString> CheckStrings,
1385*b5893f02SDimitry Andric std::vector<FileCheckDiag> *Diags) {
1386*b5893f02SDimitry Andric bool ChecksFailed = false;
1387*b5893f02SDimitry Andric
1388*b5893f02SDimitry Andric /// VariableTable - This holds all the current filecheck variables.
1389*b5893f02SDimitry Andric StringMap<StringRef> VariableTable;
1390*b5893f02SDimitry Andric
1391*b5893f02SDimitry Andric for (const auto& Def : Req.GlobalDefines)
1392*b5893f02SDimitry Andric VariableTable.insert(StringRef(Def).split('='));
1393*b5893f02SDimitry Andric
1394*b5893f02SDimitry Andric unsigned i = 0, j = 0, e = CheckStrings.size();
1395*b5893f02SDimitry Andric while (true) {
1396*b5893f02SDimitry Andric StringRef CheckRegion;
1397*b5893f02SDimitry Andric if (j == e) {
1398*b5893f02SDimitry Andric CheckRegion = Buffer;
1399*b5893f02SDimitry Andric } else {
1400*b5893f02SDimitry Andric const FileCheckString &CheckLabelStr = CheckStrings[j];
1401*b5893f02SDimitry Andric if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
1402*b5893f02SDimitry Andric ++j;
1403*b5893f02SDimitry Andric continue;
1404*b5893f02SDimitry Andric }
1405*b5893f02SDimitry Andric
1406*b5893f02SDimitry Andric // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1407*b5893f02SDimitry Andric size_t MatchLabelLen = 0;
1408*b5893f02SDimitry Andric size_t MatchLabelPos = CheckLabelStr.Check(
1409*b5893f02SDimitry Andric SM, Buffer, true, MatchLabelLen, VariableTable, Req, Diags);
1410*b5893f02SDimitry Andric if (MatchLabelPos == StringRef::npos)
1411*b5893f02SDimitry Andric // Immediately bail of CHECK-LABEL fails, nothing else we can do.
1412*b5893f02SDimitry Andric return false;
1413*b5893f02SDimitry Andric
1414*b5893f02SDimitry Andric CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1415*b5893f02SDimitry Andric Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1416*b5893f02SDimitry Andric ++j;
1417*b5893f02SDimitry Andric }
1418*b5893f02SDimitry Andric
1419*b5893f02SDimitry Andric if (Req.EnableVarScope)
1420*b5893f02SDimitry Andric ClearLocalVars(VariableTable);
1421*b5893f02SDimitry Andric
1422*b5893f02SDimitry Andric for (; i != j; ++i) {
1423*b5893f02SDimitry Andric const FileCheckString &CheckStr = CheckStrings[i];
1424*b5893f02SDimitry Andric
1425*b5893f02SDimitry Andric // Check each string within the scanned region, including a second check
1426*b5893f02SDimitry Andric // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1427*b5893f02SDimitry Andric size_t MatchLen = 0;
1428*b5893f02SDimitry Andric size_t MatchPos = CheckStr.Check(SM, CheckRegion, false, MatchLen,
1429*b5893f02SDimitry Andric VariableTable, Req, Diags);
1430*b5893f02SDimitry Andric
1431*b5893f02SDimitry Andric if (MatchPos == StringRef::npos) {
1432*b5893f02SDimitry Andric ChecksFailed = true;
1433*b5893f02SDimitry Andric i = j;
1434*b5893f02SDimitry Andric break;
1435*b5893f02SDimitry Andric }
1436*b5893f02SDimitry Andric
1437*b5893f02SDimitry Andric CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
1438*b5893f02SDimitry Andric }
1439*b5893f02SDimitry Andric
1440*b5893f02SDimitry Andric if (j == e)
1441*b5893f02SDimitry Andric break;
1442*b5893f02SDimitry Andric }
1443*b5893f02SDimitry Andric
1444*b5893f02SDimitry Andric // Success if no checks failed.
1445*b5893f02SDimitry Andric return !ChecksFailed;
1446*b5893f02SDimitry Andric }
1447