FileCheck.cpp 70 KB

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