FileCheck.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  1. //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // FileCheck does a line-by line check of a file that validates whether it
  10. // contains the expected content. This is useful for regression tests etc.
  11. //
  12. // This file implements most of the API that will be used by the FileCheck utility
  13. // as well as various unittests.
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Support/FileCheck.h"
  16. #include "llvm/ADT/StringSet.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Support/FormatVariadic.h"
  19. #include <cstdint>
  20. #include <list>
  21. #include <tuple>
  22. #include <utility>
  23. using namespace llvm;
  24. Expected<uint64_t> FileCheckNumericVariableUse::eval() const {
  25. Optional<uint64_t> Value = NumericVariable->getValue();
  26. if (Value)
  27. return *Value;
  28. return make_error<FileCheckUndefVarError>(Name);
  29. }
  30. Expected<uint64_t> FileCheckASTBinop::eval() const {
  31. Expected<uint64_t> LeftOp = LeftOperand->eval();
  32. Expected<uint64_t> RightOp = RightOperand->eval();
  33. // Bubble up any error (e.g. undefined variables) in the recursive
  34. // evaluation.
  35. if (!LeftOp || !RightOp) {
  36. Error Err = Error::success();
  37. if (!LeftOp)
  38. Err = joinErrors(std::move(Err), LeftOp.takeError());
  39. if (!RightOp)
  40. Err = joinErrors(std::move(Err), RightOp.takeError());
  41. return std::move(Err);
  42. }
  43. return EvalBinop(*LeftOp, *RightOp);
  44. }
  45. Expected<std::string> FileCheckNumericSubstitution::getResult() const {
  46. Expected<uint64_t> EvaluatedValue = ExpressionAST->eval();
  47. if (!EvaluatedValue)
  48. return EvaluatedValue.takeError();
  49. return utostr(*EvaluatedValue);
  50. }
  51. Expected<std::string> FileCheckStringSubstitution::getResult() const {
  52. // Look up the value and escape it so that we can put it into the regex.
  53. Expected<StringRef> VarVal = Context->getPatternVarValue(FromStr);
  54. if (!VarVal)
  55. return VarVal.takeError();
  56. return Regex::escape(*VarVal);
  57. }
  58. bool FileCheckPattern::isValidVarNameStart(char C) {
  59. return C == '_' || isalpha(C);
  60. }
  61. Expected<FileCheckPattern::VariableProperties>
  62. FileCheckPattern::parseVariable(StringRef &Str, const SourceMgr &SM) {
  63. if (Str.empty())
  64. return FileCheckErrorDiagnostic::get(SM, Str, "empty variable name");
  65. bool ParsedOneChar = false;
  66. unsigned I = 0;
  67. bool IsPseudo = Str[0] == '@';
  68. // Global vars start with '$'.
  69. if (Str[0] == '$' || IsPseudo)
  70. ++I;
  71. for (unsigned E = Str.size(); I != E; ++I) {
  72. if (!ParsedOneChar && !isValidVarNameStart(Str[I]))
  73. return FileCheckErrorDiagnostic::get(SM, Str, "invalid variable name");
  74. // Variable names are composed of alphanumeric characters and underscores.
  75. if (Str[I] != '_' && !isalnum(Str[I]))
  76. break;
  77. ParsedOneChar = true;
  78. }
  79. StringRef Name = Str.take_front(I);
  80. Str = Str.substr(I);
  81. return VariableProperties {Name, IsPseudo};
  82. }
  83. // StringRef holding all characters considered as horizontal whitespaces by
  84. // FileCheck input canonicalization.
  85. constexpr StringLiteral SpaceChars = " \t";
  86. // Parsing helper function that strips the first character in S and returns it.
  87. static char popFront(StringRef &S) {
  88. char C = S.front();
  89. S = S.drop_front();
  90. return C;
  91. }
  92. char FileCheckUndefVarError::ID = 0;
  93. char FileCheckErrorDiagnostic::ID = 0;
  94. char FileCheckNotFoundError::ID = 0;
  95. Expected<FileCheckNumericVariable *>
  96. FileCheckPattern::parseNumericVariableDefinition(
  97. StringRef &Expr, FileCheckPatternContext *Context,
  98. Optional<size_t> LineNumber, const SourceMgr &SM) {
  99. Expected<VariableProperties> ParseVarResult = parseVariable(Expr, SM);
  100. if (!ParseVarResult)
  101. return ParseVarResult.takeError();
  102. StringRef Name = ParseVarResult->Name;
  103. if (ParseVarResult->IsPseudo)
  104. return FileCheckErrorDiagnostic::get(
  105. SM, Name, "definition of pseudo numeric variable unsupported");
  106. // Detect collisions between string and numeric variables when the latter
  107. // is created later than the former.
  108. if (Context->DefinedVariableTable.find(Name) !=
  109. Context->DefinedVariableTable.end())
  110. return FileCheckErrorDiagnostic::get(
  111. SM, Name, "string variable with name '" + Name + "' already exists");
  112. Expr = Expr.ltrim(SpaceChars);
  113. if (!Expr.empty())
  114. return FileCheckErrorDiagnostic::get(
  115. SM, Expr, "unexpected characters after numeric variable name");
  116. FileCheckNumericVariable *DefinedNumericVariable;
  117. auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
  118. if (VarTableIter != Context->GlobalNumericVariableTable.end())
  119. DefinedNumericVariable = VarTableIter->second;
  120. else
  121. DefinedNumericVariable = Context->makeNumericVariable(Name, LineNumber);
  122. return DefinedNumericVariable;
  123. }
  124. Expected<std::unique_ptr<FileCheckNumericVariableUse>>
  125. FileCheckPattern::parseNumericVariableUse(StringRef Name, bool IsPseudo,
  126. Optional<size_t> LineNumber,
  127. FileCheckPatternContext *Context,
  128. const SourceMgr &SM) {
  129. if (IsPseudo && !Name.equals("@LINE"))
  130. return FileCheckErrorDiagnostic::get(
  131. SM, Name, "invalid pseudo numeric variable '" + Name + "'");
  132. // Numeric variable definitions and uses are parsed in the order in which
  133. // they appear in the CHECK patterns. For each definition, the pointer to the
  134. // class instance of the corresponding numeric variable definition is stored
  135. // in GlobalNumericVariableTable in parsePattern. Therefore, if the pointer
  136. // we get below is null, it means no such variable was defined before. When
  137. // that happens, we create a dummy variable so that parsing can continue. All
  138. // uses of undefined variables, whether string or numeric, are then diagnosed
  139. // in printSubstitutions() after failing to match.
  140. auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
  141. FileCheckNumericVariable *NumericVariable;
  142. if (VarTableIter != Context->GlobalNumericVariableTable.end())
  143. NumericVariable = VarTableIter->second;
  144. else {
  145. NumericVariable = Context->makeNumericVariable(Name);
  146. Context->GlobalNumericVariableTable[Name] = NumericVariable;
  147. }
  148. Optional<size_t> DefLineNumber = NumericVariable->getDefLineNumber();
  149. if (DefLineNumber && LineNumber && *DefLineNumber == *LineNumber)
  150. return FileCheckErrorDiagnostic::get(
  151. SM, Name,
  152. "numeric variable '" + Name +
  153. "' defined earlier in the same CHECK directive");
  154. return std::make_unique<FileCheckNumericVariableUse>(Name, NumericVariable);
  155. }
  156. Expected<std::unique_ptr<FileCheckExpressionAST>>
  157. FileCheckPattern::parseNumericOperand(StringRef &Expr, AllowedOperand AO,
  158. Optional<size_t> LineNumber,
  159. FileCheckPatternContext *Context,
  160. const SourceMgr &SM) {
  161. if (AO == AllowedOperand::LineVar || AO == AllowedOperand::Any) {
  162. // Try to parse as a numeric variable use.
  163. Expected<FileCheckPattern::VariableProperties> ParseVarResult =
  164. parseVariable(Expr, SM);
  165. if (ParseVarResult)
  166. return parseNumericVariableUse(ParseVarResult->Name,
  167. ParseVarResult->IsPseudo, LineNumber,
  168. Context, SM);
  169. if (AO == AllowedOperand::LineVar)
  170. return ParseVarResult.takeError();
  171. // Ignore the error and retry parsing as a literal.
  172. consumeError(ParseVarResult.takeError());
  173. }
  174. // Otherwise, parse it as a literal.
  175. uint64_t LiteralValue;
  176. if (!Expr.consumeInteger(/*Radix=*/10, LiteralValue))
  177. return std::make_unique<FileCheckExpressionLiteral>(LiteralValue);
  178. return FileCheckErrorDiagnostic::get(SM, Expr,
  179. "invalid operand format '" + Expr + "'");
  180. }
  181. static uint64_t add(uint64_t LeftOp, uint64_t RightOp) {
  182. return LeftOp + RightOp;
  183. }
  184. static uint64_t sub(uint64_t LeftOp, uint64_t RightOp) {
  185. return LeftOp - RightOp;
  186. }
  187. Expected<std::unique_ptr<FileCheckExpressionAST>> FileCheckPattern::parseBinop(
  188. StringRef &Expr, std::unique_ptr<FileCheckExpressionAST> LeftOp,
  189. bool IsLegacyLineExpr, Optional<size_t> LineNumber,
  190. FileCheckPatternContext *Context, const SourceMgr &SM) {
  191. Expr = Expr.ltrim(SpaceChars);
  192. if (Expr.empty())
  193. return std::move(LeftOp);
  194. // Check if this is a supported operation and select a function to perform
  195. // it.
  196. SMLoc OpLoc = SMLoc::getFromPointer(Expr.data());
  197. char Operator = popFront(Expr);
  198. binop_eval_t EvalBinop;
  199. switch (Operator) {
  200. case '+':
  201. EvalBinop = add;
  202. break;
  203. case '-':
  204. EvalBinop = sub;
  205. break;
  206. default:
  207. return FileCheckErrorDiagnostic::get(
  208. SM, OpLoc, Twine("unsupported operation '") + Twine(Operator) + "'");
  209. }
  210. // Parse right operand.
  211. Expr = Expr.ltrim(SpaceChars);
  212. if (Expr.empty())
  213. return FileCheckErrorDiagnostic::get(SM, Expr,
  214. "missing operand in expression");
  215. // The second operand in a legacy @LINE expression is always a literal.
  216. AllowedOperand AO =
  217. IsLegacyLineExpr ? AllowedOperand::Literal : AllowedOperand::Any;
  218. Expected<std::unique_ptr<FileCheckExpressionAST>> RightOpResult =
  219. parseNumericOperand(Expr, AO, LineNumber, Context, SM);
  220. if (!RightOpResult)
  221. return RightOpResult;
  222. Expr = Expr.ltrim(SpaceChars);
  223. return std::make_unique<FileCheckASTBinop>(EvalBinop, std::move(LeftOp),
  224. std::move(*RightOpResult));
  225. }
  226. Expected<std::unique_ptr<FileCheckExpressionAST>>
  227. FileCheckPattern::parseNumericSubstitutionBlock(
  228. StringRef Expr,
  229. Optional<FileCheckNumericVariable *> &DefinedNumericVariable,
  230. bool IsLegacyLineExpr, Optional<size_t> LineNumber,
  231. FileCheckPatternContext *Context, const SourceMgr &SM) {
  232. std::unique_ptr<FileCheckExpressionAST> ExpressionAST = nullptr;
  233. StringRef DefExpr = StringRef();
  234. DefinedNumericVariable = None;
  235. // Save variable definition expression if any.
  236. size_t DefEnd = Expr.find(':');
  237. if (DefEnd != StringRef::npos) {
  238. DefExpr = Expr.substr(0, DefEnd);
  239. Expr = Expr.substr(DefEnd + 1);
  240. }
  241. // Parse the expression itself.
  242. Expr = Expr.ltrim(SpaceChars);
  243. if (!Expr.empty()) {
  244. // The first operand in a legacy @LINE expression is always the @LINE
  245. // pseudo variable.
  246. AllowedOperand AO =
  247. IsLegacyLineExpr ? AllowedOperand::LineVar : AllowedOperand::Any;
  248. Expected<std::unique_ptr<FileCheckExpressionAST>> ParseResult =
  249. parseNumericOperand(Expr, AO, LineNumber, Context, SM);
  250. while (ParseResult && !Expr.empty()) {
  251. ParseResult = parseBinop(Expr, std::move(*ParseResult), IsLegacyLineExpr,
  252. LineNumber, Context, SM);
  253. // Legacy @LINE expressions only allow 2 operands.
  254. if (ParseResult && IsLegacyLineExpr && !Expr.empty())
  255. return FileCheckErrorDiagnostic::get(
  256. SM, Expr,
  257. "unexpected characters at end of expression '" + Expr + "'");
  258. }
  259. if (!ParseResult)
  260. return ParseResult;
  261. ExpressionAST = std::move(*ParseResult);
  262. }
  263. // Parse the numeric variable definition.
  264. if (DefEnd != StringRef::npos) {
  265. DefExpr = DefExpr.ltrim(SpaceChars);
  266. Expected<FileCheckNumericVariable *> ParseResult =
  267. parseNumericVariableDefinition(DefExpr, Context, LineNumber, SM);
  268. if (!ParseResult)
  269. return ParseResult.takeError();
  270. DefinedNumericVariable = *ParseResult;
  271. }
  272. return std::move(ExpressionAST);
  273. }
  274. bool FileCheckPattern::parsePattern(StringRef PatternStr, StringRef Prefix,
  275. SourceMgr &SM,
  276. const FileCheckRequest &Req) {
  277. bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
  278. PatternLoc = SMLoc::getFromPointer(PatternStr.data());
  279. if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
  280. // Ignore trailing whitespace.
  281. while (!PatternStr.empty() &&
  282. (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
  283. PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
  284. // Check that there is something on the line.
  285. if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
  286. SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
  287. "found empty check string with prefix '" + Prefix + ":'");
  288. return true;
  289. }
  290. if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
  291. SM.PrintMessage(
  292. PatternLoc, SourceMgr::DK_Error,
  293. "found non-empty check string for empty check with prefix '" + Prefix +
  294. ":'");
  295. return true;
  296. }
  297. if (CheckTy == Check::CheckEmpty) {
  298. RegExStr = "(\n$)";
  299. return false;
  300. }
  301. // Check to see if this is a fixed string, or if it has regex pieces.
  302. if (!MatchFullLinesHere &&
  303. (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
  304. PatternStr.find("[[") == StringRef::npos))) {
  305. FixedStr = PatternStr;
  306. return false;
  307. }
  308. if (MatchFullLinesHere) {
  309. RegExStr += '^';
  310. if (!Req.NoCanonicalizeWhiteSpace)
  311. RegExStr += " *";
  312. }
  313. // Paren value #0 is for the fully matched string. Any new parenthesized
  314. // values add from there.
  315. unsigned CurParen = 1;
  316. // Otherwise, there is at least one regex piece. Build up the regex pattern
  317. // by escaping scary characters in fixed strings, building up one big regex.
  318. while (!PatternStr.empty()) {
  319. // RegEx matches.
  320. if (PatternStr.startswith("{{")) {
  321. // This is the start of a regex match. Scan for the }}.
  322. size_t End = PatternStr.find("}}");
  323. if (End == StringRef::npos) {
  324. SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
  325. SourceMgr::DK_Error,
  326. "found start of regex string with no end '}}'");
  327. return true;
  328. }
  329. // Enclose {{}} patterns in parens just like [[]] even though we're not
  330. // capturing the result for any purpose. This is required in case the
  331. // expression contains an alternation like: CHECK: abc{{x|z}}def. We
  332. // want this to turn into: "abc(x|z)def" not "abcx|zdef".
  333. RegExStr += '(';
  334. ++CurParen;
  335. if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
  336. return true;
  337. RegExStr += ')';
  338. PatternStr = PatternStr.substr(End + 2);
  339. continue;
  340. }
  341. // String and numeric substitution blocks. Pattern substitution blocks come
  342. // in two forms: [[foo:.*]] and [[foo]]. The former matches .* (or some
  343. // other regex) and assigns it to the string variable 'foo'. The latter
  344. // substitutes foo's value. Numeric substitution blocks recognize the same
  345. // form as string ones, but start with a '#' sign after the double
  346. // brackets. They also accept a combined form which sets a numeric variable
  347. // to the evaluation of an expression. Both string and numeric variable
  348. // names must satisfy the regular expression "[a-zA-Z_][0-9a-zA-Z_]*" to be
  349. // valid, as this helps catch some common errors.
  350. if (PatternStr.startswith("[[")) {
  351. StringRef UnparsedPatternStr = PatternStr.substr(2);
  352. // Find the closing bracket pair ending the match. End is going to be an
  353. // offset relative to the beginning of the match string.
  354. size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
  355. StringRef MatchStr = UnparsedPatternStr.substr(0, End);
  356. bool IsNumBlock = MatchStr.consume_front("#");
  357. if (End == StringRef::npos) {
  358. SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
  359. SourceMgr::DK_Error,
  360. "Invalid substitution block, no ]] found");
  361. return true;
  362. }
  363. // Strip the substitution block we are parsing. End points to the start
  364. // of the "]]" closing the expression so account for it in computing the
  365. // index of the first unparsed character.
  366. PatternStr = UnparsedPatternStr.substr(End + 2);
  367. bool IsDefinition = false;
  368. bool SubstNeeded = false;
  369. // Whether the substitution block is a legacy use of @LINE with string
  370. // substitution block syntax.
  371. bool IsLegacyLineExpr = false;
  372. StringRef DefName;
  373. StringRef SubstStr;
  374. StringRef MatchRegexp;
  375. size_t SubstInsertIdx = RegExStr.size();
  376. // Parse string variable or legacy @LINE expression.
  377. if (!IsNumBlock) {
  378. size_t VarEndIdx = MatchStr.find(":");
  379. size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
  380. if (SpacePos != StringRef::npos) {
  381. SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
  382. SourceMgr::DK_Error, "unexpected whitespace");
  383. return true;
  384. }
  385. // Get the name (e.g. "foo") and verify it is well formed.
  386. StringRef OrigMatchStr = MatchStr;
  387. Expected<FileCheckPattern::VariableProperties> ParseVarResult =
  388. parseVariable(MatchStr, SM);
  389. if (!ParseVarResult) {
  390. logAllUnhandledErrors(ParseVarResult.takeError(), errs());
  391. return true;
  392. }
  393. StringRef Name = ParseVarResult->Name;
  394. bool IsPseudo = ParseVarResult->IsPseudo;
  395. IsDefinition = (VarEndIdx != StringRef::npos);
  396. SubstNeeded = !IsDefinition;
  397. if (IsDefinition) {
  398. if ((IsPseudo || !MatchStr.consume_front(":"))) {
  399. SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
  400. SourceMgr::DK_Error,
  401. "invalid name in string variable definition");
  402. return true;
  403. }
  404. // Detect collisions between string and numeric variables when the
  405. // former is created later than the latter.
  406. if (Context->GlobalNumericVariableTable.find(Name) !=
  407. Context->GlobalNumericVariableTable.end()) {
  408. SM.PrintMessage(
  409. SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
  410. "numeric variable with name '" + Name + "' already exists");
  411. return true;
  412. }
  413. DefName = Name;
  414. MatchRegexp = MatchStr;
  415. } else {
  416. if (IsPseudo) {
  417. MatchStr = OrigMatchStr;
  418. IsLegacyLineExpr = IsNumBlock = true;
  419. } else
  420. SubstStr = Name;
  421. }
  422. }
  423. // Parse numeric substitution block.
  424. std::unique_ptr<FileCheckExpressionAST> ExpressionAST;
  425. Optional<FileCheckNumericVariable *> DefinedNumericVariable;
  426. if (IsNumBlock) {
  427. Expected<std::unique_ptr<FileCheckExpressionAST>> ParseResult =
  428. parseNumericSubstitutionBlock(MatchStr, DefinedNumericVariable,
  429. IsLegacyLineExpr, LineNumber, Context,
  430. SM);
  431. if (!ParseResult) {
  432. logAllUnhandledErrors(ParseResult.takeError(), errs());
  433. return true;
  434. }
  435. ExpressionAST = std::move(*ParseResult);
  436. SubstNeeded = ExpressionAST != nullptr;
  437. if (DefinedNumericVariable) {
  438. IsDefinition = true;
  439. DefName = (*DefinedNumericVariable)->getName();
  440. }
  441. if (SubstNeeded)
  442. SubstStr = MatchStr;
  443. else
  444. MatchRegexp = "[0-9]+";
  445. }
  446. // Handle variable definition: [[<def>:(...)]] and [[#(...)<def>:(...)]].
  447. if (IsDefinition) {
  448. RegExStr += '(';
  449. ++SubstInsertIdx;
  450. if (IsNumBlock) {
  451. FileCheckNumericVariableMatch NumericVariableDefinition = {
  452. *DefinedNumericVariable, CurParen};
  453. NumericVariableDefs[DefName] = NumericVariableDefinition;
  454. // This store is done here rather than in match() to allow
  455. // parseNumericVariableUse() to get the pointer to the class instance
  456. // of the right variable definition corresponding to a given numeric
  457. // variable use.
  458. Context->GlobalNumericVariableTable[DefName] =
  459. *DefinedNumericVariable;
  460. } else {
  461. VariableDefs[DefName] = CurParen;
  462. // Mark string variable as defined to detect collisions between
  463. // string and numeric variables in parseNumericVariableUse() and
  464. // defineCmdlineVariables() when the latter is created later than the
  465. // former. We cannot reuse GlobalVariableTable for this by populating
  466. // it with an empty string since we would then lose the ability to
  467. // detect the use of an undefined variable in match().
  468. Context->DefinedVariableTable[DefName] = true;
  469. }
  470. ++CurParen;
  471. }
  472. if (!MatchRegexp.empty() && AddRegExToRegEx(MatchRegexp, CurParen, SM))
  473. return true;
  474. if (IsDefinition)
  475. RegExStr += ')';
  476. // Handle substitutions: [[foo]] and [[#<foo expr>]].
  477. if (SubstNeeded) {
  478. // Handle substitution of string variables that were defined earlier on
  479. // the same line by emitting a backreference. Expressions do not
  480. // support substituting a numeric variable defined on the same line.
  481. if (!IsNumBlock && VariableDefs.find(SubstStr) != VariableDefs.end()) {
  482. unsigned CaptureParenGroup = VariableDefs[SubstStr];
  483. if (CaptureParenGroup < 1 || CaptureParenGroup > 9) {
  484. SM.PrintMessage(SMLoc::getFromPointer(SubstStr.data()),
  485. SourceMgr::DK_Error,
  486. "Can't back-reference more than 9 variables");
  487. return true;
  488. }
  489. AddBackrefToRegEx(CaptureParenGroup);
  490. } else {
  491. // Handle substitution of string variables ([[<var>]]) defined in
  492. // previous CHECK patterns, and substitution of expressions.
  493. FileCheckSubstitution *Substitution =
  494. IsNumBlock
  495. ? Context->makeNumericSubstitution(
  496. SubstStr, std::move(ExpressionAST), SubstInsertIdx)
  497. : Context->makeStringSubstitution(SubstStr, SubstInsertIdx);
  498. Substitutions.push_back(Substitution);
  499. }
  500. }
  501. }
  502. // Handle fixed string matches.
  503. // Find the end, which is the start of the next regex.
  504. size_t FixedMatchEnd = PatternStr.find("{{");
  505. FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
  506. RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
  507. PatternStr = PatternStr.substr(FixedMatchEnd);
  508. }
  509. if (MatchFullLinesHere) {
  510. if (!Req.NoCanonicalizeWhiteSpace)
  511. RegExStr += " *";
  512. RegExStr += '$';
  513. }
  514. return false;
  515. }
  516. bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
  517. Regex R(RS);
  518. std::string Error;
  519. if (!R.isValid(Error)) {
  520. SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
  521. "invalid regex: " + Error);
  522. return true;
  523. }
  524. RegExStr += RS.str();
  525. CurParen += R.getNumMatches();
  526. return false;
  527. }
  528. void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
  529. assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
  530. std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
  531. RegExStr += Backref;
  532. }
  533. Expected<size_t> FileCheckPattern::match(StringRef Buffer, size_t &MatchLen,
  534. const SourceMgr &SM) const {
  535. // If this is the EOF pattern, match it immediately.
  536. if (CheckTy == Check::CheckEOF) {
  537. MatchLen = 0;
  538. return Buffer.size();
  539. }
  540. // If this is a fixed string pattern, just match it now.
  541. if (!FixedStr.empty()) {
  542. MatchLen = FixedStr.size();
  543. size_t Pos = Buffer.find(FixedStr);
  544. if (Pos == StringRef::npos)
  545. return make_error<FileCheckNotFoundError>();
  546. return Pos;
  547. }
  548. // Regex match.
  549. // If there are substitutions, we need to create a temporary string with the
  550. // actual value.
  551. StringRef RegExToMatch = RegExStr;
  552. std::string TmpStr;
  553. if (!Substitutions.empty()) {
  554. TmpStr = RegExStr;
  555. if (LineNumber)
  556. Context->LineVariable->setValue(*LineNumber);
  557. size_t InsertOffset = 0;
  558. // Substitute all string variables and expressions whose values are only
  559. // now known. Use of string variables defined on the same line are handled
  560. // by back-references.
  561. for (const auto &Substitution : Substitutions) {
  562. // Substitute and check for failure (e.g. use of undefined variable).
  563. Expected<std::string> Value = Substitution->getResult();
  564. if (!Value)
  565. return Value.takeError();
  566. // Plop it into the regex at the adjusted offset.
  567. TmpStr.insert(TmpStr.begin() + Substitution->getIndex() + InsertOffset,
  568. Value->begin(), Value->end());
  569. InsertOffset += Value->size();
  570. }
  571. // Match the newly constructed regex.
  572. RegExToMatch = TmpStr;
  573. }
  574. SmallVector<StringRef, 4> MatchInfo;
  575. if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
  576. return make_error<FileCheckNotFoundError>();
  577. // Successful regex match.
  578. assert(!MatchInfo.empty() && "Didn't get any match");
  579. StringRef FullMatch = MatchInfo[0];
  580. // If this defines any string variables, remember their values.
  581. for (const auto &VariableDef : VariableDefs) {
  582. assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
  583. Context->GlobalVariableTable[VariableDef.first] =
  584. MatchInfo[VariableDef.second];
  585. }
  586. // If this defines any numeric variables, remember their values.
  587. for (const auto &NumericVariableDef : NumericVariableDefs) {
  588. const FileCheckNumericVariableMatch &NumericVariableMatch =
  589. NumericVariableDef.getValue();
  590. unsigned CaptureParenGroup = NumericVariableMatch.CaptureParenGroup;
  591. assert(CaptureParenGroup < MatchInfo.size() && "Internal paren error");
  592. FileCheckNumericVariable *DefinedNumericVariable =
  593. NumericVariableMatch.DefinedNumericVariable;
  594. StringRef MatchedValue = MatchInfo[CaptureParenGroup];
  595. uint64_t Val;
  596. if (MatchedValue.getAsInteger(10, Val))
  597. return FileCheckErrorDiagnostic::get(SM, MatchedValue,
  598. "Unable to represent numeric value");
  599. DefinedNumericVariable->setValue(Val);
  600. }
  601. // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
  602. // the required preceding newline, which is consumed by the pattern in the
  603. // case of CHECK-EMPTY but not CHECK-NEXT.
  604. size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
  605. MatchLen = FullMatch.size() - MatchStartSkip;
  606. return FullMatch.data() - Buffer.data() + MatchStartSkip;
  607. }
  608. unsigned FileCheckPattern::computeMatchDistance(StringRef Buffer) const {
  609. // Just compute the number of matching characters. For regular expressions, we
  610. // just compare against the regex itself and hope for the best.
  611. //
  612. // FIXME: One easy improvement here is have the regex lib generate a single
  613. // example regular expression which matches, and use that as the example
  614. // string.
  615. StringRef ExampleString(FixedStr);
  616. if (ExampleString.empty())
  617. ExampleString = RegExStr;
  618. // Only compare up to the first line in the buffer, or the string size.
  619. StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
  620. BufferPrefix = BufferPrefix.split('\n').first;
  621. return BufferPrefix.edit_distance(ExampleString);
  622. }
  623. void FileCheckPattern::printSubstitutions(const SourceMgr &SM, StringRef Buffer,
  624. SMRange MatchRange) const {
  625. // Print what we know about substitutions.
  626. if (!Substitutions.empty()) {
  627. for (const auto &Substitution : Substitutions) {
  628. SmallString<256> Msg;
  629. raw_svector_ostream OS(Msg);
  630. Expected<std::string> MatchedValue = Substitution->getResult();
  631. // Substitution failed or is not known at match time, print the undefined
  632. // variables it uses.
  633. if (!MatchedValue) {
  634. bool UndefSeen = false;
  635. handleAllErrors(MatchedValue.takeError(),
  636. [](const FileCheckNotFoundError &E) {},
  637. // Handled in PrintNoMatch().
  638. [](const FileCheckErrorDiagnostic &E) {},
  639. [&](const FileCheckUndefVarError &E) {
  640. if (!UndefSeen) {
  641. OS << "uses undefined variable(s):";
  642. UndefSeen = true;
  643. }
  644. OS << " ";
  645. E.log(OS);
  646. });
  647. } else {
  648. // Substitution succeeded. Print substituted value.
  649. OS << "with \"";
  650. OS.write_escaped(Substitution->getFromString()) << "\" equal to \"";
  651. OS.write_escaped(*MatchedValue) << "\"";
  652. }
  653. if (MatchRange.isValid())
  654. SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
  655. {MatchRange});
  656. else
  657. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
  658. SourceMgr::DK_Note, OS.str());
  659. }
  660. }
  661. }
  662. static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
  663. const SourceMgr &SM, SMLoc Loc,
  664. Check::FileCheckType CheckTy,
  665. StringRef Buffer, size_t Pos, size_t Len,
  666. std::vector<FileCheckDiag> *Diags,
  667. bool AdjustPrevDiag = false) {
  668. SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
  669. SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
  670. SMRange Range(Start, End);
  671. if (Diags) {
  672. if (AdjustPrevDiag)
  673. Diags->rbegin()->MatchTy = MatchTy;
  674. else
  675. Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
  676. }
  677. return Range;
  678. }
  679. void FileCheckPattern::printFuzzyMatch(
  680. const SourceMgr &SM, StringRef Buffer,
  681. std::vector<FileCheckDiag> *Diags) const {
  682. // Attempt to find the closest/best fuzzy match. Usually an error happens
  683. // because some string in the output didn't exactly match. In these cases, we
  684. // would like to show the user a best guess at what "should have" matched, to
  685. // save them having to actually check the input manually.
  686. size_t NumLinesForward = 0;
  687. size_t Best = StringRef::npos;
  688. double BestQuality = 0;
  689. // Use an arbitrary 4k limit on how far we will search.
  690. for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
  691. if (Buffer[i] == '\n')
  692. ++NumLinesForward;
  693. // Patterns have leading whitespace stripped, so skip whitespace when
  694. // looking for something which looks like a pattern.
  695. if (Buffer[i] == ' ' || Buffer[i] == '\t')
  696. continue;
  697. // Compute the "quality" of this match as an arbitrary combination of the
  698. // match distance and the number of lines skipped to get to this match.
  699. unsigned Distance = computeMatchDistance(Buffer.substr(i));
  700. double Quality = Distance + (NumLinesForward / 100.);
  701. if (Quality < BestQuality || Best == StringRef::npos) {
  702. Best = i;
  703. BestQuality = Quality;
  704. }
  705. }
  706. // Print the "possible intended match here" line if we found something
  707. // reasonable and not equal to what we showed in the "scanning from here"
  708. // line.
  709. if (Best && Best != StringRef::npos && BestQuality < 50) {
  710. SMRange MatchRange =
  711. ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
  712. getCheckTy(), Buffer, Best, 0, Diags);
  713. SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
  714. "possible intended match here");
  715. // FIXME: If we wanted to be really friendly we would show why the match
  716. // failed, as it can be hard to spot simple one character differences.
  717. }
  718. }
  719. Expected<StringRef>
  720. FileCheckPatternContext::getPatternVarValue(StringRef VarName) {
  721. auto VarIter = GlobalVariableTable.find(VarName);
  722. if (VarIter == GlobalVariableTable.end())
  723. return make_error<FileCheckUndefVarError>(VarName);
  724. return VarIter->second;
  725. }
  726. template <class... Types>
  727. FileCheckNumericVariable *
  728. FileCheckPatternContext::makeNumericVariable(Types... args) {
  729. NumericVariables.push_back(
  730. std::make_unique<FileCheckNumericVariable>(args...));
  731. return NumericVariables.back().get();
  732. }
  733. FileCheckSubstitution *
  734. FileCheckPatternContext::makeStringSubstitution(StringRef VarName,
  735. size_t InsertIdx) {
  736. Substitutions.push_back(
  737. std::make_unique<FileCheckStringSubstitution>(this, VarName, InsertIdx));
  738. return Substitutions.back().get();
  739. }
  740. FileCheckSubstitution *FileCheckPatternContext::makeNumericSubstitution(
  741. StringRef ExpressionStr,
  742. std::unique_ptr<FileCheckExpressionAST> ExpressionAST, size_t InsertIdx) {
  743. Substitutions.push_back(std::make_unique<FileCheckNumericSubstitution>(
  744. this, ExpressionStr, std::move(ExpressionAST), InsertIdx));
  745. return Substitutions.back().get();
  746. }
  747. size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
  748. // Offset keeps track of the current offset within the input Str
  749. size_t Offset = 0;
  750. // [...] Nesting depth
  751. size_t BracketDepth = 0;
  752. while (!Str.empty()) {
  753. if (Str.startswith("]]") && BracketDepth == 0)
  754. return Offset;
  755. if (Str[0] == '\\') {
  756. // Backslash escapes the next char within regexes, so skip them both.
  757. Str = Str.substr(2);
  758. Offset += 2;
  759. } else {
  760. switch (Str[0]) {
  761. default:
  762. break;
  763. case '[':
  764. BracketDepth++;
  765. break;
  766. case ']':
  767. if (BracketDepth == 0) {
  768. SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
  769. SourceMgr::DK_Error,
  770. "missing closing \"]\" for regex variable");
  771. exit(1);
  772. }
  773. BracketDepth--;
  774. break;
  775. }
  776. Str = Str.substr(1);
  777. Offset++;
  778. }
  779. }
  780. return StringRef::npos;
  781. }
  782. StringRef FileCheck::CanonicalizeFile(MemoryBuffer &MB,
  783. SmallVectorImpl<char> &OutputBuffer) {
  784. OutputBuffer.reserve(MB.getBufferSize());
  785. for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
  786. Ptr != End; ++Ptr) {
  787. // Eliminate trailing dosish \r.
  788. if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
  789. continue;
  790. }
  791. // If current char is not a horizontal whitespace or if horizontal
  792. // whitespace canonicalization is disabled, dump it to output as is.
  793. if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
  794. OutputBuffer.push_back(*Ptr);
  795. continue;
  796. }
  797. // Otherwise, add one space and advance over neighboring space.
  798. OutputBuffer.push_back(' ');
  799. while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
  800. ++Ptr;
  801. }
  802. // Add a null byte and then return all but that byte.
  803. OutputBuffer.push_back('\0');
  804. return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
  805. }
  806. FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
  807. const Check::FileCheckType &CheckTy,
  808. SMLoc CheckLoc, MatchType MatchTy,
  809. SMRange InputRange)
  810. : CheckTy(CheckTy), MatchTy(MatchTy) {
  811. auto Start = SM.getLineAndColumn(InputRange.Start);
  812. auto End = SM.getLineAndColumn(InputRange.End);
  813. InputStartLine = Start.first;
  814. InputStartCol = Start.second;
  815. InputEndLine = End.first;
  816. InputEndCol = End.second;
  817. Start = SM.getLineAndColumn(CheckLoc);
  818. CheckLine = Start.first;
  819. CheckCol = Start.second;
  820. }
  821. static bool IsPartOfWord(char c) {
  822. return (isalnum(c) || c == '-' || c == '_');
  823. }
  824. Check::FileCheckType &Check::FileCheckType::setCount(int C) {
  825. assert(Count > 0 && "zero and negative counts are not supported");
  826. assert((C == 1 || Kind == CheckPlain) &&
  827. "count supported only for plain CHECK directives");
  828. Count = C;
  829. return *this;
  830. }
  831. std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
  832. switch (Kind) {
  833. case Check::CheckNone:
  834. return "invalid";
  835. case Check::CheckPlain:
  836. if (Count > 1)
  837. return Prefix.str() + "-COUNT";
  838. return Prefix;
  839. case Check::CheckNext:
  840. return Prefix.str() + "-NEXT";
  841. case Check::CheckSame:
  842. return Prefix.str() + "-SAME";
  843. case Check::CheckNot:
  844. return Prefix.str() + "-NOT";
  845. case Check::CheckDAG:
  846. return Prefix.str() + "-DAG";
  847. case Check::CheckLabel:
  848. return Prefix.str() + "-LABEL";
  849. case Check::CheckEmpty:
  850. return Prefix.str() + "-EMPTY";
  851. case Check::CheckEOF:
  852. return "implicit EOF";
  853. case Check::CheckBadNot:
  854. return "bad NOT";
  855. case Check::CheckBadCount:
  856. return "bad COUNT";
  857. }
  858. llvm_unreachable("unknown FileCheckType");
  859. }
  860. static std::pair<Check::FileCheckType, StringRef>
  861. FindCheckType(StringRef Buffer, StringRef Prefix) {
  862. if (Buffer.size() <= Prefix.size())
  863. return {Check::CheckNone, StringRef()};
  864. char NextChar = Buffer[Prefix.size()];
  865. StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
  866. // Verify that the : is present after the prefix.
  867. if (NextChar == ':')
  868. return {Check::CheckPlain, Rest};
  869. if (NextChar != '-')
  870. return {Check::CheckNone, StringRef()};
  871. if (Rest.consume_front("COUNT-")) {
  872. int64_t Count;
  873. if (Rest.consumeInteger(10, Count))
  874. // Error happened in parsing integer.
  875. return {Check::CheckBadCount, Rest};
  876. if (Count <= 0 || Count > INT32_MAX)
  877. return {Check::CheckBadCount, Rest};
  878. if (!Rest.consume_front(":"))
  879. return {Check::CheckBadCount, Rest};
  880. return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
  881. }
  882. if (Rest.consume_front("NEXT:"))
  883. return {Check::CheckNext, Rest};
  884. if (Rest.consume_front("SAME:"))
  885. return {Check::CheckSame, Rest};
  886. if (Rest.consume_front("NOT:"))
  887. return {Check::CheckNot, Rest};
  888. if (Rest.consume_front("DAG:"))
  889. return {Check::CheckDAG, Rest};
  890. if (Rest.consume_front("LABEL:"))
  891. return {Check::CheckLabel, Rest};
  892. if (Rest.consume_front("EMPTY:"))
  893. return {Check::CheckEmpty, Rest};
  894. // You can't combine -NOT with another suffix.
  895. if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
  896. Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
  897. Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
  898. Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
  899. return {Check::CheckBadNot, Rest};
  900. return {Check::CheckNone, Rest};
  901. }
  902. // From the given position, find the next character after the word.
  903. static size_t SkipWord(StringRef Str, size_t Loc) {
  904. while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
  905. ++Loc;
  906. return Loc;
  907. }
  908. /// Searches the buffer for the first prefix in the prefix regular expression.
  909. ///
  910. /// This searches the buffer using the provided regular expression, however it
  911. /// enforces constraints beyond that:
  912. /// 1) The found prefix must not be a suffix of something that looks like
  913. /// a valid prefix.
  914. /// 2) The found prefix must be followed by a valid check type suffix using \c
  915. /// FindCheckType above.
  916. ///
  917. /// \returns a pair of StringRefs into the Buffer, which combines:
  918. /// - the first match of the regular expression to satisfy these two is
  919. /// returned,
  920. /// otherwise an empty StringRef is returned to indicate failure.
  921. /// - buffer rewound to the location right after parsed suffix, for parsing
  922. /// to continue from
  923. ///
  924. /// If this routine returns a valid prefix, it will also shrink \p Buffer to
  925. /// start at the beginning of the returned prefix, increment \p LineNumber for
  926. /// each new line consumed from \p Buffer, and set \p CheckTy to the type of
  927. /// check found by examining the suffix.
  928. ///
  929. /// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
  930. /// is unspecified.
  931. static std::pair<StringRef, StringRef>
  932. FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer,
  933. unsigned &LineNumber, Check::FileCheckType &CheckTy) {
  934. SmallVector<StringRef, 2> Matches;
  935. while (!Buffer.empty()) {
  936. // Find the first (longest) match using the RE.
  937. if (!PrefixRE.match(Buffer, &Matches))
  938. // No match at all, bail.
  939. return {StringRef(), StringRef()};
  940. StringRef Prefix = Matches[0];
  941. Matches.clear();
  942. assert(Prefix.data() >= Buffer.data() &&
  943. Prefix.data() < Buffer.data() + Buffer.size() &&
  944. "Prefix doesn't start inside of buffer!");
  945. size_t Loc = Prefix.data() - Buffer.data();
  946. StringRef Skipped = Buffer.substr(0, Loc);
  947. Buffer = Buffer.drop_front(Loc);
  948. LineNumber += Skipped.count('\n');
  949. // Check that the matched prefix isn't a suffix of some other check-like
  950. // word.
  951. // FIXME: This is a very ad-hoc check. it would be better handled in some
  952. // other way. Among other things it seems hard to distinguish between
  953. // intentional and unintentional uses of this feature.
  954. if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
  955. // Now extract the type.
  956. StringRef AfterSuffix;
  957. std::tie(CheckTy, AfterSuffix) = FindCheckType(Buffer, Prefix);
  958. // If we've found a valid check type for this prefix, we're done.
  959. if (CheckTy != Check::CheckNone)
  960. return {Prefix, AfterSuffix};
  961. }
  962. // If we didn't successfully find a prefix, we need to skip this invalid
  963. // prefix and continue scanning. We directly skip the prefix that was
  964. // matched and any additional parts of that check-like word.
  965. Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
  966. }
  967. // We ran out of buffer while skipping partial matches so give up.
  968. return {StringRef(), StringRef()};
  969. }
  970. void FileCheckPatternContext::createLineVariable() {
  971. assert(!LineVariable && "@LINE pseudo numeric variable already created");
  972. StringRef LineName = "@LINE";
  973. LineVariable = makeNumericVariable(LineName);
  974. GlobalNumericVariableTable[LineName] = LineVariable;
  975. }
  976. bool FileCheck::ReadCheckFile(SourceMgr &SM, StringRef Buffer, Regex &PrefixRE,
  977. std::vector<FileCheckString> &CheckStrings) {
  978. Error DefineError =
  979. PatternContext.defineCmdlineVariables(Req.GlobalDefines, SM);
  980. if (DefineError) {
  981. logAllUnhandledErrors(std::move(DefineError), errs());
  982. return true;
  983. }
  984. PatternContext.createLineVariable();
  985. std::vector<FileCheckPattern> ImplicitNegativeChecks;
  986. for (const auto &PatternString : Req.ImplicitCheckNot) {
  987. // Create a buffer with fake command line content in order to display the
  988. // command line option responsible for the specific implicit CHECK-NOT.
  989. std::string Prefix = "-implicit-check-not='";
  990. std::string Suffix = "'";
  991. std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
  992. Prefix + PatternString + Suffix, "command line");
  993. StringRef PatternInBuffer =
  994. CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
  995. SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
  996. ImplicitNegativeChecks.push_back(
  997. FileCheckPattern(Check::CheckNot, &PatternContext));
  998. ImplicitNegativeChecks.back().parsePattern(PatternInBuffer,
  999. "IMPLICIT-CHECK", SM, Req);
  1000. }
  1001. std::vector<FileCheckPattern> DagNotMatches = ImplicitNegativeChecks;
  1002. // LineNumber keeps track of the line on which CheckPrefix instances are
  1003. // found.
  1004. unsigned LineNumber = 1;
  1005. while (1) {
  1006. Check::FileCheckType CheckTy;
  1007. // See if a prefix occurs in the memory buffer.
  1008. StringRef UsedPrefix;
  1009. StringRef AfterSuffix;
  1010. std::tie(UsedPrefix, AfterSuffix) =
  1011. FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, CheckTy);
  1012. if (UsedPrefix.empty())
  1013. break;
  1014. assert(UsedPrefix.data() == Buffer.data() &&
  1015. "Failed to move Buffer's start forward, or pointed prefix outside "
  1016. "of the buffer!");
  1017. assert(AfterSuffix.data() >= Buffer.data() &&
  1018. AfterSuffix.data() < Buffer.data() + Buffer.size() &&
  1019. "Parsing after suffix doesn't start inside of buffer!");
  1020. // Location to use for error messages.
  1021. const char *UsedPrefixStart = UsedPrefix.data();
  1022. // Skip the buffer to the end of parsed suffix (or just prefix, if no good
  1023. // suffix was processed).
  1024. Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
  1025. : AfterSuffix;
  1026. // Complain about useful-looking but unsupported suffixes.
  1027. if (CheckTy == Check::CheckBadNot) {
  1028. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
  1029. "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
  1030. return true;
  1031. }
  1032. // Complain about invalid count specification.
  1033. if (CheckTy == Check::CheckBadCount) {
  1034. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
  1035. "invalid count in -COUNT specification on prefix '" +
  1036. UsedPrefix + "'");
  1037. return true;
  1038. }
  1039. // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
  1040. // leading whitespace.
  1041. if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
  1042. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
  1043. // Scan ahead to the end of line.
  1044. size_t EOL = Buffer.find_first_of("\n\r");
  1045. // Remember the location of the start of the pattern, for diagnostics.
  1046. SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
  1047. // Parse the pattern.
  1048. FileCheckPattern P(CheckTy, &PatternContext, LineNumber);
  1049. if (P.parsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, Req))
  1050. return true;
  1051. // Verify that CHECK-LABEL lines do not define or use variables
  1052. if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
  1053. SM.PrintMessage(
  1054. SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
  1055. "found '" + UsedPrefix + "-LABEL:'"
  1056. " with variable definition or use");
  1057. return true;
  1058. }
  1059. Buffer = Buffer.substr(EOL);
  1060. // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
  1061. if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
  1062. CheckTy == Check::CheckEmpty) &&
  1063. CheckStrings.empty()) {
  1064. StringRef Type = CheckTy == Check::CheckNext
  1065. ? "NEXT"
  1066. : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
  1067. SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
  1068. SourceMgr::DK_Error,
  1069. "found '" + UsedPrefix + "-" + Type +
  1070. "' without previous '" + UsedPrefix + ": line");
  1071. return true;
  1072. }
  1073. // Handle CHECK-DAG/-NOT.
  1074. if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
  1075. DagNotMatches.push_back(P);
  1076. continue;
  1077. }
  1078. // Okay, add the string we captured to the output vector and move on.
  1079. CheckStrings.emplace_back(P, UsedPrefix, PatternLoc);
  1080. std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
  1081. DagNotMatches = ImplicitNegativeChecks;
  1082. }
  1083. // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
  1084. // prefix as a filler for the error message.
  1085. if (!DagNotMatches.empty()) {
  1086. CheckStrings.emplace_back(
  1087. FileCheckPattern(Check::CheckEOF, &PatternContext, LineNumber + 1),
  1088. *Req.CheckPrefixes.begin(), SMLoc::getFromPointer(Buffer.data()));
  1089. std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
  1090. }
  1091. if (CheckStrings.empty()) {
  1092. errs() << "error: no check strings found with prefix"
  1093. << (Req.CheckPrefixes.size() > 1 ? "es " : " ");
  1094. auto I = Req.CheckPrefixes.begin();
  1095. auto E = Req.CheckPrefixes.end();
  1096. if (I != E) {
  1097. errs() << "\'" << *I << ":'";
  1098. ++I;
  1099. }
  1100. for (; I != E; ++I)
  1101. errs() << ", \'" << *I << ":'";
  1102. errs() << '\n';
  1103. return true;
  1104. }
  1105. return false;
  1106. }
  1107. static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
  1108. StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat,
  1109. int MatchedCount, StringRef Buffer, size_t MatchPos,
  1110. size_t MatchLen, const FileCheckRequest &Req,
  1111. std::vector<FileCheckDiag> *Diags) {
  1112. bool PrintDiag = true;
  1113. if (ExpectedMatch) {
  1114. if (!Req.Verbose)
  1115. return;
  1116. if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
  1117. return;
  1118. // Due to their verbosity, we don't print verbose diagnostics here if we're
  1119. // gathering them for a different rendering, but we always print other
  1120. // diagnostics.
  1121. PrintDiag = !Diags;
  1122. }
  1123. SMRange MatchRange = ProcessMatchResult(
  1124. ExpectedMatch ? FileCheckDiag::MatchFoundAndExpected
  1125. : FileCheckDiag::MatchFoundButExcluded,
  1126. SM, Loc, Pat.getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
  1127. if (!PrintDiag)
  1128. return;
  1129. std::string Message = formatv("{0}: {1} string found in input",
  1130. Pat.getCheckTy().getDescription(Prefix),
  1131. (ExpectedMatch ? "expected" : "excluded"))
  1132. .str();
  1133. if (Pat.getCount() > 1)
  1134. Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
  1135. SM.PrintMessage(
  1136. Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
  1137. SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
  1138. {MatchRange});
  1139. Pat.printSubstitutions(SM, Buffer, MatchRange);
  1140. }
  1141. static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
  1142. const FileCheckString &CheckStr, int MatchedCount,
  1143. StringRef Buffer, size_t MatchPos, size_t MatchLen,
  1144. FileCheckRequest &Req,
  1145. std::vector<FileCheckDiag> *Diags) {
  1146. PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
  1147. MatchedCount, Buffer, MatchPos, MatchLen, Req, Diags);
  1148. }
  1149. static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
  1150. StringRef Prefix, SMLoc Loc,
  1151. const FileCheckPattern &Pat, int MatchedCount,
  1152. StringRef Buffer, bool VerboseVerbose,
  1153. std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
  1154. assert(MatchErrors && "Called on successful match");
  1155. bool PrintDiag = true;
  1156. if (!ExpectedMatch) {
  1157. if (!VerboseVerbose) {
  1158. consumeError(std::move(MatchErrors));
  1159. return;
  1160. }
  1161. // Due to their verbosity, we don't print verbose diagnostics here if we're
  1162. // gathering them for a different rendering, but we always print other
  1163. // diagnostics.
  1164. PrintDiag = !Diags;
  1165. }
  1166. // If the current position is at the end of a line, advance to the start of
  1167. // the next line.
  1168. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
  1169. SMRange SearchRange = ProcessMatchResult(
  1170. ExpectedMatch ? FileCheckDiag::MatchNoneButExpected
  1171. : FileCheckDiag::MatchNoneAndExcluded,
  1172. SM, Loc, Pat.getCheckTy(), Buffer, 0, Buffer.size(), Diags);
  1173. if (!PrintDiag) {
  1174. consumeError(std::move(MatchErrors));
  1175. return;
  1176. }
  1177. MatchErrors =
  1178. handleErrors(std::move(MatchErrors),
  1179. [](const FileCheckErrorDiagnostic &E) { E.log(errs()); });
  1180. // No problem matching the string per se.
  1181. if (!MatchErrors)
  1182. return;
  1183. consumeError(std::move(MatchErrors));
  1184. // Print "not found" diagnostic.
  1185. std::string Message = formatv("{0}: {1} string not found in input",
  1186. Pat.getCheckTy().getDescription(Prefix),
  1187. (ExpectedMatch ? "expected" : "excluded"))
  1188. .str();
  1189. if (Pat.getCount() > 1)
  1190. Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
  1191. SM.PrintMessage(
  1192. Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
  1193. // Print the "scanning from here" line.
  1194. SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
  1195. // Allow the pattern to print additional information if desired.
  1196. Pat.printSubstitutions(SM, Buffer);
  1197. if (ExpectedMatch)
  1198. Pat.printFuzzyMatch(SM, Buffer, Diags);
  1199. }
  1200. static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
  1201. const FileCheckString &CheckStr, int MatchedCount,
  1202. StringRef Buffer, bool VerboseVerbose,
  1203. std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
  1204. PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
  1205. MatchedCount, Buffer, VerboseVerbose, Diags,
  1206. std::move(MatchErrors));
  1207. }
  1208. /// Counts the number of newlines in the specified range.
  1209. static unsigned CountNumNewlinesBetween(StringRef Range,
  1210. const char *&FirstNewLine) {
  1211. unsigned NumNewLines = 0;
  1212. while (1) {
  1213. // Scan for newline.
  1214. Range = Range.substr(Range.find_first_of("\n\r"));
  1215. if (Range.empty())
  1216. return NumNewLines;
  1217. ++NumNewLines;
  1218. // Handle \n\r and \r\n as a single newline.
  1219. if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
  1220. (Range[0] != Range[1]))
  1221. Range = Range.substr(1);
  1222. Range = Range.substr(1);
  1223. if (NumNewLines == 1)
  1224. FirstNewLine = Range.begin();
  1225. }
  1226. }
  1227. size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
  1228. bool IsLabelScanMode, size_t &MatchLen,
  1229. FileCheckRequest &Req,
  1230. std::vector<FileCheckDiag> *Diags) const {
  1231. size_t LastPos = 0;
  1232. std::vector<const FileCheckPattern *> NotStrings;
  1233. // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
  1234. // bounds; we have not processed variable definitions within the bounded block
  1235. // yet so cannot handle any final CHECK-DAG yet; this is handled when going
  1236. // over the block again (including the last CHECK-LABEL) in normal mode.
  1237. if (!IsLabelScanMode) {
  1238. // Match "dag strings" (with mixed "not strings" if any).
  1239. LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
  1240. if (LastPos == StringRef::npos)
  1241. return StringRef::npos;
  1242. }
  1243. // Match itself from the last position after matching CHECK-DAG.
  1244. size_t LastMatchEnd = LastPos;
  1245. size_t FirstMatchPos = 0;
  1246. // Go match the pattern Count times. Majority of patterns only match with
  1247. // count 1 though.
  1248. assert(Pat.getCount() != 0 && "pattern count can not be zero");
  1249. for (int i = 1; i <= Pat.getCount(); i++) {
  1250. StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
  1251. size_t CurrentMatchLen;
  1252. // get a match at current start point
  1253. Expected<size_t> MatchResult = Pat.match(MatchBuffer, CurrentMatchLen, SM);
  1254. // report
  1255. if (!MatchResult) {
  1256. PrintNoMatch(true, SM, *this, i, MatchBuffer, Req.VerboseVerbose, Diags,
  1257. MatchResult.takeError());
  1258. return StringRef::npos;
  1259. }
  1260. size_t MatchPos = *MatchResult;
  1261. PrintMatch(true, SM, *this, i, MatchBuffer, MatchPos, CurrentMatchLen, Req,
  1262. Diags);
  1263. if (i == 1)
  1264. FirstMatchPos = LastPos + MatchPos;
  1265. // move start point after the match
  1266. LastMatchEnd += MatchPos + CurrentMatchLen;
  1267. }
  1268. // Full match len counts from first match pos.
  1269. MatchLen = LastMatchEnd - FirstMatchPos;
  1270. // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
  1271. // or CHECK-NOT
  1272. if (!IsLabelScanMode) {
  1273. size_t MatchPos = FirstMatchPos - LastPos;
  1274. StringRef MatchBuffer = Buffer.substr(LastPos);
  1275. StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
  1276. // If this check is a "CHECK-NEXT", verify that the previous match was on
  1277. // the previous line (i.e. that there is one newline between them).
  1278. if (CheckNext(SM, SkippedRegion)) {
  1279. ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
  1280. Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
  1281. Diags, Req.Verbose);
  1282. return StringRef::npos;
  1283. }
  1284. // If this check is a "CHECK-SAME", verify that the previous match was on
  1285. // the same line (i.e. that there is no newline between them).
  1286. if (CheckSame(SM, SkippedRegion)) {
  1287. ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
  1288. Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
  1289. Diags, Req.Verbose);
  1290. return StringRef::npos;
  1291. }
  1292. // If this match had "not strings", verify that they don't exist in the
  1293. // skipped region.
  1294. if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
  1295. return StringRef::npos;
  1296. }
  1297. return FirstMatchPos;
  1298. }
  1299. bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
  1300. if (Pat.getCheckTy() != Check::CheckNext &&
  1301. Pat.getCheckTy() != Check::CheckEmpty)
  1302. return false;
  1303. Twine CheckName =
  1304. Prefix +
  1305. Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
  1306. // Count the number of newlines between the previous match and this one.
  1307. const char *FirstNewLine = nullptr;
  1308. unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
  1309. if (NumNewLines == 0) {
  1310. SM.PrintMessage(Loc, SourceMgr::DK_Error,
  1311. CheckName + ": is on the same line as previous match");
  1312. SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
  1313. "'next' match was here");
  1314. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
  1315. "previous match ended here");
  1316. return true;
  1317. }
  1318. if (NumNewLines != 1) {
  1319. SM.PrintMessage(Loc, SourceMgr::DK_Error,
  1320. CheckName +
  1321. ": is not on the line after the previous match");
  1322. SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
  1323. "'next' match was here");
  1324. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
  1325. "previous match ended here");
  1326. SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
  1327. "non-matching line after previous match is here");
  1328. return true;
  1329. }
  1330. return false;
  1331. }
  1332. bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
  1333. if (Pat.getCheckTy() != Check::CheckSame)
  1334. return false;
  1335. // Count the number of newlines between the previous match and this one.
  1336. const char *FirstNewLine = nullptr;
  1337. unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
  1338. if (NumNewLines != 0) {
  1339. SM.PrintMessage(Loc, SourceMgr::DK_Error,
  1340. Prefix +
  1341. "-SAME: is not on the same line as the previous match");
  1342. SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
  1343. "'next' match was here");
  1344. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
  1345. "previous match ended here");
  1346. return true;
  1347. }
  1348. return false;
  1349. }
  1350. bool FileCheckString::CheckNot(
  1351. const SourceMgr &SM, StringRef Buffer,
  1352. const std::vector<const FileCheckPattern *> &NotStrings,
  1353. const FileCheckRequest &Req, std::vector<FileCheckDiag> *Diags) const {
  1354. for (const FileCheckPattern *Pat : NotStrings) {
  1355. assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
  1356. size_t MatchLen = 0;
  1357. Expected<size_t> MatchResult = Pat->match(Buffer, MatchLen, SM);
  1358. if (!MatchResult) {
  1359. PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
  1360. Req.VerboseVerbose, Diags, MatchResult.takeError());
  1361. continue;
  1362. }
  1363. size_t Pos = *MatchResult;
  1364. PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, Pos, MatchLen,
  1365. Req, Diags);
  1366. return true;
  1367. }
  1368. return false;
  1369. }
  1370. size_t
  1371. FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
  1372. std::vector<const FileCheckPattern *> &NotStrings,
  1373. const FileCheckRequest &Req,
  1374. std::vector<FileCheckDiag> *Diags) const {
  1375. if (DagNotStrings.empty())
  1376. return 0;
  1377. // The start of the search range.
  1378. size_t StartPos = 0;
  1379. struct MatchRange {
  1380. size_t Pos;
  1381. size_t End;
  1382. };
  1383. // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
  1384. // ranges are erased from this list once they are no longer in the search
  1385. // range.
  1386. std::list<MatchRange> MatchRanges;
  1387. // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
  1388. // group, so we don't use a range-based for loop here.
  1389. for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
  1390. PatItr != PatEnd; ++PatItr) {
  1391. const FileCheckPattern &Pat = *PatItr;
  1392. assert((Pat.getCheckTy() == Check::CheckDAG ||
  1393. Pat.getCheckTy() == Check::CheckNot) &&
  1394. "Invalid CHECK-DAG or CHECK-NOT!");
  1395. if (Pat.getCheckTy() == Check::CheckNot) {
  1396. NotStrings.push_back(&Pat);
  1397. continue;
  1398. }
  1399. assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
  1400. // CHECK-DAG always matches from the start.
  1401. size_t MatchLen = 0, MatchPos = StartPos;
  1402. // Search for a match that doesn't overlap a previous match in this
  1403. // CHECK-DAG group.
  1404. for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
  1405. StringRef MatchBuffer = Buffer.substr(MatchPos);
  1406. Expected<size_t> MatchResult = Pat.match(MatchBuffer, MatchLen, SM);
  1407. // With a group of CHECK-DAGs, a single mismatching means the match on
  1408. // that group of CHECK-DAGs fails immediately.
  1409. if (!MatchResult) {
  1410. PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
  1411. Req.VerboseVerbose, Diags, MatchResult.takeError());
  1412. return StringRef::npos;
  1413. }
  1414. size_t MatchPosBuf = *MatchResult;
  1415. // Re-calc it as the offset relative to the start of the original string.
  1416. MatchPos += MatchPosBuf;
  1417. if (Req.VerboseVerbose)
  1418. PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
  1419. MatchLen, Req, Diags);
  1420. MatchRange M{MatchPos, MatchPos + MatchLen};
  1421. if (Req.AllowDeprecatedDagOverlap) {
  1422. // We don't need to track all matches in this mode, so we just maintain
  1423. // one match range that encompasses the current CHECK-DAG group's
  1424. // matches.
  1425. if (MatchRanges.empty())
  1426. MatchRanges.insert(MatchRanges.end(), M);
  1427. else {
  1428. auto Block = MatchRanges.begin();
  1429. Block->Pos = std::min(Block->Pos, M.Pos);
  1430. Block->End = std::max(Block->End, M.End);
  1431. }
  1432. break;
  1433. }
  1434. // Iterate previous matches until overlapping match or insertion point.
  1435. bool Overlap = false;
  1436. for (; MI != ME; ++MI) {
  1437. if (M.Pos < MI->End) {
  1438. // !Overlap => New match has no overlap and is before this old match.
  1439. // Overlap => New match overlaps this old match.
  1440. Overlap = MI->Pos < M.End;
  1441. break;
  1442. }
  1443. }
  1444. if (!Overlap) {
  1445. // Insert non-overlapping match into list.
  1446. MatchRanges.insert(MI, M);
  1447. break;
  1448. }
  1449. if (Req.VerboseVerbose) {
  1450. // Due to their verbosity, we don't print verbose diagnostics here if
  1451. // we're gathering them for a different rendering, but we always print
  1452. // other diagnostics.
  1453. if (!Diags) {
  1454. SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
  1455. SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
  1456. SMRange OldRange(OldStart, OldEnd);
  1457. SM.PrintMessage(OldStart, SourceMgr::DK_Note,
  1458. "match discarded, overlaps earlier DAG match here",
  1459. {OldRange});
  1460. } else
  1461. Diags->rbegin()->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
  1462. }
  1463. MatchPos = MI->End;
  1464. }
  1465. if (!Req.VerboseVerbose)
  1466. PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
  1467. MatchLen, Req, Diags);
  1468. // Handle the end of a CHECK-DAG group.
  1469. if (std::next(PatItr) == PatEnd ||
  1470. std::next(PatItr)->getCheckTy() == Check::CheckNot) {
  1471. if (!NotStrings.empty()) {
  1472. // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
  1473. // CHECK-DAG, verify that there are no 'not' strings occurred in that
  1474. // region.
  1475. StringRef SkippedRegion =
  1476. Buffer.slice(StartPos, MatchRanges.begin()->Pos);
  1477. if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
  1478. return StringRef::npos;
  1479. // Clear "not strings".
  1480. NotStrings.clear();
  1481. }
  1482. // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
  1483. // end of this CHECK-DAG group's match range.
  1484. StartPos = MatchRanges.rbegin()->End;
  1485. // Don't waste time checking for (impossible) overlaps before that.
  1486. MatchRanges.clear();
  1487. }
  1488. }
  1489. return StartPos;
  1490. }
  1491. // A check prefix must contain only alphanumeric, hyphens and underscores.
  1492. static bool ValidateCheckPrefix(StringRef CheckPrefix) {
  1493. static const Regex Validator("^[a-zA-Z0-9_-]*$");
  1494. return Validator.match(CheckPrefix);
  1495. }
  1496. bool FileCheck::ValidateCheckPrefixes() {
  1497. StringSet<> PrefixSet;
  1498. for (StringRef Prefix : Req.CheckPrefixes) {
  1499. // Reject empty prefixes.
  1500. if (Prefix == "")
  1501. return false;
  1502. if (!PrefixSet.insert(Prefix).second)
  1503. return false;
  1504. if (!ValidateCheckPrefix(Prefix))
  1505. return false;
  1506. }
  1507. return true;
  1508. }
  1509. Regex FileCheck::buildCheckPrefixRegex() {
  1510. // I don't think there's a way to specify an initial value for cl::list,
  1511. // so if nothing was specified, add the default
  1512. if (Req.CheckPrefixes.empty())
  1513. Req.CheckPrefixes.push_back("CHECK");
  1514. // We already validated the contents of CheckPrefixes so just concatenate
  1515. // them as alternatives.
  1516. SmallString<32> PrefixRegexStr;
  1517. for (StringRef Prefix : Req.CheckPrefixes) {
  1518. if (Prefix != Req.CheckPrefixes.front())
  1519. PrefixRegexStr.push_back('|');
  1520. PrefixRegexStr.append(Prefix);
  1521. }
  1522. return Regex(PrefixRegexStr);
  1523. }
  1524. Error FileCheckPatternContext::defineCmdlineVariables(
  1525. std::vector<std::string> &CmdlineDefines, SourceMgr &SM) {
  1526. assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
  1527. "Overriding defined variable with command-line variable definitions");
  1528. if (CmdlineDefines.empty())
  1529. return Error::success();
  1530. // Create a string representing the vector of command-line definitions. Each
  1531. // definition is on its own line and prefixed with a definition number to
  1532. // clarify which definition a given diagnostic corresponds to.
  1533. unsigned I = 0;
  1534. Error Errs = Error::success();
  1535. std::string CmdlineDefsDiag;
  1536. SmallVector<std::pair<size_t, size_t>, 4> CmdlineDefsIndices;
  1537. for (StringRef CmdlineDef : CmdlineDefines) {
  1538. std::string DefPrefix = ("Global define #" + Twine(++I) + ": ").str();
  1539. size_t EqIdx = CmdlineDef.find('=');
  1540. if (EqIdx == StringRef::npos) {
  1541. CmdlineDefsIndices.push_back(std::make_pair(CmdlineDefsDiag.size(), 0));
  1542. continue;
  1543. }
  1544. // Numeric variable definition.
  1545. if (CmdlineDef[0] == '#') {
  1546. // Append a copy of the command-line definition adapted to use the same
  1547. // format as in the input file to be able to reuse
  1548. // parseNumericSubstitutionBlock.
  1549. CmdlineDefsDiag += (DefPrefix + CmdlineDef + " (parsed as: [[").str();
  1550. std::string SubstitutionStr = CmdlineDef;
  1551. SubstitutionStr[EqIdx] = ':';
  1552. CmdlineDefsIndices.push_back(
  1553. std::make_pair(CmdlineDefsDiag.size(), SubstitutionStr.size()));
  1554. CmdlineDefsDiag += (SubstitutionStr + Twine("]])\n")).str();
  1555. } else {
  1556. CmdlineDefsDiag += DefPrefix;
  1557. CmdlineDefsIndices.push_back(
  1558. std::make_pair(CmdlineDefsDiag.size(), CmdlineDef.size()));
  1559. CmdlineDefsDiag += (CmdlineDef + "\n").str();
  1560. }
  1561. }
  1562. // Create a buffer with fake command line content in order to display
  1563. // parsing diagnostic with location information and point to the
  1564. // global definition with invalid syntax.
  1565. std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
  1566. MemoryBuffer::getMemBufferCopy(CmdlineDefsDiag, "Global defines");
  1567. StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
  1568. SM.AddNewSourceBuffer(std::move(CmdLineDefsDiagBuffer), SMLoc());
  1569. for (std::pair<size_t, size_t> CmdlineDefIndices : CmdlineDefsIndices) {
  1570. StringRef CmdlineDef = CmdlineDefsDiagRef.substr(CmdlineDefIndices.first,
  1571. CmdlineDefIndices.second);
  1572. if (CmdlineDef.empty()) {
  1573. Errs = joinErrors(
  1574. std::move(Errs),
  1575. FileCheckErrorDiagnostic::get(
  1576. SM, CmdlineDef, "missing equal sign in global definition"));
  1577. continue;
  1578. }
  1579. // Numeric variable definition.
  1580. if (CmdlineDef[0] == '#') {
  1581. // Now parse the definition both to check that the syntax is correct and
  1582. // to create the necessary class instance.
  1583. StringRef CmdlineDefExpr = CmdlineDef.substr(1);
  1584. Optional<FileCheckNumericVariable *> DefinedNumericVariable;
  1585. Expected<std::unique_ptr<FileCheckExpressionAST>> ExpressionASTResult =
  1586. FileCheckPattern::parseNumericSubstitutionBlock(
  1587. CmdlineDefExpr, DefinedNumericVariable, false, None, this, SM);
  1588. if (!ExpressionASTResult) {
  1589. Errs = joinErrors(std::move(Errs), ExpressionASTResult.takeError());
  1590. continue;
  1591. }
  1592. std::unique_ptr<FileCheckExpressionAST> ExpressionAST =
  1593. std::move(*ExpressionASTResult);
  1594. // Now evaluate the expression whose value this variable should be set
  1595. // to, since the expression of a command-line variable definition should
  1596. // only use variables defined earlier on the command-line. If not, this
  1597. // is an error and we report it.
  1598. Expected<uint64_t> Value = ExpressionAST->eval();
  1599. if (!Value) {
  1600. Errs = joinErrors(std::move(Errs), Value.takeError());
  1601. continue;
  1602. }
  1603. assert(DefinedNumericVariable && "No variable defined");
  1604. (*DefinedNumericVariable)->setValue(*Value);
  1605. // Record this variable definition.
  1606. GlobalNumericVariableTable[(*DefinedNumericVariable)->getName()] =
  1607. *DefinedNumericVariable;
  1608. } else {
  1609. // String variable definition.
  1610. std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.split('=');
  1611. StringRef CmdlineName = CmdlineNameVal.first;
  1612. StringRef OrigCmdlineName = CmdlineName;
  1613. Expected<FileCheckPattern::VariableProperties> ParseVarResult =
  1614. FileCheckPattern::parseVariable(CmdlineName, SM);
  1615. if (!ParseVarResult) {
  1616. Errs = joinErrors(std::move(Errs), ParseVarResult.takeError());
  1617. continue;
  1618. }
  1619. // Check that CmdlineName does not denote a pseudo variable is only
  1620. // composed of the parsed numeric variable. This catches cases like
  1621. // "FOO+2" in a "FOO+2=10" definition.
  1622. if (ParseVarResult->IsPseudo || !CmdlineName.empty()) {
  1623. Errs = joinErrors(std::move(Errs),
  1624. FileCheckErrorDiagnostic::get(
  1625. SM, OrigCmdlineName,
  1626. "invalid name in string variable definition '" +
  1627. OrigCmdlineName + "'"));
  1628. continue;
  1629. }
  1630. StringRef Name = ParseVarResult->Name;
  1631. // Detect collisions between string and numeric variables when the former
  1632. // is created later than the latter.
  1633. if (GlobalNumericVariableTable.find(Name) !=
  1634. GlobalNumericVariableTable.end()) {
  1635. Errs = joinErrors(std::move(Errs), FileCheckErrorDiagnostic::get(
  1636. SM, Name,
  1637. "numeric variable with name '" +
  1638. Name + "' already exists"));
  1639. continue;
  1640. }
  1641. GlobalVariableTable.insert(CmdlineNameVal);
  1642. // Mark the string variable as defined to detect collisions between
  1643. // string and numeric variables in defineCmdlineVariables when the latter
  1644. // is created later than the former. We cannot reuse GlobalVariableTable
  1645. // for this by populating it with an empty string since we would then
  1646. // lose the ability to detect the use of an undefined variable in
  1647. // match().
  1648. DefinedVariableTable[Name] = true;
  1649. }
  1650. }
  1651. return Errs;
  1652. }
  1653. void FileCheckPatternContext::clearLocalVars() {
  1654. SmallVector<StringRef, 16> LocalPatternVars, LocalNumericVars;
  1655. for (const StringMapEntry<StringRef> &Var : GlobalVariableTable)
  1656. if (Var.first()[0] != '$')
  1657. LocalPatternVars.push_back(Var.first());
  1658. // Numeric substitution reads the value of a variable directly, not via
  1659. // GlobalNumericVariableTable. Therefore, we clear local variables by
  1660. // clearing their value which will lead to a numeric substitution failure. We
  1661. // also mark the variable for removal from GlobalNumericVariableTable since
  1662. // this is what defineCmdlineVariables checks to decide that no global
  1663. // variable has been defined.
  1664. for (const auto &Var : GlobalNumericVariableTable)
  1665. if (Var.first()[0] != '$') {
  1666. Var.getValue()->clearValue();
  1667. LocalNumericVars.push_back(Var.first());
  1668. }
  1669. for (const auto &Var : LocalPatternVars)
  1670. GlobalVariableTable.erase(Var);
  1671. for (const auto &Var : LocalNumericVars)
  1672. GlobalNumericVariableTable.erase(Var);
  1673. }
  1674. bool FileCheck::CheckInput(SourceMgr &SM, StringRef Buffer,
  1675. ArrayRef<FileCheckString> CheckStrings,
  1676. std::vector<FileCheckDiag> *Diags) {
  1677. bool ChecksFailed = false;
  1678. unsigned i = 0, j = 0, e = CheckStrings.size();
  1679. while (true) {
  1680. StringRef CheckRegion;
  1681. if (j == e) {
  1682. CheckRegion = Buffer;
  1683. } else {
  1684. const FileCheckString &CheckLabelStr = CheckStrings[j];
  1685. if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
  1686. ++j;
  1687. continue;
  1688. }
  1689. // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
  1690. size_t MatchLabelLen = 0;
  1691. size_t MatchLabelPos =
  1692. CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, Req, Diags);
  1693. if (MatchLabelPos == StringRef::npos)
  1694. // Immediately bail if CHECK-LABEL fails, nothing else we can do.
  1695. return false;
  1696. CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
  1697. Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
  1698. ++j;
  1699. }
  1700. // Do not clear the first region as it's the one before the first
  1701. // CHECK-LABEL and it would clear variables defined on the command-line
  1702. // before they get used.
  1703. if (i != 0 && Req.EnableVarScope)
  1704. PatternContext.clearLocalVars();
  1705. for (; i != j; ++i) {
  1706. const FileCheckString &CheckStr = CheckStrings[i];
  1707. // Check each string within the scanned region, including a second check
  1708. // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
  1709. size_t MatchLen = 0;
  1710. size_t MatchPos =
  1711. CheckStr.Check(SM, CheckRegion, false, MatchLen, Req, Diags);
  1712. if (MatchPos == StringRef::npos) {
  1713. ChecksFailed = true;
  1714. i = j;
  1715. break;
  1716. }
  1717. CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
  1718. }
  1719. if (j == e)
  1720. break;
  1721. }
  1722. // Success if no checks failed.
  1723. return !ChecksFailed;
  1724. }