FileCheck.cpp 74 KB

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