FileCheck.cpp 70 KB

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