FileCheck.cpp 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754
  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/FileCheck/FileCheck.h"
  16. #include "FileCheckImpl.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/StringSet.h"
  19. #include "llvm/ADT/Twine.h"
  20. #include "llvm/Support/CheckedArithmetic.h"
  21. #include "llvm/Support/FormatVariadic.h"
  22. #include <cstdint>
  23. #include <list>
  24. #include <set>
  25. #include <tuple>
  26. #include <utility>
  27. using namespace llvm;
  28. StringRef ExpressionFormat::toString() const {
  29. switch (Value) {
  30. case Kind::NoFormat:
  31. return StringRef("<none>");
  32. case Kind::Unsigned:
  33. return StringRef("%u");
  34. case Kind::Signed:
  35. return StringRef("%d");
  36. case Kind::HexUpper:
  37. return StringRef("%X");
  38. case Kind::HexLower:
  39. return StringRef("%x");
  40. }
  41. llvm_unreachable("unknown expression format");
  42. }
  43. Expected<std::string> ExpressionFormat::getWildcardRegex() const {
  44. auto CreatePrecisionRegex = [this](StringRef S) {
  45. return (S + Twine('{') + Twine(Precision) + "}").str();
  46. };
  47. switch (Value) {
  48. case Kind::Unsigned:
  49. if (Precision)
  50. return CreatePrecisionRegex("([1-9][0-9]*)?[0-9]");
  51. return std::string("[0-9]+");
  52. case Kind::Signed:
  53. if (Precision)
  54. return CreatePrecisionRegex("-?([1-9][0-9]*)?[0-9]");
  55. return std::string("-?[0-9]+");
  56. case Kind::HexUpper:
  57. if (Precision)
  58. return CreatePrecisionRegex("([1-9A-F][0-9A-F]*)?[0-9A-F]");
  59. return std::string("[0-9A-F]+");
  60. case Kind::HexLower:
  61. if (Precision)
  62. return CreatePrecisionRegex("([1-9a-f][0-9a-f]*)?[0-9a-f]");
  63. return std::string("[0-9a-f]+");
  64. default:
  65. return createStringError(std::errc::invalid_argument,
  66. "trying to match value with invalid format");
  67. }
  68. }
  69. Expected<std::string>
  70. ExpressionFormat::getMatchingString(ExpressionValue IntegerValue) const {
  71. uint64_t AbsoluteValue;
  72. StringRef SignPrefix = IntegerValue.isNegative() ? "-" : "";
  73. if (Value == Kind::Signed) {
  74. Expected<int64_t> SignedValue = IntegerValue.getSignedValue();
  75. if (!SignedValue)
  76. return SignedValue.takeError();
  77. if (*SignedValue < 0)
  78. AbsoluteValue = cantFail(IntegerValue.getAbsolute().getUnsignedValue());
  79. else
  80. AbsoluteValue = *SignedValue;
  81. } else {
  82. Expected<uint64_t> UnsignedValue = IntegerValue.getUnsignedValue();
  83. if (!UnsignedValue)
  84. return UnsignedValue.takeError();
  85. AbsoluteValue = *UnsignedValue;
  86. }
  87. std::string AbsoluteValueStr;
  88. switch (Value) {
  89. case Kind::Unsigned:
  90. case Kind::Signed:
  91. AbsoluteValueStr = utostr(AbsoluteValue);
  92. break;
  93. case Kind::HexUpper:
  94. case Kind::HexLower:
  95. AbsoluteValueStr = utohexstr(AbsoluteValue, Value == Kind::HexLower);
  96. break;
  97. default:
  98. return createStringError(std::errc::invalid_argument,
  99. "trying to match value with invalid format");
  100. }
  101. if (Precision > AbsoluteValueStr.size()) {
  102. unsigned LeadingZeros = Precision - AbsoluteValueStr.size();
  103. return (Twine(SignPrefix) + std::string(LeadingZeros, '0') +
  104. AbsoluteValueStr)
  105. .str();
  106. }
  107. return (Twine(SignPrefix) + AbsoluteValueStr).str();
  108. }
  109. Expected<ExpressionValue>
  110. ExpressionFormat::valueFromStringRepr(StringRef StrVal,
  111. const SourceMgr &SM) const {
  112. bool ValueIsSigned = Value == Kind::Signed;
  113. StringRef OverflowErrorStr = "unable to represent numeric value";
  114. if (ValueIsSigned) {
  115. int64_t SignedValue;
  116. if (StrVal.getAsInteger(10, SignedValue))
  117. return ErrorDiagnostic::get(SM, StrVal, OverflowErrorStr);
  118. return ExpressionValue(SignedValue);
  119. }
  120. bool Hex = Value == Kind::HexUpper || Value == Kind::HexLower;
  121. uint64_t UnsignedValue;
  122. if (StrVal.getAsInteger(Hex ? 16 : 10, UnsignedValue))
  123. return ErrorDiagnostic::get(SM, StrVal, OverflowErrorStr);
  124. return ExpressionValue(UnsignedValue);
  125. }
  126. static int64_t getAsSigned(uint64_t UnsignedValue) {
  127. // Use memcpy to reinterpret the bitpattern in Value since casting to
  128. // signed is implementation-defined if the unsigned value is too big to be
  129. // represented in the signed type and using an union violates type aliasing
  130. // rules.
  131. int64_t SignedValue;
  132. memcpy(&SignedValue, &UnsignedValue, sizeof(SignedValue));
  133. return SignedValue;
  134. }
  135. Expected<int64_t> ExpressionValue::getSignedValue() const {
  136. if (Negative)
  137. return getAsSigned(Value);
  138. if (Value > (uint64_t)std::numeric_limits<int64_t>::max())
  139. return make_error<OverflowError>();
  140. // Value is in the representable range of int64_t so we can use cast.
  141. return static_cast<int64_t>(Value);
  142. }
  143. Expected<uint64_t> ExpressionValue::getUnsignedValue() const {
  144. if (Negative)
  145. return make_error<OverflowError>();
  146. return Value;
  147. }
  148. ExpressionValue ExpressionValue::getAbsolute() const {
  149. if (!Negative)
  150. return *this;
  151. int64_t SignedValue = getAsSigned(Value);
  152. int64_t MaxInt64 = std::numeric_limits<int64_t>::max();
  153. // Absolute value can be represented as int64_t.
  154. if (SignedValue >= -MaxInt64)
  155. return ExpressionValue(-getAsSigned(Value));
  156. // -X == -(max int64_t + Rem), negate each component independently.
  157. SignedValue += MaxInt64;
  158. uint64_t RemainingValueAbsolute = -SignedValue;
  159. return ExpressionValue(MaxInt64 + RemainingValueAbsolute);
  160. }
  161. Expected<ExpressionValue> llvm::operator+(const ExpressionValue &LeftOperand,
  162. const ExpressionValue &RightOperand) {
  163. if (LeftOperand.isNegative() && RightOperand.isNegative()) {
  164. int64_t LeftValue = cantFail(LeftOperand.getSignedValue());
  165. int64_t RightValue = cantFail(RightOperand.getSignedValue());
  166. Optional<int64_t> Result = checkedAdd<int64_t>(LeftValue, RightValue);
  167. if (!Result)
  168. return make_error<OverflowError>();
  169. return ExpressionValue(*Result);
  170. }
  171. // (-A) + B == B - A.
  172. if (LeftOperand.isNegative())
  173. return RightOperand - LeftOperand.getAbsolute();
  174. // A + (-B) == A - B.
  175. if (RightOperand.isNegative())
  176. return LeftOperand - RightOperand.getAbsolute();
  177. // Both values are positive at this point.
  178. uint64_t LeftValue = cantFail(LeftOperand.getUnsignedValue());
  179. uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
  180. Optional<uint64_t> Result =
  181. checkedAddUnsigned<uint64_t>(LeftValue, RightValue);
  182. if (!Result)
  183. return make_error<OverflowError>();
  184. return ExpressionValue(*Result);
  185. }
  186. Expected<ExpressionValue> llvm::operator-(const ExpressionValue &LeftOperand,
  187. const ExpressionValue &RightOperand) {
  188. // Result will be negative and thus might underflow.
  189. if (LeftOperand.isNegative() && !RightOperand.isNegative()) {
  190. int64_t LeftValue = cantFail(LeftOperand.getSignedValue());
  191. uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
  192. // Result <= -1 - (max int64_t) which overflows on 1- and 2-complement.
  193. if (RightValue > (uint64_t)std::numeric_limits<int64_t>::max())
  194. return make_error<OverflowError>();
  195. Optional<int64_t> Result =
  196. checkedSub(LeftValue, static_cast<int64_t>(RightValue));
  197. if (!Result)
  198. return make_error<OverflowError>();
  199. return ExpressionValue(*Result);
  200. }
  201. // (-A) - (-B) == B - A.
  202. if (LeftOperand.isNegative())
  203. return RightOperand.getAbsolute() - LeftOperand.getAbsolute();
  204. // A - (-B) == A + B.
  205. if (RightOperand.isNegative())
  206. return LeftOperand + RightOperand.getAbsolute();
  207. // Both values are positive at this point.
  208. uint64_t LeftValue = cantFail(LeftOperand.getUnsignedValue());
  209. uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
  210. if (LeftValue >= RightValue)
  211. return ExpressionValue(LeftValue - RightValue);
  212. else {
  213. uint64_t AbsoluteDifference = RightValue - LeftValue;
  214. uint64_t MaxInt64 = std::numeric_limits<int64_t>::max();
  215. // Value might underflow.
  216. if (AbsoluteDifference > MaxInt64) {
  217. AbsoluteDifference -= MaxInt64;
  218. int64_t Result = -MaxInt64;
  219. int64_t MinInt64 = std::numeric_limits<int64_t>::min();
  220. // Underflow, tested by:
  221. // abs(Result + (max int64_t)) > abs((min int64_t) + (max int64_t))
  222. if (AbsoluteDifference > static_cast<uint64_t>(-(MinInt64 - Result)))
  223. return make_error<OverflowError>();
  224. Result -= static_cast<int64_t>(AbsoluteDifference);
  225. return ExpressionValue(Result);
  226. }
  227. return ExpressionValue(-static_cast<int64_t>(AbsoluteDifference));
  228. }
  229. }
  230. Expected<ExpressionValue> llvm::operator*(const ExpressionValue &LeftOperand,
  231. const ExpressionValue &RightOperand) {
  232. // -A * -B == A * B
  233. if (LeftOperand.isNegative() && RightOperand.isNegative())
  234. return LeftOperand.getAbsolute() * RightOperand.getAbsolute();
  235. // A * -B == -B * A
  236. if (RightOperand.isNegative())
  237. return RightOperand * LeftOperand;
  238. assert(!RightOperand.isNegative() && "Unexpected negative operand!");
  239. // Result will be negative and can underflow.
  240. if (LeftOperand.isNegative()) {
  241. auto Result = LeftOperand.getAbsolute() * RightOperand.getAbsolute();
  242. if (!Result)
  243. return Result;
  244. return ExpressionValue(0) - *Result;
  245. }
  246. // Result will be positive and can overflow.
  247. uint64_t LeftValue = cantFail(LeftOperand.getUnsignedValue());
  248. uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
  249. Optional<uint64_t> Result =
  250. checkedMulUnsigned<uint64_t>(LeftValue, RightValue);
  251. if (!Result)
  252. return make_error<OverflowError>();
  253. return ExpressionValue(*Result);
  254. }
  255. Expected<ExpressionValue> llvm::operator/(const ExpressionValue &LeftOperand,
  256. const ExpressionValue &RightOperand) {
  257. // -A / -B == A / B
  258. if (LeftOperand.isNegative() && RightOperand.isNegative())
  259. return LeftOperand.getAbsolute() / RightOperand.getAbsolute();
  260. // Check for divide by zero.
  261. if (RightOperand == ExpressionValue(0))
  262. return make_error<OverflowError>();
  263. // Result will be negative and can underflow.
  264. if (LeftOperand.isNegative() || RightOperand.isNegative())
  265. return ExpressionValue(0) -
  266. cantFail(LeftOperand.getAbsolute() / RightOperand.getAbsolute());
  267. uint64_t LeftValue = cantFail(LeftOperand.getUnsignedValue());
  268. uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
  269. return ExpressionValue(LeftValue / RightValue);
  270. }
  271. Expected<ExpressionValue> llvm::max(const ExpressionValue &LeftOperand,
  272. const ExpressionValue &RightOperand) {
  273. if (LeftOperand.isNegative() && RightOperand.isNegative()) {
  274. int64_t LeftValue = cantFail(LeftOperand.getSignedValue());
  275. int64_t RightValue = cantFail(RightOperand.getSignedValue());
  276. return ExpressionValue(std::max(LeftValue, RightValue));
  277. }
  278. if (!LeftOperand.isNegative() && !RightOperand.isNegative()) {
  279. uint64_t LeftValue = cantFail(LeftOperand.getUnsignedValue());
  280. uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
  281. return ExpressionValue(std::max(LeftValue, RightValue));
  282. }
  283. if (LeftOperand.isNegative())
  284. return RightOperand;
  285. return LeftOperand;
  286. }
  287. Expected<ExpressionValue> llvm::min(const ExpressionValue &LeftOperand,
  288. const ExpressionValue &RightOperand) {
  289. if (cantFail(max(LeftOperand, RightOperand)) == LeftOperand)
  290. return RightOperand;
  291. return LeftOperand;
  292. }
  293. Expected<ExpressionValue> NumericVariableUse::eval() const {
  294. Optional<ExpressionValue> Value = Variable->getValue();
  295. if (Value)
  296. return *Value;
  297. return make_error<UndefVarError>(getExpressionStr());
  298. }
  299. Expected<ExpressionValue> BinaryOperation::eval() const {
  300. Expected<ExpressionValue> LeftOp = LeftOperand->eval();
  301. Expected<ExpressionValue> RightOp = RightOperand->eval();
  302. // Bubble up any error (e.g. undefined variables) in the recursive
  303. // evaluation.
  304. if (!LeftOp || !RightOp) {
  305. Error Err = Error::success();
  306. if (!LeftOp)
  307. Err = joinErrors(std::move(Err), LeftOp.takeError());
  308. if (!RightOp)
  309. Err = joinErrors(std::move(Err), RightOp.takeError());
  310. return std::move(Err);
  311. }
  312. return EvalBinop(*LeftOp, *RightOp);
  313. }
  314. Expected<ExpressionFormat>
  315. BinaryOperation::getImplicitFormat(const SourceMgr &SM) const {
  316. Expected<ExpressionFormat> LeftFormat = LeftOperand->getImplicitFormat(SM);
  317. Expected<ExpressionFormat> RightFormat = RightOperand->getImplicitFormat(SM);
  318. if (!LeftFormat || !RightFormat) {
  319. Error Err = Error::success();
  320. if (!LeftFormat)
  321. Err = joinErrors(std::move(Err), LeftFormat.takeError());
  322. if (!RightFormat)
  323. Err = joinErrors(std::move(Err), RightFormat.takeError());
  324. return std::move(Err);
  325. }
  326. if (*LeftFormat != ExpressionFormat::Kind::NoFormat &&
  327. *RightFormat != ExpressionFormat::Kind::NoFormat &&
  328. *LeftFormat != *RightFormat)
  329. return ErrorDiagnostic::get(
  330. SM, getExpressionStr(),
  331. "implicit format conflict between '" + LeftOperand->getExpressionStr() +
  332. "' (" + LeftFormat->toString() + ") and '" +
  333. RightOperand->getExpressionStr() + "' (" + RightFormat->toString() +
  334. "), need an explicit format specifier");
  335. return *LeftFormat != ExpressionFormat::Kind::NoFormat ? *LeftFormat
  336. : *RightFormat;
  337. }
  338. Expected<std::string> NumericSubstitution::getResult() const {
  339. assert(ExpressionPointer->getAST() != nullptr &&
  340. "Substituting empty expression");
  341. Expected<ExpressionValue> EvaluatedValue =
  342. ExpressionPointer->getAST()->eval();
  343. if (!EvaluatedValue)
  344. return EvaluatedValue.takeError();
  345. ExpressionFormat Format = ExpressionPointer->getFormat();
  346. return Format.getMatchingString(*EvaluatedValue);
  347. }
  348. Expected<std::string> StringSubstitution::getResult() const {
  349. // Look up the value and escape it so that we can put it into the regex.
  350. Expected<StringRef> VarVal = Context->getPatternVarValue(FromStr);
  351. if (!VarVal)
  352. return VarVal.takeError();
  353. return Regex::escape(*VarVal);
  354. }
  355. bool Pattern::isValidVarNameStart(char C) { return C == '_' || isAlpha(C); }
  356. Expected<Pattern::VariableProperties>
  357. Pattern::parseVariable(StringRef &Str, const SourceMgr &SM) {
  358. if (Str.empty())
  359. return ErrorDiagnostic::get(SM, Str, "empty variable name");
  360. size_t I = 0;
  361. bool IsPseudo = Str[0] == '@';
  362. // Global vars start with '$'.
  363. if (Str[0] == '$' || IsPseudo)
  364. ++I;
  365. if (!isValidVarNameStart(Str[I++]))
  366. return ErrorDiagnostic::get(SM, Str, "invalid variable name");
  367. for (size_t E = Str.size(); I != E; ++I)
  368. // Variable names are composed of alphanumeric characters and underscores.
  369. if (Str[I] != '_' && !isAlnum(Str[I]))
  370. break;
  371. StringRef Name = Str.take_front(I);
  372. Str = Str.substr(I);
  373. return VariableProperties {Name, IsPseudo};
  374. }
  375. // StringRef holding all characters considered as horizontal whitespaces by
  376. // FileCheck input canonicalization.
  377. constexpr StringLiteral SpaceChars = " \t";
  378. // Parsing helper function that strips the first character in S and returns it.
  379. static char popFront(StringRef &S) {
  380. char C = S.front();
  381. S = S.drop_front();
  382. return C;
  383. }
  384. char OverflowError::ID = 0;
  385. char UndefVarError::ID = 0;
  386. char ErrorDiagnostic::ID = 0;
  387. char NotFoundError::ID = 0;
  388. Expected<NumericVariable *> Pattern::parseNumericVariableDefinition(
  389. StringRef &Expr, FileCheckPatternContext *Context,
  390. Optional<size_t> LineNumber, ExpressionFormat ImplicitFormat,
  391. const SourceMgr &SM) {
  392. Expected<VariableProperties> ParseVarResult = parseVariable(Expr, SM);
  393. if (!ParseVarResult)
  394. return ParseVarResult.takeError();
  395. StringRef Name = ParseVarResult->Name;
  396. if (ParseVarResult->IsPseudo)
  397. return ErrorDiagnostic::get(
  398. SM, Name, "definition of pseudo numeric variable unsupported");
  399. // Detect collisions between string and numeric variables when the latter
  400. // is created later than the former.
  401. if (Context->DefinedVariableTable.find(Name) !=
  402. Context->DefinedVariableTable.end())
  403. return ErrorDiagnostic::get(
  404. SM, Name, "string variable with name '" + Name + "' already exists");
  405. Expr = Expr.ltrim(SpaceChars);
  406. if (!Expr.empty())
  407. return ErrorDiagnostic::get(
  408. SM, Expr, "unexpected characters after numeric variable name");
  409. NumericVariable *DefinedNumericVariable;
  410. auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
  411. if (VarTableIter != Context->GlobalNumericVariableTable.end()) {
  412. DefinedNumericVariable = VarTableIter->second;
  413. if (DefinedNumericVariable->getImplicitFormat() != ImplicitFormat)
  414. return ErrorDiagnostic::get(
  415. SM, Expr, "format different from previous variable definition");
  416. } else
  417. DefinedNumericVariable =
  418. Context->makeNumericVariable(Name, ImplicitFormat, LineNumber);
  419. return DefinedNumericVariable;
  420. }
  421. Expected<std::unique_ptr<NumericVariableUse>> Pattern::parseNumericVariableUse(
  422. StringRef Name, bool IsPseudo, Optional<size_t> LineNumber,
  423. FileCheckPatternContext *Context, const SourceMgr &SM) {
  424. if (IsPseudo && !Name.equals("@LINE"))
  425. return ErrorDiagnostic::get(
  426. SM, Name, "invalid pseudo numeric variable '" + Name + "'");
  427. // Numeric variable definitions and uses are parsed in the order in which
  428. // they appear in the CHECK patterns. For each definition, the pointer to the
  429. // class instance of the corresponding numeric variable definition is stored
  430. // in GlobalNumericVariableTable in parsePattern. Therefore, if the pointer
  431. // we get below is null, it means no such variable was defined before. When
  432. // that happens, we create a dummy variable so that parsing can continue. All
  433. // uses of undefined variables, whether string or numeric, are then diagnosed
  434. // in printSubstitutions() after failing to match.
  435. auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
  436. NumericVariable *NumericVariable;
  437. if (VarTableIter != Context->GlobalNumericVariableTable.end())
  438. NumericVariable = VarTableIter->second;
  439. else {
  440. NumericVariable = Context->makeNumericVariable(
  441. Name, ExpressionFormat(ExpressionFormat::Kind::Unsigned));
  442. Context->GlobalNumericVariableTable[Name] = NumericVariable;
  443. }
  444. Optional<size_t> DefLineNumber = NumericVariable->getDefLineNumber();
  445. if (DefLineNumber && LineNumber && *DefLineNumber == *LineNumber)
  446. return ErrorDiagnostic::get(
  447. SM, Name,
  448. "numeric variable '" + Name +
  449. "' defined earlier in the same CHECK directive");
  450. return std::make_unique<NumericVariableUse>(Name, NumericVariable);
  451. }
  452. Expected<std::unique_ptr<ExpressionAST>> Pattern::parseNumericOperand(
  453. StringRef &Expr, AllowedOperand AO, bool MaybeInvalidConstraint,
  454. Optional<size_t> LineNumber, FileCheckPatternContext *Context,
  455. const SourceMgr &SM) {
  456. if (Expr.startswith("(")) {
  457. if (AO != AllowedOperand::Any)
  458. return ErrorDiagnostic::get(
  459. SM, Expr, "parenthesized expression not permitted here");
  460. return parseParenExpr(Expr, LineNumber, Context, SM);
  461. }
  462. if (AO == AllowedOperand::LineVar || AO == AllowedOperand::Any) {
  463. // Try to parse as a numeric variable use.
  464. Expected<Pattern::VariableProperties> ParseVarResult =
  465. parseVariable(Expr, SM);
  466. if (ParseVarResult) {
  467. // Try to parse a function call.
  468. if (Expr.ltrim(SpaceChars).startswith("(")) {
  469. if (AO != AllowedOperand::Any)
  470. return ErrorDiagnostic::get(SM, ParseVarResult->Name,
  471. "unexpected function call");
  472. return parseCallExpr(Expr, ParseVarResult->Name, LineNumber, Context,
  473. SM);
  474. }
  475. return parseNumericVariableUse(ParseVarResult->Name,
  476. ParseVarResult->IsPseudo, LineNumber,
  477. Context, SM);
  478. }
  479. if (AO == AllowedOperand::LineVar)
  480. return ParseVarResult.takeError();
  481. // Ignore the error and retry parsing as a literal.
  482. consumeError(ParseVarResult.takeError());
  483. }
  484. // Otherwise, parse it as a literal.
  485. int64_t SignedLiteralValue;
  486. uint64_t UnsignedLiteralValue;
  487. StringRef SaveExpr = Expr;
  488. // Accept both signed and unsigned literal, default to signed literal.
  489. if (!Expr.consumeInteger((AO == AllowedOperand::LegacyLiteral) ? 10 : 0,
  490. UnsignedLiteralValue))
  491. return std::make_unique<ExpressionLiteral>(SaveExpr.drop_back(Expr.size()),
  492. UnsignedLiteralValue);
  493. Expr = SaveExpr;
  494. if (AO == AllowedOperand::Any && !Expr.consumeInteger(0, SignedLiteralValue))
  495. return std::make_unique<ExpressionLiteral>(SaveExpr.drop_back(Expr.size()),
  496. SignedLiteralValue);
  497. return ErrorDiagnostic::get(
  498. SM, Expr,
  499. Twine("invalid ") +
  500. (MaybeInvalidConstraint ? "matching constraint or " : "") +
  501. "operand format");
  502. }
  503. Expected<std::unique_ptr<ExpressionAST>>
  504. Pattern::parseParenExpr(StringRef &Expr, Optional<size_t> LineNumber,
  505. FileCheckPatternContext *Context, const SourceMgr &SM) {
  506. Expr = Expr.ltrim(SpaceChars);
  507. assert(Expr.startswith("("));
  508. // Parse right operand.
  509. Expr.consume_front("(");
  510. Expr = Expr.ltrim(SpaceChars);
  511. if (Expr.empty())
  512. return ErrorDiagnostic::get(SM, Expr, "missing operand in expression");
  513. // Note: parseNumericOperand handles nested opening parentheses.
  514. Expected<std::unique_ptr<ExpressionAST>> SubExprResult = parseNumericOperand(
  515. Expr, AllowedOperand::Any, /*MaybeInvalidConstraint=*/false, LineNumber,
  516. Context, SM);
  517. Expr = Expr.ltrim(SpaceChars);
  518. while (SubExprResult && !Expr.empty() && !Expr.startswith(")")) {
  519. StringRef OrigExpr = Expr;
  520. SubExprResult = parseBinop(OrigExpr, Expr, std::move(*SubExprResult), false,
  521. LineNumber, Context, SM);
  522. Expr = Expr.ltrim(SpaceChars);
  523. }
  524. if (!SubExprResult)
  525. return SubExprResult;
  526. if (!Expr.consume_front(")")) {
  527. return ErrorDiagnostic::get(SM, Expr,
  528. "missing ')' at end of nested expression");
  529. }
  530. return SubExprResult;
  531. }
  532. Expected<std::unique_ptr<ExpressionAST>>
  533. Pattern::parseBinop(StringRef Expr, StringRef &RemainingExpr,
  534. std::unique_ptr<ExpressionAST> LeftOp,
  535. bool IsLegacyLineExpr, Optional<size_t> LineNumber,
  536. FileCheckPatternContext *Context, const SourceMgr &SM) {
  537. RemainingExpr = RemainingExpr.ltrim(SpaceChars);
  538. if (RemainingExpr.empty())
  539. return std::move(LeftOp);
  540. // Check if this is a supported operation and select a function to perform
  541. // it.
  542. SMLoc OpLoc = SMLoc::getFromPointer(RemainingExpr.data());
  543. char Operator = popFront(RemainingExpr);
  544. binop_eval_t EvalBinop;
  545. switch (Operator) {
  546. case '+':
  547. EvalBinop = operator+;
  548. break;
  549. case '-':
  550. EvalBinop = operator-;
  551. break;
  552. default:
  553. return ErrorDiagnostic::get(
  554. SM, OpLoc, Twine("unsupported operation '") + Twine(Operator) + "'");
  555. }
  556. // Parse right operand.
  557. RemainingExpr = RemainingExpr.ltrim(SpaceChars);
  558. if (RemainingExpr.empty())
  559. return ErrorDiagnostic::get(SM, RemainingExpr,
  560. "missing operand in expression");
  561. // The second operand in a legacy @LINE expression is always a literal.
  562. AllowedOperand AO =
  563. IsLegacyLineExpr ? AllowedOperand::LegacyLiteral : AllowedOperand::Any;
  564. Expected<std::unique_ptr<ExpressionAST>> RightOpResult =
  565. parseNumericOperand(RemainingExpr, AO, /*MaybeInvalidConstraint=*/false,
  566. LineNumber, Context, SM);
  567. if (!RightOpResult)
  568. return RightOpResult;
  569. Expr = Expr.drop_back(RemainingExpr.size());
  570. return std::make_unique<BinaryOperation>(Expr, EvalBinop, std::move(LeftOp),
  571. std::move(*RightOpResult));
  572. }
  573. Expected<std::unique_ptr<ExpressionAST>>
  574. Pattern::parseCallExpr(StringRef &Expr, StringRef FuncName,
  575. Optional<size_t> LineNumber,
  576. FileCheckPatternContext *Context, const SourceMgr &SM) {
  577. Expr = Expr.ltrim(SpaceChars);
  578. assert(Expr.startswith("("));
  579. auto OptFunc = StringSwitch<Optional<binop_eval_t>>(FuncName)
  580. .Case("add", operator+)
  581. .Case("div", operator/)
  582. .Case("max", max)
  583. .Case("min", min)
  584. .Case("mul", operator*)
  585. .Case("sub", operator-)
  586. .Default(None);
  587. if (!OptFunc)
  588. return ErrorDiagnostic::get(
  589. SM, FuncName, Twine("call to undefined function '") + FuncName + "'");
  590. Expr.consume_front("(");
  591. Expr = Expr.ltrim(SpaceChars);
  592. // Parse call arguments, which are comma separated.
  593. SmallVector<std::unique_ptr<ExpressionAST>, 4> Args;
  594. while (!Expr.empty() && !Expr.startswith(")")) {
  595. if (Expr.startswith(","))
  596. return ErrorDiagnostic::get(SM, Expr, "missing argument");
  597. // Parse the argument, which is an arbitary expression.
  598. StringRef OuterBinOpExpr = Expr;
  599. Expected<std::unique_ptr<ExpressionAST>> Arg = parseNumericOperand(
  600. Expr, AllowedOperand::Any, /*MaybeInvalidConstraint=*/false, LineNumber,
  601. Context, SM);
  602. while (Arg && !Expr.empty()) {
  603. Expr = Expr.ltrim(SpaceChars);
  604. // Have we reached an argument terminator?
  605. if (Expr.startswith(",") || Expr.startswith(")"))
  606. break;
  607. // Arg = Arg <op> <expr>
  608. Arg = parseBinop(OuterBinOpExpr, Expr, std::move(*Arg), false, LineNumber,
  609. Context, SM);
  610. }
  611. // Prefer an expression error over a generic invalid argument message.
  612. if (!Arg)
  613. return Arg.takeError();
  614. Args.push_back(std::move(*Arg));
  615. // Have we parsed all available arguments?
  616. Expr = Expr.ltrim(SpaceChars);
  617. if (!Expr.consume_front(","))
  618. break;
  619. Expr = Expr.ltrim(SpaceChars);
  620. if (Expr.startswith(")"))
  621. return ErrorDiagnostic::get(SM, Expr, "missing argument");
  622. }
  623. if (!Expr.consume_front(")"))
  624. return ErrorDiagnostic::get(SM, Expr,
  625. "missing ')' at end of call expression");
  626. const unsigned NumArgs = Args.size();
  627. if (NumArgs == 2)
  628. return std::make_unique<BinaryOperation>(Expr, *OptFunc, std::move(Args[0]),
  629. std::move(Args[1]));
  630. // TODO: Support more than binop_eval_t.
  631. return ErrorDiagnostic::get(SM, FuncName,
  632. Twine("function '") + FuncName +
  633. Twine("' takes 2 arguments but ") +
  634. Twine(NumArgs) + " given");
  635. }
  636. Expected<std::unique_ptr<Expression>> Pattern::parseNumericSubstitutionBlock(
  637. StringRef Expr, Optional<NumericVariable *> &DefinedNumericVariable,
  638. bool IsLegacyLineExpr, Optional<size_t> LineNumber,
  639. FileCheckPatternContext *Context, const SourceMgr &SM) {
  640. std::unique_ptr<ExpressionAST> ExpressionASTPointer = nullptr;
  641. StringRef DefExpr = StringRef();
  642. DefinedNumericVariable = None;
  643. ExpressionFormat ExplicitFormat = ExpressionFormat();
  644. unsigned Precision = 0;
  645. // Parse format specifier (NOTE: ',' is also an argument seperator).
  646. size_t FormatSpecEnd = Expr.find(',');
  647. size_t FunctionStart = Expr.find('(');
  648. if (FormatSpecEnd != StringRef::npos && FormatSpecEnd < FunctionStart) {
  649. StringRef FormatExpr = Expr.take_front(FormatSpecEnd);
  650. Expr = Expr.drop_front(FormatSpecEnd + 1);
  651. FormatExpr = FormatExpr.trim(SpaceChars);
  652. if (!FormatExpr.consume_front("%"))
  653. return ErrorDiagnostic::get(
  654. SM, FormatExpr,
  655. "invalid matching format specification in expression");
  656. // Parse precision.
  657. if (FormatExpr.consume_front(".")) {
  658. if (FormatExpr.consumeInteger(10, Precision))
  659. return ErrorDiagnostic::get(SM, FormatExpr,
  660. "invalid precision in format specifier");
  661. }
  662. if (!FormatExpr.empty()) {
  663. // Check for unknown matching format specifier and set matching format in
  664. // class instance representing this expression.
  665. SMLoc FmtLoc = SMLoc::getFromPointer(FormatExpr.data());
  666. switch (popFront(FormatExpr)) {
  667. case 'u':
  668. ExplicitFormat =
  669. ExpressionFormat(ExpressionFormat::Kind::Unsigned, Precision);
  670. break;
  671. case 'd':
  672. ExplicitFormat =
  673. ExpressionFormat(ExpressionFormat::Kind::Signed, Precision);
  674. break;
  675. case 'x':
  676. ExplicitFormat =
  677. ExpressionFormat(ExpressionFormat::Kind::HexLower, Precision);
  678. break;
  679. case 'X':
  680. ExplicitFormat =
  681. ExpressionFormat(ExpressionFormat::Kind::HexUpper, Precision);
  682. break;
  683. default:
  684. return ErrorDiagnostic::get(SM, FmtLoc,
  685. "invalid format specifier in expression");
  686. }
  687. }
  688. FormatExpr = FormatExpr.ltrim(SpaceChars);
  689. if (!FormatExpr.empty())
  690. return ErrorDiagnostic::get(
  691. SM, FormatExpr,
  692. "invalid matching format specification in expression");
  693. }
  694. // Save variable definition expression if any.
  695. size_t DefEnd = Expr.find(':');
  696. if (DefEnd != StringRef::npos) {
  697. DefExpr = Expr.substr(0, DefEnd);
  698. Expr = Expr.substr(DefEnd + 1);
  699. }
  700. // Parse matching constraint.
  701. Expr = Expr.ltrim(SpaceChars);
  702. bool HasParsedValidConstraint = false;
  703. if (Expr.consume_front("=="))
  704. HasParsedValidConstraint = true;
  705. // Parse the expression itself.
  706. Expr = Expr.ltrim(SpaceChars);
  707. if (Expr.empty()) {
  708. if (HasParsedValidConstraint)
  709. return ErrorDiagnostic::get(
  710. SM, Expr, "empty numeric expression should not have a constraint");
  711. } else {
  712. Expr = Expr.rtrim(SpaceChars);
  713. StringRef OuterBinOpExpr = Expr;
  714. // The first operand in a legacy @LINE expression is always the @LINE
  715. // pseudo variable.
  716. AllowedOperand AO =
  717. IsLegacyLineExpr ? AllowedOperand::LineVar : AllowedOperand::Any;
  718. Expected<std::unique_ptr<ExpressionAST>> ParseResult = parseNumericOperand(
  719. Expr, AO, !HasParsedValidConstraint, LineNumber, Context, SM);
  720. while (ParseResult && !Expr.empty()) {
  721. ParseResult = parseBinop(OuterBinOpExpr, Expr, std::move(*ParseResult),
  722. IsLegacyLineExpr, LineNumber, Context, SM);
  723. // Legacy @LINE expressions only allow 2 operands.
  724. if (ParseResult && IsLegacyLineExpr && !Expr.empty())
  725. return ErrorDiagnostic::get(
  726. SM, Expr,
  727. "unexpected characters at end of expression '" + Expr + "'");
  728. }
  729. if (!ParseResult)
  730. return ParseResult.takeError();
  731. ExpressionASTPointer = std::move(*ParseResult);
  732. }
  733. // Select format of the expression, i.e. (i) its explicit format, if any,
  734. // otherwise (ii) its implicit format, if any, otherwise (iii) the default
  735. // format (unsigned). Error out in case of conflicting implicit format
  736. // without explicit format.
  737. ExpressionFormat Format;
  738. if (ExplicitFormat)
  739. Format = ExplicitFormat;
  740. else if (ExpressionASTPointer) {
  741. Expected<ExpressionFormat> ImplicitFormat =
  742. ExpressionASTPointer->getImplicitFormat(SM);
  743. if (!ImplicitFormat)
  744. return ImplicitFormat.takeError();
  745. Format = *ImplicitFormat;
  746. }
  747. if (!Format)
  748. Format = ExpressionFormat(ExpressionFormat::Kind::Unsigned, Precision);
  749. std::unique_ptr<Expression> ExpressionPointer =
  750. std::make_unique<Expression>(std::move(ExpressionASTPointer), Format);
  751. // Parse the numeric variable definition.
  752. if (DefEnd != StringRef::npos) {
  753. DefExpr = DefExpr.ltrim(SpaceChars);
  754. Expected<NumericVariable *> ParseResult = parseNumericVariableDefinition(
  755. DefExpr, Context, LineNumber, ExpressionPointer->getFormat(), SM);
  756. if (!ParseResult)
  757. return ParseResult.takeError();
  758. DefinedNumericVariable = *ParseResult;
  759. }
  760. return std::move(ExpressionPointer);
  761. }
  762. bool Pattern::parsePattern(StringRef PatternStr, StringRef Prefix,
  763. SourceMgr &SM, const FileCheckRequest &Req) {
  764. bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
  765. IgnoreCase = Req.IgnoreCase;
  766. PatternLoc = SMLoc::getFromPointer(PatternStr.data());
  767. if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
  768. // Ignore trailing whitespace.
  769. while (!PatternStr.empty() &&
  770. (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
  771. PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
  772. // Check that there is something on the line.
  773. if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
  774. SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
  775. "found empty check string with prefix '" + Prefix + ":'");
  776. return true;
  777. }
  778. if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
  779. SM.PrintMessage(
  780. PatternLoc, SourceMgr::DK_Error,
  781. "found non-empty check string for empty check with prefix '" + Prefix +
  782. ":'");
  783. return true;
  784. }
  785. if (CheckTy == Check::CheckEmpty) {
  786. RegExStr = "(\n$)";
  787. return false;
  788. }
  789. // If literal check, set fixed string.
  790. if (CheckTy.isLiteralMatch()) {
  791. FixedStr = PatternStr;
  792. return false;
  793. }
  794. // Check to see if this is a fixed string, or if it has regex pieces.
  795. if (!MatchFullLinesHere &&
  796. (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
  797. PatternStr.find("[[") == StringRef::npos))) {
  798. FixedStr = PatternStr;
  799. return false;
  800. }
  801. if (MatchFullLinesHere) {
  802. RegExStr += '^';
  803. if (!Req.NoCanonicalizeWhiteSpace)
  804. RegExStr += " *";
  805. }
  806. // Paren value #0 is for the fully matched string. Any new parenthesized
  807. // values add from there.
  808. unsigned CurParen = 1;
  809. // Otherwise, there is at least one regex piece. Build up the regex pattern
  810. // by escaping scary characters in fixed strings, building up one big regex.
  811. while (!PatternStr.empty()) {
  812. // RegEx matches.
  813. if (PatternStr.startswith("{{")) {
  814. // This is the start of a regex match. Scan for the }}.
  815. size_t End = PatternStr.find("}}");
  816. if (End == StringRef::npos) {
  817. SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
  818. SourceMgr::DK_Error,
  819. "found start of regex string with no end '}}'");
  820. return true;
  821. }
  822. // Enclose {{}} patterns in parens just like [[]] even though we're not
  823. // capturing the result for any purpose. This is required in case the
  824. // expression contains an alternation like: CHECK: abc{{x|z}}def. We
  825. // want this to turn into: "abc(x|z)def" not "abcx|zdef".
  826. RegExStr += '(';
  827. ++CurParen;
  828. if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
  829. return true;
  830. RegExStr += ')';
  831. PatternStr = PatternStr.substr(End + 2);
  832. continue;
  833. }
  834. // String and numeric substitution blocks. Pattern substitution blocks come
  835. // in two forms: [[foo:.*]] and [[foo]]. The former matches .* (or some
  836. // other regex) and assigns it to the string variable 'foo'. The latter
  837. // substitutes foo's value. Numeric substitution blocks recognize the same
  838. // form as string ones, but start with a '#' sign after the double
  839. // brackets. They also accept a combined form which sets a numeric variable
  840. // to the evaluation of an expression. Both string and numeric variable
  841. // names must satisfy the regular expression "[a-zA-Z_][0-9a-zA-Z_]*" to be
  842. // valid, as this helps catch some common errors.
  843. if (PatternStr.startswith("[[")) {
  844. StringRef UnparsedPatternStr = PatternStr.substr(2);
  845. // Find the closing bracket pair ending the match. End is going to be an
  846. // offset relative to the beginning of the match string.
  847. size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
  848. StringRef MatchStr = UnparsedPatternStr.substr(0, End);
  849. bool IsNumBlock = MatchStr.consume_front("#");
  850. if (End == StringRef::npos) {
  851. SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
  852. SourceMgr::DK_Error,
  853. "Invalid substitution block, no ]] found");
  854. return true;
  855. }
  856. // Strip the substitution block we are parsing. End points to the start
  857. // of the "]]" closing the expression so account for it in computing the
  858. // index of the first unparsed character.
  859. PatternStr = UnparsedPatternStr.substr(End + 2);
  860. bool IsDefinition = false;
  861. bool SubstNeeded = false;
  862. // Whether the substitution block is a legacy use of @LINE with string
  863. // substitution block syntax.
  864. bool IsLegacyLineExpr = false;
  865. StringRef DefName;
  866. StringRef SubstStr;
  867. std::string MatchRegexp;
  868. size_t SubstInsertIdx = RegExStr.size();
  869. // Parse string variable or legacy @LINE expression.
  870. if (!IsNumBlock) {
  871. size_t VarEndIdx = MatchStr.find(':');
  872. size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
  873. if (SpacePos != StringRef::npos) {
  874. SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
  875. SourceMgr::DK_Error, "unexpected whitespace");
  876. return true;
  877. }
  878. // Get the name (e.g. "foo") and verify it is well formed.
  879. StringRef OrigMatchStr = MatchStr;
  880. Expected<Pattern::VariableProperties> ParseVarResult =
  881. parseVariable(MatchStr, SM);
  882. if (!ParseVarResult) {
  883. logAllUnhandledErrors(ParseVarResult.takeError(), errs());
  884. return true;
  885. }
  886. StringRef Name = ParseVarResult->Name;
  887. bool IsPseudo = ParseVarResult->IsPseudo;
  888. IsDefinition = (VarEndIdx != StringRef::npos);
  889. SubstNeeded = !IsDefinition;
  890. if (IsDefinition) {
  891. if ((IsPseudo || !MatchStr.consume_front(":"))) {
  892. SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
  893. SourceMgr::DK_Error,
  894. "invalid name in string variable definition");
  895. return true;
  896. }
  897. // Detect collisions between string and numeric variables when the
  898. // former is created later than the latter.
  899. if (Context->GlobalNumericVariableTable.find(Name) !=
  900. Context->GlobalNumericVariableTable.end()) {
  901. SM.PrintMessage(
  902. SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
  903. "numeric variable with name '" + Name + "' already exists");
  904. return true;
  905. }
  906. DefName = Name;
  907. MatchRegexp = MatchStr.str();
  908. } else {
  909. if (IsPseudo) {
  910. MatchStr = OrigMatchStr;
  911. IsLegacyLineExpr = IsNumBlock = true;
  912. } else
  913. SubstStr = Name;
  914. }
  915. }
  916. // Parse numeric substitution block.
  917. std::unique_ptr<Expression> ExpressionPointer;
  918. Optional<NumericVariable *> DefinedNumericVariable;
  919. if (IsNumBlock) {
  920. Expected<std::unique_ptr<Expression>> ParseResult =
  921. parseNumericSubstitutionBlock(MatchStr, DefinedNumericVariable,
  922. IsLegacyLineExpr, LineNumber, Context,
  923. SM);
  924. if (!ParseResult) {
  925. logAllUnhandledErrors(ParseResult.takeError(), errs());
  926. return true;
  927. }
  928. ExpressionPointer = std::move(*ParseResult);
  929. SubstNeeded = ExpressionPointer->getAST() != nullptr;
  930. if (DefinedNumericVariable) {
  931. IsDefinition = true;
  932. DefName = (*DefinedNumericVariable)->getName();
  933. }
  934. if (SubstNeeded)
  935. SubstStr = MatchStr;
  936. else {
  937. ExpressionFormat Format = ExpressionPointer->getFormat();
  938. MatchRegexp = cantFail(Format.getWildcardRegex());
  939. }
  940. }
  941. // Handle variable definition: [[<def>:(...)]] and [[#(...)<def>:(...)]].
  942. if (IsDefinition) {
  943. RegExStr += '(';
  944. ++SubstInsertIdx;
  945. if (IsNumBlock) {
  946. NumericVariableMatch NumericVariableDefinition = {
  947. *DefinedNumericVariable, CurParen};
  948. NumericVariableDefs[DefName] = NumericVariableDefinition;
  949. // This store is done here rather than in match() to allow
  950. // parseNumericVariableUse() to get the pointer to the class instance
  951. // of the right variable definition corresponding to a given numeric
  952. // variable use.
  953. Context->GlobalNumericVariableTable[DefName] =
  954. *DefinedNumericVariable;
  955. } else {
  956. VariableDefs[DefName] = CurParen;
  957. // Mark string variable as defined to detect collisions between
  958. // string and numeric variables in parseNumericVariableUse() and
  959. // defineCmdlineVariables() when the latter is created later than the
  960. // former. We cannot reuse GlobalVariableTable for this by populating
  961. // it with an empty string since we would then lose the ability to
  962. // detect the use of an undefined variable in match().
  963. Context->DefinedVariableTable[DefName] = true;
  964. }
  965. ++CurParen;
  966. }
  967. if (!MatchRegexp.empty() && AddRegExToRegEx(MatchRegexp, CurParen, SM))
  968. return true;
  969. if (IsDefinition)
  970. RegExStr += ')';
  971. // Handle substitutions: [[foo]] and [[#<foo expr>]].
  972. if (SubstNeeded) {
  973. // Handle substitution of string variables that were defined earlier on
  974. // the same line by emitting a backreference. Expressions do not
  975. // support substituting a numeric variable defined on the same line.
  976. if (!IsNumBlock && VariableDefs.find(SubstStr) != VariableDefs.end()) {
  977. unsigned CaptureParenGroup = VariableDefs[SubstStr];
  978. if (CaptureParenGroup < 1 || CaptureParenGroup > 9) {
  979. SM.PrintMessage(SMLoc::getFromPointer(SubstStr.data()),
  980. SourceMgr::DK_Error,
  981. "Can't back-reference more than 9 variables");
  982. return true;
  983. }
  984. AddBackrefToRegEx(CaptureParenGroup);
  985. } else {
  986. // Handle substitution of string variables ([[<var>]]) defined in
  987. // previous CHECK patterns, and substitution of expressions.
  988. Substitution *Substitution =
  989. IsNumBlock
  990. ? Context->makeNumericSubstitution(
  991. SubstStr, std::move(ExpressionPointer), SubstInsertIdx)
  992. : Context->makeStringSubstitution(SubstStr, SubstInsertIdx);
  993. Substitutions.push_back(Substitution);
  994. }
  995. }
  996. }
  997. // Handle fixed string matches.
  998. // Find the end, which is the start of the next regex.
  999. size_t FixedMatchEnd = PatternStr.find("{{");
  1000. FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
  1001. RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
  1002. PatternStr = PatternStr.substr(FixedMatchEnd);
  1003. }
  1004. if (MatchFullLinesHere) {
  1005. if (!Req.NoCanonicalizeWhiteSpace)
  1006. RegExStr += " *";
  1007. RegExStr += '$';
  1008. }
  1009. return false;
  1010. }
  1011. bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
  1012. Regex R(RS);
  1013. std::string Error;
  1014. if (!R.isValid(Error)) {
  1015. SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
  1016. "invalid regex: " + Error);
  1017. return true;
  1018. }
  1019. RegExStr += RS.str();
  1020. CurParen += R.getNumMatches();
  1021. return false;
  1022. }
  1023. void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
  1024. assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
  1025. std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
  1026. RegExStr += Backref;
  1027. }
  1028. Expected<size_t> Pattern::match(StringRef Buffer, size_t &MatchLen,
  1029. const SourceMgr &SM) const {
  1030. // If this is the EOF pattern, match it immediately.
  1031. if (CheckTy == Check::CheckEOF) {
  1032. MatchLen = 0;
  1033. return Buffer.size();
  1034. }
  1035. // If this is a fixed string pattern, just match it now.
  1036. if (!FixedStr.empty()) {
  1037. MatchLen = FixedStr.size();
  1038. size_t Pos =
  1039. IgnoreCase ? Buffer.find_lower(FixedStr) : Buffer.find(FixedStr);
  1040. if (Pos == StringRef::npos)
  1041. return make_error<NotFoundError>();
  1042. return Pos;
  1043. }
  1044. // Regex match.
  1045. // If there are substitutions, we need to create a temporary string with the
  1046. // actual value.
  1047. StringRef RegExToMatch = RegExStr;
  1048. std::string TmpStr;
  1049. if (!Substitutions.empty()) {
  1050. TmpStr = RegExStr;
  1051. if (LineNumber)
  1052. Context->LineVariable->setValue(ExpressionValue(*LineNumber));
  1053. size_t InsertOffset = 0;
  1054. // Substitute all string variables and expressions whose values are only
  1055. // now known. Use of string variables defined on the same line are handled
  1056. // by back-references.
  1057. for (const auto &Substitution : Substitutions) {
  1058. // Substitute and check for failure (e.g. use of undefined variable).
  1059. Expected<std::string> Value = Substitution->getResult();
  1060. if (!Value) {
  1061. // Convert to an ErrorDiagnostic to get location information. This is
  1062. // done here rather than PrintNoMatch since now we know which
  1063. // substitution block caused the overflow.
  1064. Error Err =
  1065. handleErrors(Value.takeError(), [&](const OverflowError &E) {
  1066. return ErrorDiagnostic::get(SM, Substitution->getFromString(),
  1067. "unable to substitute variable or "
  1068. "numeric expression: overflow error");
  1069. });
  1070. return std::move(Err);
  1071. }
  1072. // Plop it into the regex at the adjusted offset.
  1073. TmpStr.insert(TmpStr.begin() + Substitution->getIndex() + InsertOffset,
  1074. Value->begin(), Value->end());
  1075. InsertOffset += Value->size();
  1076. }
  1077. // Match the newly constructed regex.
  1078. RegExToMatch = TmpStr;
  1079. }
  1080. SmallVector<StringRef, 4> MatchInfo;
  1081. unsigned int Flags = Regex::Newline;
  1082. if (IgnoreCase)
  1083. Flags |= Regex::IgnoreCase;
  1084. if (!Regex(RegExToMatch, Flags).match(Buffer, &MatchInfo))
  1085. return make_error<NotFoundError>();
  1086. // Successful regex match.
  1087. assert(!MatchInfo.empty() && "Didn't get any match");
  1088. StringRef FullMatch = MatchInfo[0];
  1089. // If this defines any string variables, remember their values.
  1090. for (const auto &VariableDef : VariableDefs) {
  1091. assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
  1092. Context->GlobalVariableTable[VariableDef.first] =
  1093. MatchInfo[VariableDef.second];
  1094. }
  1095. // If this defines any numeric variables, remember their values.
  1096. for (const auto &NumericVariableDef : NumericVariableDefs) {
  1097. const NumericVariableMatch &NumericVariableMatch =
  1098. NumericVariableDef.getValue();
  1099. unsigned CaptureParenGroup = NumericVariableMatch.CaptureParenGroup;
  1100. assert(CaptureParenGroup < MatchInfo.size() && "Internal paren error");
  1101. NumericVariable *DefinedNumericVariable =
  1102. NumericVariableMatch.DefinedNumericVariable;
  1103. StringRef MatchedValue = MatchInfo[CaptureParenGroup];
  1104. ExpressionFormat Format = DefinedNumericVariable->getImplicitFormat();
  1105. Expected<ExpressionValue> Value =
  1106. Format.valueFromStringRepr(MatchedValue, SM);
  1107. if (!Value)
  1108. return Value.takeError();
  1109. DefinedNumericVariable->setValue(*Value, MatchedValue);
  1110. }
  1111. // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
  1112. // the required preceding newline, which is consumed by the pattern in the
  1113. // case of CHECK-EMPTY but not CHECK-NEXT.
  1114. size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
  1115. MatchLen = FullMatch.size() - MatchStartSkip;
  1116. return FullMatch.data() - Buffer.data() + MatchStartSkip;
  1117. }
  1118. unsigned Pattern::computeMatchDistance(StringRef Buffer) const {
  1119. // Just compute the number of matching characters. For regular expressions, we
  1120. // just compare against the regex itself and hope for the best.
  1121. //
  1122. // FIXME: One easy improvement here is have the regex lib generate a single
  1123. // example regular expression which matches, and use that as the example
  1124. // string.
  1125. StringRef ExampleString(FixedStr);
  1126. if (ExampleString.empty())
  1127. ExampleString = RegExStr;
  1128. // Only compare up to the first line in the buffer, or the string size.
  1129. StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
  1130. BufferPrefix = BufferPrefix.split('\n').first;
  1131. return BufferPrefix.edit_distance(ExampleString);
  1132. }
  1133. void Pattern::printSubstitutions(const SourceMgr &SM, StringRef Buffer,
  1134. SMRange Range,
  1135. FileCheckDiag::MatchType MatchTy,
  1136. std::vector<FileCheckDiag> *Diags) const {
  1137. // Print what we know about substitutions.
  1138. if (!Substitutions.empty()) {
  1139. for (const auto &Substitution : Substitutions) {
  1140. SmallString<256> Msg;
  1141. raw_svector_ostream OS(Msg);
  1142. Expected<std::string> MatchedValue = Substitution->getResult();
  1143. // Substitution failed or is not known at match time, print the undefined
  1144. // variables it uses.
  1145. if (!MatchedValue) {
  1146. bool UndefSeen = false;
  1147. handleAllErrors(
  1148. MatchedValue.takeError(), [](const NotFoundError &E) {},
  1149. // Handled in PrintNoMatch().
  1150. [](const ErrorDiagnostic &E) {},
  1151. // Handled in match().
  1152. [](const OverflowError &E) {},
  1153. [&](const UndefVarError &E) {
  1154. if (!UndefSeen) {
  1155. OS << "uses undefined variable(s):";
  1156. UndefSeen = true;
  1157. }
  1158. OS << " ";
  1159. E.log(OS);
  1160. });
  1161. } else {
  1162. // Substitution succeeded. Print substituted value.
  1163. OS << "with \"";
  1164. OS.write_escaped(Substitution->getFromString()) << "\" equal to \"";
  1165. OS.write_escaped(*MatchedValue) << "\"";
  1166. }
  1167. // We report only the start of the match/search range to suggest we are
  1168. // reporting the substitutions as set at the start of the match/search.
  1169. // Indicating a non-zero-length range might instead seem to imply that the
  1170. // substitution matches or was captured from exactly that range.
  1171. if (Diags)
  1172. Diags->emplace_back(SM, CheckTy, getLoc(), MatchTy,
  1173. SMRange(Range.Start, Range.Start), OS.str());
  1174. else
  1175. SM.PrintMessage(Range.Start, SourceMgr::DK_Note, OS.str());
  1176. }
  1177. }
  1178. }
  1179. void Pattern::printVariableDefs(const SourceMgr &SM,
  1180. FileCheckDiag::MatchType MatchTy,
  1181. std::vector<FileCheckDiag> *Diags) const {
  1182. if (VariableDefs.empty() && NumericVariableDefs.empty())
  1183. return;
  1184. // Build list of variable captures.
  1185. struct VarCapture {
  1186. StringRef Name;
  1187. SMRange Range;
  1188. };
  1189. SmallVector<VarCapture, 2> VarCaptures;
  1190. for (const auto &VariableDef : VariableDefs) {
  1191. VarCapture VC;
  1192. VC.Name = VariableDef.first;
  1193. StringRef Value = Context->GlobalVariableTable[VC.Name];
  1194. SMLoc Start = SMLoc::getFromPointer(Value.data());
  1195. SMLoc End = SMLoc::getFromPointer(Value.data() + Value.size());
  1196. VC.Range = SMRange(Start, End);
  1197. VarCaptures.push_back(VC);
  1198. }
  1199. for (const auto &VariableDef : NumericVariableDefs) {
  1200. VarCapture VC;
  1201. VC.Name = VariableDef.getKey();
  1202. StringRef StrValue = VariableDef.getValue()
  1203. .DefinedNumericVariable->getStringValue()
  1204. .getValue();
  1205. SMLoc Start = SMLoc::getFromPointer(StrValue.data());
  1206. SMLoc End = SMLoc::getFromPointer(StrValue.data() + StrValue.size());
  1207. VC.Range = SMRange(Start, End);
  1208. VarCaptures.push_back(VC);
  1209. }
  1210. // Sort variable captures by the order in which they matched the input.
  1211. // Ranges shouldn't be overlapping, so we can just compare the start.
  1212. llvm::sort(VarCaptures, [](const VarCapture &A, const VarCapture &B) {
  1213. assert(A.Range.Start != B.Range.Start &&
  1214. "unexpected overlapping variable captures");
  1215. return A.Range.Start.getPointer() < B.Range.Start.getPointer();
  1216. });
  1217. // Create notes for the sorted captures.
  1218. for (const VarCapture &VC : VarCaptures) {
  1219. SmallString<256> Msg;
  1220. raw_svector_ostream OS(Msg);
  1221. OS << "captured var \"" << VC.Name << "\"";
  1222. if (Diags)
  1223. Diags->emplace_back(SM, CheckTy, getLoc(), MatchTy, VC.Range, OS.str());
  1224. else
  1225. SM.PrintMessage(VC.Range.Start, SourceMgr::DK_Note, OS.str(), VC.Range);
  1226. }
  1227. }
  1228. static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
  1229. const SourceMgr &SM, SMLoc Loc,
  1230. Check::FileCheckType CheckTy,
  1231. StringRef Buffer, size_t Pos, size_t Len,
  1232. std::vector<FileCheckDiag> *Diags,
  1233. bool AdjustPrevDiags = false) {
  1234. SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
  1235. SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
  1236. SMRange Range(Start, End);
  1237. if (Diags) {
  1238. if (AdjustPrevDiags) {
  1239. SMLoc CheckLoc = Diags->rbegin()->CheckLoc;
  1240. for (auto I = Diags->rbegin(), E = Diags->rend();
  1241. I != E && I->CheckLoc == CheckLoc; ++I)
  1242. I->MatchTy = MatchTy;
  1243. } else
  1244. Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
  1245. }
  1246. return Range;
  1247. }
  1248. void Pattern::printFuzzyMatch(const SourceMgr &SM, StringRef Buffer,
  1249. std::vector<FileCheckDiag> *Diags) const {
  1250. // Attempt to find the closest/best fuzzy match. Usually an error happens
  1251. // because some string in the output didn't exactly match. In these cases, we
  1252. // would like to show the user a best guess at what "should have" matched, to
  1253. // save them having to actually check the input manually.
  1254. size_t NumLinesForward = 0;
  1255. size_t Best = StringRef::npos;
  1256. double BestQuality = 0;
  1257. // Use an arbitrary 4k limit on how far we will search.
  1258. for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
  1259. if (Buffer[i] == '\n')
  1260. ++NumLinesForward;
  1261. // Patterns have leading whitespace stripped, so skip whitespace when
  1262. // looking for something which looks like a pattern.
  1263. if (Buffer[i] == ' ' || Buffer[i] == '\t')
  1264. continue;
  1265. // Compute the "quality" of this match as an arbitrary combination of the
  1266. // match distance and the number of lines skipped to get to this match.
  1267. unsigned Distance = computeMatchDistance(Buffer.substr(i));
  1268. double Quality = Distance + (NumLinesForward / 100.);
  1269. if (Quality < BestQuality || Best == StringRef::npos) {
  1270. Best = i;
  1271. BestQuality = Quality;
  1272. }
  1273. }
  1274. // Print the "possible intended match here" line if we found something
  1275. // reasonable and not equal to what we showed in the "scanning from here"
  1276. // line.
  1277. if (Best && Best != StringRef::npos && BestQuality < 50) {
  1278. SMRange MatchRange =
  1279. ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
  1280. getCheckTy(), Buffer, Best, 0, Diags);
  1281. SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
  1282. "possible intended match here");
  1283. // FIXME: If we wanted to be really friendly we would show why the match
  1284. // failed, as it can be hard to spot simple one character differences.
  1285. }
  1286. }
  1287. Expected<StringRef>
  1288. FileCheckPatternContext::getPatternVarValue(StringRef VarName) {
  1289. auto VarIter = GlobalVariableTable.find(VarName);
  1290. if (VarIter == GlobalVariableTable.end())
  1291. return make_error<UndefVarError>(VarName);
  1292. return VarIter->second;
  1293. }
  1294. template <class... Types>
  1295. NumericVariable *FileCheckPatternContext::makeNumericVariable(Types... args) {
  1296. NumericVariables.push_back(std::make_unique<NumericVariable>(args...));
  1297. return NumericVariables.back().get();
  1298. }
  1299. Substitution *
  1300. FileCheckPatternContext::makeStringSubstitution(StringRef VarName,
  1301. size_t InsertIdx) {
  1302. Substitutions.push_back(
  1303. std::make_unique<StringSubstitution>(this, VarName, InsertIdx));
  1304. return Substitutions.back().get();
  1305. }
  1306. Substitution *FileCheckPatternContext::makeNumericSubstitution(
  1307. StringRef ExpressionStr, std::unique_ptr<Expression> Expression,
  1308. size_t InsertIdx) {
  1309. Substitutions.push_back(std::make_unique<NumericSubstitution>(
  1310. this, ExpressionStr, std::move(Expression), InsertIdx));
  1311. return Substitutions.back().get();
  1312. }
  1313. size_t Pattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
  1314. // Offset keeps track of the current offset within the input Str
  1315. size_t Offset = 0;
  1316. // [...] Nesting depth
  1317. size_t BracketDepth = 0;
  1318. while (!Str.empty()) {
  1319. if (Str.startswith("]]") && BracketDepth == 0)
  1320. return Offset;
  1321. if (Str[0] == '\\') {
  1322. // Backslash escapes the next char within regexes, so skip them both.
  1323. Str = Str.substr(2);
  1324. Offset += 2;
  1325. } else {
  1326. switch (Str[0]) {
  1327. default:
  1328. break;
  1329. case '[':
  1330. BracketDepth++;
  1331. break;
  1332. case ']':
  1333. if (BracketDepth == 0) {
  1334. SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
  1335. SourceMgr::DK_Error,
  1336. "missing closing \"]\" for regex variable");
  1337. exit(1);
  1338. }
  1339. BracketDepth--;
  1340. break;
  1341. }
  1342. Str = Str.substr(1);
  1343. Offset++;
  1344. }
  1345. }
  1346. return StringRef::npos;
  1347. }
  1348. StringRef FileCheck::CanonicalizeFile(MemoryBuffer &MB,
  1349. SmallVectorImpl<char> &OutputBuffer) {
  1350. OutputBuffer.reserve(MB.getBufferSize());
  1351. for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
  1352. Ptr != End; ++Ptr) {
  1353. // Eliminate trailing dosish \r.
  1354. if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
  1355. continue;
  1356. }
  1357. // If current char is not a horizontal whitespace or if horizontal
  1358. // whitespace canonicalization is disabled, dump it to output as is.
  1359. if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
  1360. OutputBuffer.push_back(*Ptr);
  1361. continue;
  1362. }
  1363. // Otherwise, add one space and advance over neighboring space.
  1364. OutputBuffer.push_back(' ');
  1365. while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
  1366. ++Ptr;
  1367. }
  1368. // Add a null byte and then return all but that byte.
  1369. OutputBuffer.push_back('\0');
  1370. return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
  1371. }
  1372. FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
  1373. const Check::FileCheckType &CheckTy,
  1374. SMLoc CheckLoc, MatchType MatchTy,
  1375. SMRange InputRange, StringRef Note)
  1376. : CheckTy(CheckTy), CheckLoc(CheckLoc), MatchTy(MatchTy), Note(Note) {
  1377. auto Start = SM.getLineAndColumn(InputRange.Start);
  1378. auto End = SM.getLineAndColumn(InputRange.End);
  1379. InputStartLine = Start.first;
  1380. InputStartCol = Start.second;
  1381. InputEndLine = End.first;
  1382. InputEndCol = End.second;
  1383. }
  1384. static bool IsPartOfWord(char c) {
  1385. return (isAlnum(c) || c == '-' || c == '_');
  1386. }
  1387. Check::FileCheckType &Check::FileCheckType::setCount(int C) {
  1388. assert(Count > 0 && "zero and negative counts are not supported");
  1389. assert((C == 1 || Kind == CheckPlain) &&
  1390. "count supported only for plain CHECK directives");
  1391. Count = C;
  1392. return *this;
  1393. }
  1394. std::string Check::FileCheckType::getModifiersDescription() const {
  1395. if (Modifiers.none())
  1396. return "";
  1397. std::string Ret;
  1398. raw_string_ostream OS(Ret);
  1399. OS << '{';
  1400. if (isLiteralMatch())
  1401. OS << "LITERAL";
  1402. OS << '}';
  1403. return OS.str();
  1404. }
  1405. std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
  1406. // Append directive modifiers.
  1407. auto WithModifiers = [this, Prefix](StringRef Str) -> std::string {
  1408. return (Prefix + Str + getModifiersDescription()).str();
  1409. };
  1410. switch (Kind) {
  1411. case Check::CheckNone:
  1412. return "invalid";
  1413. case Check::CheckPlain:
  1414. if (Count > 1)
  1415. return WithModifiers("-COUNT");
  1416. return WithModifiers("");
  1417. case Check::CheckNext:
  1418. return WithModifiers("-NEXT");
  1419. case Check::CheckSame:
  1420. return WithModifiers("-SAME");
  1421. case Check::CheckNot:
  1422. return WithModifiers("-NOT");
  1423. case Check::CheckDAG:
  1424. return WithModifiers("-DAG");
  1425. case Check::CheckLabel:
  1426. return WithModifiers("-LABEL");
  1427. case Check::CheckEmpty:
  1428. return WithModifiers("-EMPTY");
  1429. case Check::CheckComment:
  1430. return std::string(Prefix);
  1431. case Check::CheckEOF:
  1432. return "implicit EOF";
  1433. case Check::CheckBadNot:
  1434. return "bad NOT";
  1435. case Check::CheckBadCount:
  1436. return "bad COUNT";
  1437. }
  1438. llvm_unreachable("unknown FileCheckType");
  1439. }
  1440. static std::pair<Check::FileCheckType, StringRef>
  1441. FindCheckType(const FileCheckRequest &Req, StringRef Buffer, StringRef Prefix) {
  1442. if (Buffer.size() <= Prefix.size())
  1443. return {Check::CheckNone, StringRef()};
  1444. StringRef Rest = Buffer.drop_front(Prefix.size());
  1445. // Check for comment.
  1446. if (llvm::is_contained(Req.CommentPrefixes, Prefix)) {
  1447. if (Rest.consume_front(":"))
  1448. return {Check::CheckComment, Rest};
  1449. // Ignore a comment prefix if it has a suffix like "-NOT".
  1450. return {Check::CheckNone, StringRef()};
  1451. }
  1452. auto ConsumeModifiers = [&](Check::FileCheckType Ret)
  1453. -> std::pair<Check::FileCheckType, StringRef> {
  1454. if (Rest.consume_front(":"))
  1455. return {Ret, Rest};
  1456. if (!Rest.consume_front("{"))
  1457. return {Check::CheckNone, StringRef()};
  1458. // Parse the modifiers, speparated by commas.
  1459. do {
  1460. // Allow whitespace in modifiers list.
  1461. Rest = Rest.ltrim();
  1462. if (Rest.consume_front("LITERAL"))
  1463. Ret.setLiteralMatch();
  1464. else
  1465. return {Check::CheckNone, Rest};
  1466. // Allow whitespace in modifiers list.
  1467. Rest = Rest.ltrim();
  1468. } while (Rest.consume_front(","));
  1469. if (!Rest.consume_front("}:"))
  1470. return {Check::CheckNone, Rest};
  1471. return {Ret, Rest};
  1472. };
  1473. // Verify that the prefix is followed by directive modifiers or a colon.
  1474. if (Rest.consume_front(":"))
  1475. return {Check::CheckPlain, Rest};
  1476. if (Rest.front() == '{')
  1477. return ConsumeModifiers(Check::CheckPlain);
  1478. if (!Rest.consume_front("-"))
  1479. return {Check::CheckNone, StringRef()};
  1480. if (Rest.consume_front("COUNT-")) {
  1481. int64_t Count;
  1482. if (Rest.consumeInteger(10, Count))
  1483. // Error happened in parsing integer.
  1484. return {Check::CheckBadCount, Rest};
  1485. if (Count <= 0 || Count > INT32_MAX)
  1486. return {Check::CheckBadCount, Rest};
  1487. if (Rest.front() != ':' && Rest.front() != '{')
  1488. return {Check::CheckBadCount, Rest};
  1489. return ConsumeModifiers(
  1490. Check::FileCheckType(Check::CheckPlain).setCount(Count));
  1491. }
  1492. // You can't combine -NOT with another suffix.
  1493. if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
  1494. Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
  1495. Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
  1496. Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
  1497. return {Check::CheckBadNot, Rest};
  1498. if (Rest.consume_front("NEXT"))
  1499. return ConsumeModifiers(Check::CheckNext);
  1500. if (Rest.consume_front("SAME"))
  1501. return ConsumeModifiers(Check::CheckSame);
  1502. if (Rest.consume_front("NOT"))
  1503. return ConsumeModifiers(Check::CheckNot);
  1504. if (Rest.consume_front("DAG"))
  1505. return ConsumeModifiers(Check::CheckDAG);
  1506. if (Rest.consume_front("LABEL"))
  1507. return ConsumeModifiers(Check::CheckLabel);
  1508. if (Rest.consume_front("EMPTY"))
  1509. return ConsumeModifiers(Check::CheckEmpty);
  1510. return {Check::CheckNone, Rest};
  1511. }
  1512. // From the given position, find the next character after the word.
  1513. static size_t SkipWord(StringRef Str, size_t Loc) {
  1514. while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
  1515. ++Loc;
  1516. return Loc;
  1517. }
  1518. /// Searches the buffer for the first prefix in the prefix regular expression.
  1519. ///
  1520. /// This searches the buffer using the provided regular expression, however it
  1521. /// enforces constraints beyond that:
  1522. /// 1) The found prefix must not be a suffix of something that looks like
  1523. /// a valid prefix.
  1524. /// 2) The found prefix must be followed by a valid check type suffix using \c
  1525. /// FindCheckType above.
  1526. ///
  1527. /// \returns a pair of StringRefs into the Buffer, which combines:
  1528. /// - the first match of the regular expression to satisfy these two is
  1529. /// returned,
  1530. /// otherwise an empty StringRef is returned to indicate failure.
  1531. /// - buffer rewound to the location right after parsed suffix, for parsing
  1532. /// to continue from
  1533. ///
  1534. /// If this routine returns a valid prefix, it will also shrink \p Buffer to
  1535. /// start at the beginning of the returned prefix, increment \p LineNumber for
  1536. /// each new line consumed from \p Buffer, and set \p CheckTy to the type of
  1537. /// check found by examining the suffix.
  1538. ///
  1539. /// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
  1540. /// is unspecified.
  1541. static std::pair<StringRef, StringRef>
  1542. FindFirstMatchingPrefix(const FileCheckRequest &Req, Regex &PrefixRE,
  1543. StringRef &Buffer, unsigned &LineNumber,
  1544. Check::FileCheckType &CheckTy) {
  1545. SmallVector<StringRef, 2> Matches;
  1546. while (!Buffer.empty()) {
  1547. // Find the first (longest) match using the RE.
  1548. if (!PrefixRE.match(Buffer, &Matches))
  1549. // No match at all, bail.
  1550. return {StringRef(), StringRef()};
  1551. StringRef Prefix = Matches[0];
  1552. Matches.clear();
  1553. assert(Prefix.data() >= Buffer.data() &&
  1554. Prefix.data() < Buffer.data() + Buffer.size() &&
  1555. "Prefix doesn't start inside of buffer!");
  1556. size_t Loc = Prefix.data() - Buffer.data();
  1557. StringRef Skipped = Buffer.substr(0, Loc);
  1558. Buffer = Buffer.drop_front(Loc);
  1559. LineNumber += Skipped.count('\n');
  1560. // Check that the matched prefix isn't a suffix of some other check-like
  1561. // word.
  1562. // FIXME: This is a very ad-hoc check. it would be better handled in some
  1563. // other way. Among other things it seems hard to distinguish between
  1564. // intentional and unintentional uses of this feature.
  1565. if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
  1566. // Now extract the type.
  1567. StringRef AfterSuffix;
  1568. std::tie(CheckTy, AfterSuffix) = FindCheckType(Req, Buffer, Prefix);
  1569. // If we've found a valid check type for this prefix, we're done.
  1570. if (CheckTy != Check::CheckNone)
  1571. return {Prefix, AfterSuffix};
  1572. }
  1573. // If we didn't successfully find a prefix, we need to skip this invalid
  1574. // prefix and continue scanning. We directly skip the prefix that was
  1575. // matched and any additional parts of that check-like word.
  1576. Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
  1577. }
  1578. // We ran out of buffer while skipping partial matches so give up.
  1579. return {StringRef(), StringRef()};
  1580. }
  1581. void FileCheckPatternContext::createLineVariable() {
  1582. assert(!LineVariable && "@LINE pseudo numeric variable already created");
  1583. StringRef LineName = "@LINE";
  1584. LineVariable = makeNumericVariable(
  1585. LineName, ExpressionFormat(ExpressionFormat::Kind::Unsigned));
  1586. GlobalNumericVariableTable[LineName] = LineVariable;
  1587. }
  1588. FileCheck::FileCheck(FileCheckRequest Req)
  1589. : Req(Req), PatternContext(std::make_unique<FileCheckPatternContext>()),
  1590. CheckStrings(std::make_unique<std::vector<FileCheckString>>()) {}
  1591. FileCheck::~FileCheck() = default;
  1592. bool FileCheck::readCheckFile(
  1593. SourceMgr &SM, StringRef Buffer, Regex &PrefixRE,
  1594. std::pair<unsigned, unsigned> *ImpPatBufferIDRange) {
  1595. if (ImpPatBufferIDRange)
  1596. ImpPatBufferIDRange->first = ImpPatBufferIDRange->second = 0;
  1597. Error DefineError =
  1598. PatternContext->defineCmdlineVariables(Req.GlobalDefines, SM);
  1599. if (DefineError) {
  1600. logAllUnhandledErrors(std::move(DefineError), errs());
  1601. return true;
  1602. }
  1603. PatternContext->createLineVariable();
  1604. std::vector<Pattern> ImplicitNegativeChecks;
  1605. for (StringRef PatternString : Req.ImplicitCheckNot) {
  1606. // Create a buffer with fake command line content in order to display the
  1607. // command line option responsible for the specific implicit CHECK-NOT.
  1608. std::string Prefix = "-implicit-check-not='";
  1609. std::string Suffix = "'";
  1610. std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
  1611. (Prefix + PatternString + Suffix).str(), "command line");
  1612. StringRef PatternInBuffer =
  1613. CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
  1614. unsigned BufferID = SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
  1615. if (ImpPatBufferIDRange) {
  1616. if (ImpPatBufferIDRange->first == ImpPatBufferIDRange->second) {
  1617. ImpPatBufferIDRange->first = BufferID;
  1618. ImpPatBufferIDRange->second = BufferID + 1;
  1619. } else {
  1620. assert(BufferID == ImpPatBufferIDRange->second &&
  1621. "expected consecutive source buffer IDs");
  1622. ++ImpPatBufferIDRange->second;
  1623. }
  1624. }
  1625. ImplicitNegativeChecks.push_back(
  1626. Pattern(Check::CheckNot, PatternContext.get()));
  1627. ImplicitNegativeChecks.back().parsePattern(PatternInBuffer,
  1628. "IMPLICIT-CHECK", SM, Req);
  1629. }
  1630. std::vector<Pattern> DagNotMatches = ImplicitNegativeChecks;
  1631. // LineNumber keeps track of the line on which CheckPrefix instances are
  1632. // found.
  1633. unsigned LineNumber = 1;
  1634. std::set<StringRef> PrefixesNotFound(Req.CheckPrefixes.begin(),
  1635. Req.CheckPrefixes.end());
  1636. const size_t DistinctPrefixes = PrefixesNotFound.size();
  1637. while (true) {
  1638. Check::FileCheckType CheckTy;
  1639. // See if a prefix occurs in the memory buffer.
  1640. StringRef UsedPrefix;
  1641. StringRef AfterSuffix;
  1642. std::tie(UsedPrefix, AfterSuffix) =
  1643. FindFirstMatchingPrefix(Req, PrefixRE, Buffer, LineNumber, CheckTy);
  1644. if (UsedPrefix.empty())
  1645. break;
  1646. if (CheckTy != Check::CheckComment)
  1647. PrefixesNotFound.erase(UsedPrefix);
  1648. assert(UsedPrefix.data() == Buffer.data() &&
  1649. "Failed to move Buffer's start forward, or pointed prefix outside "
  1650. "of the buffer!");
  1651. assert(AfterSuffix.data() >= Buffer.data() &&
  1652. AfterSuffix.data() < Buffer.data() + Buffer.size() &&
  1653. "Parsing after suffix doesn't start inside of buffer!");
  1654. // Location to use for error messages.
  1655. const char *UsedPrefixStart = UsedPrefix.data();
  1656. // Skip the buffer to the end of parsed suffix (or just prefix, if no good
  1657. // suffix was processed).
  1658. Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
  1659. : AfterSuffix;
  1660. // Complain about useful-looking but unsupported suffixes.
  1661. if (CheckTy == Check::CheckBadNot) {
  1662. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
  1663. "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
  1664. return true;
  1665. }
  1666. // Complain about invalid count specification.
  1667. if (CheckTy == Check::CheckBadCount) {
  1668. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Error,
  1669. "invalid count in -COUNT specification on prefix '" +
  1670. UsedPrefix + "'");
  1671. return true;
  1672. }
  1673. // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
  1674. // leading whitespace.
  1675. if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
  1676. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
  1677. // Scan ahead to the end of line.
  1678. size_t EOL = Buffer.find_first_of("\n\r");
  1679. // Remember the location of the start of the pattern, for diagnostics.
  1680. SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
  1681. // Extract the pattern from the buffer.
  1682. StringRef PatternBuffer = Buffer.substr(0, EOL);
  1683. Buffer = Buffer.substr(EOL);
  1684. // If this is a comment, we're done.
  1685. if (CheckTy == Check::CheckComment)
  1686. continue;
  1687. // Parse the pattern.
  1688. Pattern P(CheckTy, PatternContext.get(), LineNumber);
  1689. if (P.parsePattern(PatternBuffer, UsedPrefix, SM, Req))
  1690. return true;
  1691. // Verify that CHECK-LABEL lines do not define or use variables
  1692. if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
  1693. SM.PrintMessage(
  1694. SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
  1695. "found '" + UsedPrefix + "-LABEL:'"
  1696. " with variable definition or use");
  1697. return true;
  1698. }
  1699. // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
  1700. if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
  1701. CheckTy == Check::CheckEmpty) &&
  1702. CheckStrings->empty()) {
  1703. StringRef Type = CheckTy == Check::CheckNext
  1704. ? "NEXT"
  1705. : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
  1706. SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
  1707. SourceMgr::DK_Error,
  1708. "found '" + UsedPrefix + "-" + Type +
  1709. "' without previous '" + UsedPrefix + ": line");
  1710. return true;
  1711. }
  1712. // Handle CHECK-DAG/-NOT.
  1713. if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
  1714. DagNotMatches.push_back(P);
  1715. continue;
  1716. }
  1717. // Okay, add the string we captured to the output vector and move on.
  1718. CheckStrings->emplace_back(P, UsedPrefix, PatternLoc);
  1719. std::swap(DagNotMatches, CheckStrings->back().DagNotStrings);
  1720. DagNotMatches = ImplicitNegativeChecks;
  1721. }
  1722. // When there are no used prefixes we report an error except in the case that
  1723. // no prefix is specified explicitly but -implicit-check-not is specified.
  1724. const bool NoPrefixesFound = PrefixesNotFound.size() == DistinctPrefixes;
  1725. const bool SomePrefixesUnexpectedlyNotUsed =
  1726. !Req.AllowUnusedPrefixes && !PrefixesNotFound.empty();
  1727. if ((NoPrefixesFound || SomePrefixesUnexpectedlyNotUsed) &&
  1728. (ImplicitNegativeChecks.empty() || !Req.IsDefaultCheckPrefix)) {
  1729. errs() << "error: no check strings found with prefix"
  1730. << (PrefixesNotFound.size() > 1 ? "es " : " ");
  1731. bool First = true;
  1732. for (StringRef MissingPrefix : PrefixesNotFound) {
  1733. if (!First)
  1734. errs() << ", ";
  1735. errs() << "\'" << MissingPrefix << ":'";
  1736. First = false;
  1737. }
  1738. errs() << '\n';
  1739. return true;
  1740. }
  1741. // Add an EOF pattern for any trailing --implicit-check-not/CHECK-DAG/-NOTs,
  1742. // and use the first prefix as a filler for the error message.
  1743. if (!DagNotMatches.empty()) {
  1744. CheckStrings->emplace_back(
  1745. Pattern(Check::CheckEOF, PatternContext.get(), LineNumber + 1),
  1746. *Req.CheckPrefixes.begin(), SMLoc::getFromPointer(Buffer.data()));
  1747. std::swap(DagNotMatches, CheckStrings->back().DagNotStrings);
  1748. }
  1749. return false;
  1750. }
  1751. static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
  1752. StringRef Prefix, SMLoc Loc, const Pattern &Pat,
  1753. int MatchedCount, StringRef Buffer, size_t MatchPos,
  1754. size_t MatchLen, const FileCheckRequest &Req,
  1755. std::vector<FileCheckDiag> *Diags) {
  1756. bool PrintDiag = true;
  1757. if (ExpectedMatch) {
  1758. if (!Req.Verbose)
  1759. return;
  1760. if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
  1761. return;
  1762. // Due to their verbosity, we don't print verbose diagnostics here if we're
  1763. // gathering them for a different rendering, but we always print other
  1764. // diagnostics.
  1765. PrintDiag = !Diags;
  1766. }
  1767. FileCheckDiag::MatchType MatchTy = ExpectedMatch
  1768. ? FileCheckDiag::MatchFoundAndExpected
  1769. : FileCheckDiag::MatchFoundButExcluded;
  1770. SMRange MatchRange = ProcessMatchResult(MatchTy, SM, Loc, Pat.getCheckTy(),
  1771. Buffer, MatchPos, MatchLen, Diags);
  1772. if (Diags) {
  1773. Pat.printSubstitutions(SM, Buffer, MatchRange, MatchTy, Diags);
  1774. Pat.printVariableDefs(SM, MatchTy, Diags);
  1775. }
  1776. if (!PrintDiag)
  1777. return;
  1778. std::string Message = formatv("{0}: {1} string found in input",
  1779. Pat.getCheckTy().getDescription(Prefix),
  1780. (ExpectedMatch ? "expected" : "excluded"))
  1781. .str();
  1782. if (Pat.getCount() > 1)
  1783. Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
  1784. SM.PrintMessage(
  1785. Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
  1786. SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
  1787. {MatchRange});
  1788. Pat.printSubstitutions(SM, Buffer, MatchRange, MatchTy, nullptr);
  1789. Pat.printVariableDefs(SM, MatchTy, nullptr);
  1790. }
  1791. static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
  1792. const FileCheckString &CheckStr, int MatchedCount,
  1793. StringRef Buffer, size_t MatchPos, size_t MatchLen,
  1794. FileCheckRequest &Req,
  1795. std::vector<FileCheckDiag> *Diags) {
  1796. PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
  1797. MatchedCount, Buffer, MatchPos, MatchLen, Req, Diags);
  1798. }
  1799. static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
  1800. StringRef Prefix, SMLoc Loc, const Pattern &Pat,
  1801. int MatchedCount, StringRef Buffer,
  1802. bool VerboseVerbose, std::vector<FileCheckDiag> *Diags,
  1803. Error MatchErrors) {
  1804. assert(MatchErrors && "Called on successful match");
  1805. bool PrintDiag = true;
  1806. if (!ExpectedMatch) {
  1807. if (!VerboseVerbose) {
  1808. consumeError(std::move(MatchErrors));
  1809. return;
  1810. }
  1811. // Due to their verbosity, we don't print verbose diagnostics here if we're
  1812. // gathering them for a different rendering, but we always print other
  1813. // diagnostics.
  1814. PrintDiag = !Diags;
  1815. }
  1816. // If the current position is at the end of a line, advance to the start of
  1817. // the next line.
  1818. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
  1819. FileCheckDiag::MatchType MatchTy = ExpectedMatch
  1820. ? FileCheckDiag::MatchNoneButExpected
  1821. : FileCheckDiag::MatchNoneAndExcluded;
  1822. SMRange SearchRange = ProcessMatchResult(MatchTy, SM, Loc, Pat.getCheckTy(),
  1823. Buffer, 0, Buffer.size(), Diags);
  1824. if (Diags)
  1825. Pat.printSubstitutions(SM, Buffer, SearchRange, MatchTy, Diags);
  1826. if (!PrintDiag) {
  1827. consumeError(std::move(MatchErrors));
  1828. return;
  1829. }
  1830. MatchErrors = handleErrors(std::move(MatchErrors),
  1831. [](const ErrorDiagnostic &E) { E.log(errs()); });
  1832. // No problem matching the string per se.
  1833. if (!MatchErrors)
  1834. return;
  1835. consumeError(std::move(MatchErrors));
  1836. // Print "not found" diagnostic.
  1837. std::string Message = formatv("{0}: {1} string not found in input",
  1838. Pat.getCheckTy().getDescription(Prefix),
  1839. (ExpectedMatch ? "expected" : "excluded"))
  1840. .str();
  1841. if (Pat.getCount() > 1)
  1842. Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
  1843. SM.PrintMessage(
  1844. Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
  1845. // Print the "scanning from here" line.
  1846. SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
  1847. // Allow the pattern to print additional information if desired.
  1848. Pat.printSubstitutions(SM, Buffer, SearchRange, MatchTy, nullptr);
  1849. if (ExpectedMatch)
  1850. Pat.printFuzzyMatch(SM, Buffer, Diags);
  1851. }
  1852. static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
  1853. const FileCheckString &CheckStr, int MatchedCount,
  1854. StringRef Buffer, bool VerboseVerbose,
  1855. std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
  1856. PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
  1857. MatchedCount, Buffer, VerboseVerbose, Diags,
  1858. std::move(MatchErrors));
  1859. }
  1860. /// Counts the number of newlines in the specified range.
  1861. static unsigned CountNumNewlinesBetween(StringRef Range,
  1862. const char *&FirstNewLine) {
  1863. unsigned NumNewLines = 0;
  1864. while (1) {
  1865. // Scan for newline.
  1866. Range = Range.substr(Range.find_first_of("\n\r"));
  1867. if (Range.empty())
  1868. return NumNewLines;
  1869. ++NumNewLines;
  1870. // Handle \n\r and \r\n as a single newline.
  1871. if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
  1872. (Range[0] != Range[1]))
  1873. Range = Range.substr(1);
  1874. Range = Range.substr(1);
  1875. if (NumNewLines == 1)
  1876. FirstNewLine = Range.begin();
  1877. }
  1878. }
  1879. size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
  1880. bool IsLabelScanMode, size_t &MatchLen,
  1881. FileCheckRequest &Req,
  1882. std::vector<FileCheckDiag> *Diags) const {
  1883. size_t LastPos = 0;
  1884. std::vector<const Pattern *> NotStrings;
  1885. // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
  1886. // bounds; we have not processed variable definitions within the bounded block
  1887. // yet so cannot handle any final CHECK-DAG yet; this is handled when going
  1888. // over the block again (including the last CHECK-LABEL) in normal mode.
  1889. if (!IsLabelScanMode) {
  1890. // Match "dag strings" (with mixed "not strings" if any).
  1891. LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
  1892. if (LastPos == StringRef::npos)
  1893. return StringRef::npos;
  1894. }
  1895. // Match itself from the last position after matching CHECK-DAG.
  1896. size_t LastMatchEnd = LastPos;
  1897. size_t FirstMatchPos = 0;
  1898. // Go match the pattern Count times. Majority of patterns only match with
  1899. // count 1 though.
  1900. assert(Pat.getCount() != 0 && "pattern count can not be zero");
  1901. for (int i = 1; i <= Pat.getCount(); i++) {
  1902. StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
  1903. size_t CurrentMatchLen;
  1904. // get a match at current start point
  1905. Expected<size_t> MatchResult = Pat.match(MatchBuffer, CurrentMatchLen, SM);
  1906. // report
  1907. if (!MatchResult) {
  1908. PrintNoMatch(true, SM, *this, i, MatchBuffer, Req.VerboseVerbose, Diags,
  1909. MatchResult.takeError());
  1910. return StringRef::npos;
  1911. }
  1912. size_t MatchPos = *MatchResult;
  1913. PrintMatch(true, SM, *this, i, MatchBuffer, MatchPos, CurrentMatchLen, Req,
  1914. Diags);
  1915. if (i == 1)
  1916. FirstMatchPos = LastPos + MatchPos;
  1917. // move start point after the match
  1918. LastMatchEnd += MatchPos + CurrentMatchLen;
  1919. }
  1920. // Full match len counts from first match pos.
  1921. MatchLen = LastMatchEnd - FirstMatchPos;
  1922. // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
  1923. // or CHECK-NOT
  1924. if (!IsLabelScanMode) {
  1925. size_t MatchPos = FirstMatchPos - LastPos;
  1926. StringRef MatchBuffer = Buffer.substr(LastPos);
  1927. StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
  1928. // If this check is a "CHECK-NEXT", verify that the previous match was on
  1929. // the previous line (i.e. that there is one newline between them).
  1930. if (CheckNext(SM, SkippedRegion)) {
  1931. ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
  1932. Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
  1933. Diags, Req.Verbose);
  1934. return StringRef::npos;
  1935. }
  1936. // If this check is a "CHECK-SAME", verify that the previous match was on
  1937. // the same line (i.e. that there is no newline between them).
  1938. if (CheckSame(SM, SkippedRegion)) {
  1939. ProcessMatchResult(FileCheckDiag::MatchFoundButWrongLine, SM, Loc,
  1940. Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
  1941. Diags, Req.Verbose);
  1942. return StringRef::npos;
  1943. }
  1944. // If this match had "not strings", verify that they don't exist in the
  1945. // skipped region.
  1946. if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
  1947. return StringRef::npos;
  1948. }
  1949. return FirstMatchPos;
  1950. }
  1951. bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
  1952. if (Pat.getCheckTy() != Check::CheckNext &&
  1953. Pat.getCheckTy() != Check::CheckEmpty)
  1954. return false;
  1955. Twine CheckName =
  1956. Prefix +
  1957. Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
  1958. // Count the number of newlines between the previous match and this one.
  1959. const char *FirstNewLine = nullptr;
  1960. unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
  1961. if (NumNewLines == 0) {
  1962. SM.PrintMessage(Loc, SourceMgr::DK_Error,
  1963. CheckName + ": is on the same line as previous match");
  1964. SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
  1965. "'next' match was here");
  1966. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
  1967. "previous match ended here");
  1968. return true;
  1969. }
  1970. if (NumNewLines != 1) {
  1971. SM.PrintMessage(Loc, SourceMgr::DK_Error,
  1972. CheckName +
  1973. ": is not on the line after the previous match");
  1974. SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
  1975. "'next' match was here");
  1976. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
  1977. "previous match ended here");
  1978. SM.PrintMessage(SMLoc::getFromPointer(FirstNewLine), SourceMgr::DK_Note,
  1979. "non-matching line after previous match is here");
  1980. return true;
  1981. }
  1982. return false;
  1983. }
  1984. bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
  1985. if (Pat.getCheckTy() != Check::CheckSame)
  1986. return false;
  1987. // Count the number of newlines between the previous match and this one.
  1988. const char *FirstNewLine = nullptr;
  1989. unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
  1990. if (NumNewLines != 0) {
  1991. SM.PrintMessage(Loc, SourceMgr::DK_Error,
  1992. Prefix +
  1993. "-SAME: is not on the same line as the previous match");
  1994. SM.PrintMessage(SMLoc::getFromPointer(Buffer.end()), SourceMgr::DK_Note,
  1995. "'next' match was here");
  1996. SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
  1997. "previous match ended here");
  1998. return true;
  1999. }
  2000. return false;
  2001. }
  2002. bool FileCheckString::CheckNot(const SourceMgr &SM, StringRef Buffer,
  2003. const std::vector<const Pattern *> &NotStrings,
  2004. const FileCheckRequest &Req,
  2005. std::vector<FileCheckDiag> *Diags) const {
  2006. bool DirectiveFail = false;
  2007. for (const Pattern *Pat : NotStrings) {
  2008. assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
  2009. size_t MatchLen = 0;
  2010. Expected<size_t> MatchResult = Pat->match(Buffer, MatchLen, SM);
  2011. if (!MatchResult) {
  2012. PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
  2013. Req.VerboseVerbose, Diags, MatchResult.takeError());
  2014. continue;
  2015. }
  2016. size_t Pos = *MatchResult;
  2017. PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, Pos, MatchLen,
  2018. Req, Diags);
  2019. DirectiveFail = true;
  2020. }
  2021. return DirectiveFail;
  2022. }
  2023. size_t FileCheckString::CheckDag(const SourceMgr &SM, StringRef Buffer,
  2024. std::vector<const Pattern *> &NotStrings,
  2025. const FileCheckRequest &Req,
  2026. std::vector<FileCheckDiag> *Diags) const {
  2027. if (DagNotStrings.empty())
  2028. return 0;
  2029. // The start of the search range.
  2030. size_t StartPos = 0;
  2031. struct MatchRange {
  2032. size_t Pos;
  2033. size_t End;
  2034. };
  2035. // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
  2036. // ranges are erased from this list once they are no longer in the search
  2037. // range.
  2038. std::list<MatchRange> MatchRanges;
  2039. // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
  2040. // group, so we don't use a range-based for loop here.
  2041. for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
  2042. PatItr != PatEnd; ++PatItr) {
  2043. const Pattern &Pat = *PatItr;
  2044. assert((Pat.getCheckTy() == Check::CheckDAG ||
  2045. Pat.getCheckTy() == Check::CheckNot) &&
  2046. "Invalid CHECK-DAG or CHECK-NOT!");
  2047. if (Pat.getCheckTy() == Check::CheckNot) {
  2048. NotStrings.push_back(&Pat);
  2049. continue;
  2050. }
  2051. assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
  2052. // CHECK-DAG always matches from the start.
  2053. size_t MatchLen = 0, MatchPos = StartPos;
  2054. // Search for a match that doesn't overlap a previous match in this
  2055. // CHECK-DAG group.
  2056. for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
  2057. StringRef MatchBuffer = Buffer.substr(MatchPos);
  2058. Expected<size_t> MatchResult = Pat.match(MatchBuffer, MatchLen, SM);
  2059. // With a group of CHECK-DAGs, a single mismatching means the match on
  2060. // that group of CHECK-DAGs fails immediately.
  2061. if (!MatchResult) {
  2062. PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
  2063. Req.VerboseVerbose, Diags, MatchResult.takeError());
  2064. return StringRef::npos;
  2065. }
  2066. size_t MatchPosBuf = *MatchResult;
  2067. // Re-calc it as the offset relative to the start of the original string.
  2068. MatchPos += MatchPosBuf;
  2069. if (Req.VerboseVerbose)
  2070. PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
  2071. MatchLen, Req, Diags);
  2072. MatchRange M{MatchPos, MatchPos + MatchLen};
  2073. if (Req.AllowDeprecatedDagOverlap) {
  2074. // We don't need to track all matches in this mode, so we just maintain
  2075. // one match range that encompasses the current CHECK-DAG group's
  2076. // matches.
  2077. if (MatchRanges.empty())
  2078. MatchRanges.insert(MatchRanges.end(), M);
  2079. else {
  2080. auto Block = MatchRanges.begin();
  2081. Block->Pos = std::min(Block->Pos, M.Pos);
  2082. Block->End = std::max(Block->End, M.End);
  2083. }
  2084. break;
  2085. }
  2086. // Iterate previous matches until overlapping match or insertion point.
  2087. bool Overlap = false;
  2088. for (; MI != ME; ++MI) {
  2089. if (M.Pos < MI->End) {
  2090. // !Overlap => New match has no overlap and is before this old match.
  2091. // Overlap => New match overlaps this old match.
  2092. Overlap = MI->Pos < M.End;
  2093. break;
  2094. }
  2095. }
  2096. if (!Overlap) {
  2097. // Insert non-overlapping match into list.
  2098. MatchRanges.insert(MI, M);
  2099. break;
  2100. }
  2101. if (Req.VerboseVerbose) {
  2102. // Due to their verbosity, we don't print verbose diagnostics here if
  2103. // we're gathering them for a different rendering, but we always print
  2104. // other diagnostics.
  2105. if (!Diags) {
  2106. SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
  2107. SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
  2108. SMRange OldRange(OldStart, OldEnd);
  2109. SM.PrintMessage(OldStart, SourceMgr::DK_Note,
  2110. "match discarded, overlaps earlier DAG match here",
  2111. {OldRange});
  2112. } else {
  2113. SMLoc CheckLoc = Diags->rbegin()->CheckLoc;
  2114. for (auto I = Diags->rbegin(), E = Diags->rend();
  2115. I != E && I->CheckLoc == CheckLoc; ++I)
  2116. I->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
  2117. }
  2118. }
  2119. MatchPos = MI->End;
  2120. }
  2121. if (!Req.VerboseVerbose)
  2122. PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
  2123. MatchLen, Req, Diags);
  2124. // Handle the end of a CHECK-DAG group.
  2125. if (std::next(PatItr) == PatEnd ||
  2126. std::next(PatItr)->getCheckTy() == Check::CheckNot) {
  2127. if (!NotStrings.empty()) {
  2128. // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
  2129. // CHECK-DAG, verify that there are no 'not' strings occurred in that
  2130. // region.
  2131. StringRef SkippedRegion =
  2132. Buffer.slice(StartPos, MatchRanges.begin()->Pos);
  2133. if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
  2134. return StringRef::npos;
  2135. // Clear "not strings".
  2136. NotStrings.clear();
  2137. }
  2138. // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
  2139. // end of this CHECK-DAG group's match range.
  2140. StartPos = MatchRanges.rbegin()->End;
  2141. // Don't waste time checking for (impossible) overlaps before that.
  2142. MatchRanges.clear();
  2143. }
  2144. }
  2145. return StartPos;
  2146. }
  2147. static bool ValidatePrefixes(StringRef Kind, StringSet<> &UniquePrefixes,
  2148. ArrayRef<StringRef> SuppliedPrefixes) {
  2149. for (StringRef Prefix : SuppliedPrefixes) {
  2150. if (Prefix.empty()) {
  2151. errs() << "error: supplied " << Kind << " prefix must not be the empty "
  2152. << "string\n";
  2153. return false;
  2154. }
  2155. static const Regex Validator("^[a-zA-Z0-9_-]*$");
  2156. if (!Validator.match(Prefix)) {
  2157. errs() << "error: supplied " << Kind << " prefix must start with a "
  2158. << "letter and contain only alphanumeric characters, hyphens, and "
  2159. << "underscores: '" << Prefix << "'\n";
  2160. return false;
  2161. }
  2162. if (!UniquePrefixes.insert(Prefix).second) {
  2163. errs() << "error: supplied " << Kind << " prefix must be unique among "
  2164. << "check and comment prefixes: '" << Prefix << "'\n";
  2165. return false;
  2166. }
  2167. }
  2168. return true;
  2169. }
  2170. static const char *DefaultCheckPrefixes[] = {"CHECK"};
  2171. static const char *DefaultCommentPrefixes[] = {"COM", "RUN"};
  2172. bool FileCheck::ValidateCheckPrefixes() {
  2173. StringSet<> UniquePrefixes;
  2174. // Add default prefixes to catch user-supplied duplicates of them below.
  2175. if (Req.CheckPrefixes.empty()) {
  2176. for (const char *Prefix : DefaultCheckPrefixes)
  2177. UniquePrefixes.insert(Prefix);
  2178. }
  2179. if (Req.CommentPrefixes.empty()) {
  2180. for (const char *Prefix : DefaultCommentPrefixes)
  2181. UniquePrefixes.insert(Prefix);
  2182. }
  2183. // Do not validate the default prefixes, or diagnostics about duplicates might
  2184. // incorrectly indicate that they were supplied by the user.
  2185. if (!ValidatePrefixes("check", UniquePrefixes, Req.CheckPrefixes))
  2186. return false;
  2187. if (!ValidatePrefixes("comment", UniquePrefixes, Req.CommentPrefixes))
  2188. return false;
  2189. return true;
  2190. }
  2191. Regex FileCheck::buildCheckPrefixRegex() {
  2192. if (Req.CheckPrefixes.empty()) {
  2193. for (const char *Prefix : DefaultCheckPrefixes)
  2194. Req.CheckPrefixes.push_back(Prefix);
  2195. Req.IsDefaultCheckPrefix = true;
  2196. }
  2197. if (Req.CommentPrefixes.empty()) {
  2198. for (const char *Prefix : DefaultCommentPrefixes)
  2199. Req.CommentPrefixes.push_back(Prefix);
  2200. }
  2201. // We already validated the contents of CheckPrefixes and CommentPrefixes so
  2202. // just concatenate them as alternatives.
  2203. SmallString<32> PrefixRegexStr;
  2204. for (size_t I = 0, E = Req.CheckPrefixes.size(); I != E; ++I) {
  2205. if (I != 0)
  2206. PrefixRegexStr.push_back('|');
  2207. PrefixRegexStr.append(Req.CheckPrefixes[I]);
  2208. }
  2209. for (StringRef Prefix : Req.CommentPrefixes) {
  2210. PrefixRegexStr.push_back('|');
  2211. PrefixRegexStr.append(Prefix);
  2212. }
  2213. return Regex(PrefixRegexStr);
  2214. }
  2215. Error FileCheckPatternContext::defineCmdlineVariables(
  2216. ArrayRef<StringRef> CmdlineDefines, SourceMgr &SM) {
  2217. assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
  2218. "Overriding defined variable with command-line variable definitions");
  2219. if (CmdlineDefines.empty())
  2220. return Error::success();
  2221. // Create a string representing the vector of command-line definitions. Each
  2222. // definition is on its own line and prefixed with a definition number to
  2223. // clarify which definition a given diagnostic corresponds to.
  2224. unsigned I = 0;
  2225. Error Errs = Error::success();
  2226. std::string CmdlineDefsDiag;
  2227. SmallVector<std::pair<size_t, size_t>, 4> CmdlineDefsIndices;
  2228. for (StringRef CmdlineDef : CmdlineDefines) {
  2229. std::string DefPrefix = ("Global define #" + Twine(++I) + ": ").str();
  2230. size_t EqIdx = CmdlineDef.find('=');
  2231. if (EqIdx == StringRef::npos) {
  2232. CmdlineDefsIndices.push_back(std::make_pair(CmdlineDefsDiag.size(), 0));
  2233. continue;
  2234. }
  2235. // Numeric variable definition.
  2236. if (CmdlineDef[0] == '#') {
  2237. // Append a copy of the command-line definition adapted to use the same
  2238. // format as in the input file to be able to reuse
  2239. // parseNumericSubstitutionBlock.
  2240. CmdlineDefsDiag += (DefPrefix + CmdlineDef + " (parsed as: [[").str();
  2241. std::string SubstitutionStr = std::string(CmdlineDef);
  2242. SubstitutionStr[EqIdx] = ':';
  2243. CmdlineDefsIndices.push_back(
  2244. std::make_pair(CmdlineDefsDiag.size(), SubstitutionStr.size()));
  2245. CmdlineDefsDiag += (SubstitutionStr + Twine("]])\n")).str();
  2246. } else {
  2247. CmdlineDefsDiag += DefPrefix;
  2248. CmdlineDefsIndices.push_back(
  2249. std::make_pair(CmdlineDefsDiag.size(), CmdlineDef.size()));
  2250. CmdlineDefsDiag += (CmdlineDef + "\n").str();
  2251. }
  2252. }
  2253. // Create a buffer with fake command line content in order to display
  2254. // parsing diagnostic with location information and point to the
  2255. // global definition with invalid syntax.
  2256. std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
  2257. MemoryBuffer::getMemBufferCopy(CmdlineDefsDiag, "Global defines");
  2258. StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
  2259. SM.AddNewSourceBuffer(std::move(CmdLineDefsDiagBuffer), SMLoc());
  2260. for (std::pair<size_t, size_t> CmdlineDefIndices : CmdlineDefsIndices) {
  2261. StringRef CmdlineDef = CmdlineDefsDiagRef.substr(CmdlineDefIndices.first,
  2262. CmdlineDefIndices.second);
  2263. if (CmdlineDef.empty()) {
  2264. Errs = joinErrors(
  2265. std::move(Errs),
  2266. ErrorDiagnostic::get(SM, CmdlineDef,
  2267. "missing equal sign in global definition"));
  2268. continue;
  2269. }
  2270. // Numeric variable definition.
  2271. if (CmdlineDef[0] == '#') {
  2272. // Now parse the definition both to check that the syntax is correct and
  2273. // to create the necessary class instance.
  2274. StringRef CmdlineDefExpr = CmdlineDef.substr(1);
  2275. Optional<NumericVariable *> DefinedNumericVariable;
  2276. Expected<std::unique_ptr<Expression>> ExpressionResult =
  2277. Pattern::parseNumericSubstitutionBlock(
  2278. CmdlineDefExpr, DefinedNumericVariable, false, None, this, SM);
  2279. if (!ExpressionResult) {
  2280. Errs = joinErrors(std::move(Errs), ExpressionResult.takeError());
  2281. continue;
  2282. }
  2283. std::unique_ptr<Expression> Expression = std::move(*ExpressionResult);
  2284. // Now evaluate the expression whose value this variable should be set
  2285. // to, since the expression of a command-line variable definition should
  2286. // only use variables defined earlier on the command-line. If not, this
  2287. // is an error and we report it.
  2288. Expected<ExpressionValue> Value = Expression->getAST()->eval();
  2289. if (!Value) {
  2290. Errs = joinErrors(std::move(Errs), Value.takeError());
  2291. continue;
  2292. }
  2293. assert(DefinedNumericVariable && "No variable defined");
  2294. (*DefinedNumericVariable)->setValue(*Value);
  2295. // Record this variable definition.
  2296. GlobalNumericVariableTable[(*DefinedNumericVariable)->getName()] =
  2297. *DefinedNumericVariable;
  2298. } else {
  2299. // String variable definition.
  2300. std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.split('=');
  2301. StringRef CmdlineName = CmdlineNameVal.first;
  2302. StringRef OrigCmdlineName = CmdlineName;
  2303. Expected<Pattern::VariableProperties> ParseVarResult =
  2304. Pattern::parseVariable(CmdlineName, SM);
  2305. if (!ParseVarResult) {
  2306. Errs = joinErrors(std::move(Errs), ParseVarResult.takeError());
  2307. continue;
  2308. }
  2309. // Check that CmdlineName does not denote a pseudo variable is only
  2310. // composed of the parsed numeric variable. This catches cases like
  2311. // "FOO+2" in a "FOO+2=10" definition.
  2312. if (ParseVarResult->IsPseudo || !CmdlineName.empty()) {
  2313. Errs = joinErrors(std::move(Errs),
  2314. ErrorDiagnostic::get(
  2315. SM, OrigCmdlineName,
  2316. "invalid name in string variable definition '" +
  2317. OrigCmdlineName + "'"));
  2318. continue;
  2319. }
  2320. StringRef Name = ParseVarResult->Name;
  2321. // Detect collisions between string and numeric variables when the former
  2322. // is created later than the latter.
  2323. if (GlobalNumericVariableTable.find(Name) !=
  2324. GlobalNumericVariableTable.end()) {
  2325. Errs = joinErrors(std::move(Errs),
  2326. ErrorDiagnostic::get(SM, Name,
  2327. "numeric variable with name '" +
  2328. Name + "' already exists"));
  2329. continue;
  2330. }
  2331. GlobalVariableTable.insert(CmdlineNameVal);
  2332. // Mark the string variable as defined to detect collisions between
  2333. // string and numeric variables in defineCmdlineVariables when the latter
  2334. // is created later than the former. We cannot reuse GlobalVariableTable
  2335. // for this by populating it with an empty string since we would then
  2336. // lose the ability to detect the use of an undefined variable in
  2337. // match().
  2338. DefinedVariableTable[Name] = true;
  2339. }
  2340. }
  2341. return Errs;
  2342. }
  2343. void FileCheckPatternContext::clearLocalVars() {
  2344. SmallVector<StringRef, 16> LocalPatternVars, LocalNumericVars;
  2345. for (const StringMapEntry<StringRef> &Var : GlobalVariableTable)
  2346. if (Var.first()[0] != '$')
  2347. LocalPatternVars.push_back(Var.first());
  2348. // Numeric substitution reads the value of a variable directly, not via
  2349. // GlobalNumericVariableTable. Therefore, we clear local variables by
  2350. // clearing their value which will lead to a numeric substitution failure. We
  2351. // also mark the variable for removal from GlobalNumericVariableTable since
  2352. // this is what defineCmdlineVariables checks to decide that no global
  2353. // variable has been defined.
  2354. for (const auto &Var : GlobalNumericVariableTable)
  2355. if (Var.first()[0] != '$') {
  2356. Var.getValue()->clearValue();
  2357. LocalNumericVars.push_back(Var.first());
  2358. }
  2359. for (const auto &Var : LocalPatternVars)
  2360. GlobalVariableTable.erase(Var);
  2361. for (const auto &Var : LocalNumericVars)
  2362. GlobalNumericVariableTable.erase(Var);
  2363. }
  2364. bool FileCheck::checkInput(SourceMgr &SM, StringRef Buffer,
  2365. std::vector<FileCheckDiag> *Diags) {
  2366. bool ChecksFailed = false;
  2367. unsigned i = 0, j = 0, e = CheckStrings->size();
  2368. while (true) {
  2369. StringRef CheckRegion;
  2370. if (j == e) {
  2371. CheckRegion = Buffer;
  2372. } else {
  2373. const FileCheckString &CheckLabelStr = (*CheckStrings)[j];
  2374. if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
  2375. ++j;
  2376. continue;
  2377. }
  2378. // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
  2379. size_t MatchLabelLen = 0;
  2380. size_t MatchLabelPos =
  2381. CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, Req, Diags);
  2382. if (MatchLabelPos == StringRef::npos)
  2383. // Immediately bail if CHECK-LABEL fails, nothing else we can do.
  2384. return false;
  2385. CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
  2386. Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
  2387. ++j;
  2388. }
  2389. // Do not clear the first region as it's the one before the first
  2390. // CHECK-LABEL and it would clear variables defined on the command-line
  2391. // before they get used.
  2392. if (i != 0 && Req.EnableVarScope)
  2393. PatternContext->clearLocalVars();
  2394. for (; i != j; ++i) {
  2395. const FileCheckString &CheckStr = (*CheckStrings)[i];
  2396. // Check each string within the scanned region, including a second check
  2397. // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
  2398. size_t MatchLen = 0;
  2399. size_t MatchPos =
  2400. CheckStr.Check(SM, CheckRegion, false, MatchLen, Req, Diags);
  2401. if (MatchPos == StringRef::npos) {
  2402. ChecksFailed = true;
  2403. i = j;
  2404. break;
  2405. }
  2406. CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
  2407. }
  2408. if (j == e)
  2409. break;
  2410. }
  2411. // Success if no checks failed.
  2412. return !ChecksFailed;
  2413. }