cmListCommand.cxx 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmListCommand.h"
  4. #include "cmsys/RegularExpression.hxx"
  5. #include <algorithm>
  6. #include <assert.h>
  7. #include <cstddef>
  8. #include <functional>
  9. #include <iterator>
  10. #include <set>
  11. #include <sstream>
  12. #include <stdexcept>
  13. #include <stdio.h>
  14. #include <stdlib.h> // required for atoi
  15. #include <utility>
  16. #include <vector>
  17. #include "cm_memory.hxx"
  18. #include "cm_static_string_view.hxx"
  19. #include "cmAlgorithms.h"
  20. #include "cmExecutionStatus.h"
  21. #include "cmGeneratorExpression.h"
  22. #include "cmMakefile.h"
  23. #include "cmMessageType.h"
  24. #include "cmPolicies.h"
  25. #include "cmRange.h"
  26. #include "cmStringAlgorithms.h"
  27. #include "cmStringReplaceHelper.h"
  28. #include "cmSubcommandTable.h"
  29. #include "cmSystemTools.h"
  30. namespace {
  31. bool FilterRegex(std::vector<std::string> const& args, bool includeMatches,
  32. std::string const& listName,
  33. std::vector<std::string>& varArgsExpanded,
  34. cmExecutionStatus& status);
  35. bool GetListString(std::string& listString, const std::string& var,
  36. const cmMakefile& makefile)
  37. {
  38. // get the old value
  39. const char* cacheValue = makefile.GetDefinition(var);
  40. if (!cacheValue) {
  41. return false;
  42. }
  43. listString = cacheValue;
  44. return true;
  45. }
  46. bool GetList(std::vector<std::string>& list, const std::string& var,
  47. const cmMakefile& makefile)
  48. {
  49. std::string listString;
  50. if (!GetListString(listString, var, makefile)) {
  51. return false;
  52. }
  53. // if the size of the list
  54. if (listString.empty()) {
  55. return true;
  56. }
  57. // expand the variable into a list
  58. cmExpandList(listString, list, true);
  59. // if no empty elements then just return
  60. if (!cmContains(list, std::string())) {
  61. return true;
  62. }
  63. // if we have empty elements we need to check policy CMP0007
  64. switch (makefile.GetPolicyStatus(cmPolicies::CMP0007)) {
  65. case cmPolicies::WARN: {
  66. // Default is to warn and use old behavior
  67. // OLD behavior is to allow compatibility, so recall
  68. // ExpandListArgument without the true which will remove
  69. // empty values
  70. list.clear();
  71. cmExpandList(listString, list);
  72. std::string warn =
  73. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0007),
  74. " List has value = [", listString, "].");
  75. makefile.IssueMessage(MessageType::AUTHOR_WARNING, warn);
  76. return true;
  77. }
  78. case cmPolicies::OLD:
  79. // OLD behavior is to allow compatibility, so recall
  80. // ExpandListArgument without the true which will remove
  81. // empty values
  82. list.clear();
  83. cmExpandList(listString, list);
  84. return true;
  85. case cmPolicies::NEW:
  86. return true;
  87. case cmPolicies::REQUIRED_IF_USED:
  88. case cmPolicies::REQUIRED_ALWAYS:
  89. makefile.IssueMessage(
  90. MessageType::FATAL_ERROR,
  91. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0007));
  92. return false;
  93. }
  94. return true;
  95. }
  96. bool HandleLengthCommand(std::vector<std::string> const& args,
  97. cmExecutionStatus& status)
  98. {
  99. if (args.size() != 3) {
  100. status.SetError("sub-command LENGTH requires two arguments.");
  101. return false;
  102. }
  103. const std::string& listName = args[1];
  104. const std::string& variableName = args.back();
  105. std::vector<std::string> varArgsExpanded;
  106. // do not check the return value here
  107. // if the list var is not found varArgsExpanded will have size 0
  108. // and we will return 0
  109. GetList(varArgsExpanded, listName, status.GetMakefile());
  110. size_t length = varArgsExpanded.size();
  111. char buffer[1024];
  112. sprintf(buffer, "%d", static_cast<int>(length));
  113. status.GetMakefile().AddDefinition(variableName, buffer);
  114. return true;
  115. }
  116. bool HandleGetCommand(std::vector<std::string> const& args,
  117. cmExecutionStatus& status)
  118. {
  119. if (args.size() < 4) {
  120. status.SetError("sub-command GET requires at least three arguments.");
  121. return false;
  122. }
  123. const std::string& listName = args[1];
  124. const std::string& variableName = args.back();
  125. // expand the variable
  126. std::vector<std::string> varArgsExpanded;
  127. if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
  128. status.GetMakefile().AddDefinition(variableName, "NOTFOUND");
  129. return true;
  130. }
  131. // FIXME: Add policy to make non-existing lists an error like empty lists.
  132. if (varArgsExpanded.empty()) {
  133. status.SetError("GET given empty list");
  134. return false;
  135. }
  136. std::string value;
  137. size_t cc;
  138. const char* sep = "";
  139. size_t nitem = varArgsExpanded.size();
  140. for (cc = 2; cc < args.size() - 1; cc++) {
  141. int item = atoi(args[cc].c_str());
  142. value += sep;
  143. sep = ";";
  144. if (item < 0) {
  145. item = static_cast<int>(nitem) + item;
  146. }
  147. if (item < 0 || nitem <= static_cast<size_t>(item)) {
  148. std::ostringstream str;
  149. str << "index: " << item << " out of range (-" << nitem << ", "
  150. << nitem - 1 << ")";
  151. status.SetError(str.str());
  152. return false;
  153. }
  154. value += varArgsExpanded[item];
  155. }
  156. status.GetMakefile().AddDefinition(variableName, value);
  157. return true;
  158. }
  159. bool HandleAppendCommand(std::vector<std::string> const& args,
  160. cmExecutionStatus& status)
  161. {
  162. assert(args.size() >= 2);
  163. // Skip if nothing to append.
  164. if (args.size() < 3) {
  165. return true;
  166. }
  167. cmMakefile& makefile = status.GetMakefile();
  168. std::string const& listName = args[1];
  169. // expand the variable
  170. std::string listString;
  171. GetListString(listString, listName, makefile);
  172. // If `listString` or `args` is empty, no need to append `;`,
  173. // then index is going to be `1` and points to the end-of-string ";"
  174. auto const offset =
  175. std::string::size_type(listString.empty() || args.empty());
  176. listString += &";"[offset] + cmJoin(cmMakeRange(args).advance(2), ";");
  177. makefile.AddDefinition(listName, listString);
  178. return true;
  179. }
  180. bool HandlePrependCommand(std::vector<std::string> const& args,
  181. cmExecutionStatus& status)
  182. {
  183. assert(args.size() >= 2);
  184. // Skip if nothing to prepend.
  185. if (args.size() < 3) {
  186. return true;
  187. }
  188. cmMakefile& makefile = status.GetMakefile();
  189. std::string const& listName = args[1];
  190. // expand the variable
  191. std::string listString;
  192. GetListString(listString, listName, makefile);
  193. // If `listString` or `args` is empty, no need to append `;`,
  194. // then `offset` is going to be `1` and points to the end-of-string ";"
  195. auto const offset =
  196. std::string::size_type(listString.empty() || args.empty());
  197. listString.insert(0,
  198. cmJoin(cmMakeRange(args).advance(2), ";") + &";"[offset]);
  199. makefile.AddDefinition(listName, listString);
  200. return true;
  201. }
  202. bool HandlePopBackCommand(std::vector<std::string> const& args,
  203. cmExecutionStatus& status)
  204. {
  205. assert(args.size() >= 2);
  206. cmMakefile& makefile = status.GetMakefile();
  207. auto ai = args.cbegin();
  208. ++ai; // Skip subcommand name
  209. std::string const& listName = *ai++;
  210. std::vector<std::string> varArgsExpanded;
  211. if (!GetList(varArgsExpanded, listName, makefile)) {
  212. // Can't get the list definition... undefine any vars given after.
  213. for (; ai != args.cend(); ++ai) {
  214. makefile.RemoveDefinition(*ai);
  215. }
  216. return true;
  217. }
  218. if (!varArgsExpanded.empty()) {
  219. if (ai == args.cend()) {
  220. // No variables are given... Just remove one element.
  221. varArgsExpanded.pop_back();
  222. } else {
  223. // Ok, assign elements to be removed to the given variables
  224. for (; !varArgsExpanded.empty() && ai != args.cend(); ++ai) {
  225. assert(!ai->empty());
  226. makefile.AddDefinition(*ai, varArgsExpanded.back());
  227. varArgsExpanded.pop_back();
  228. }
  229. // Undefine the rest variables if the list gets empty earlier...
  230. for (; ai != args.cend(); ++ai) {
  231. makefile.RemoveDefinition(*ai);
  232. }
  233. }
  234. makefile.AddDefinition(listName, cmJoin(varArgsExpanded, ";"));
  235. } else if (ai !=
  236. args.cend()) { // The list is empty, but some args were given
  237. // Need to *undefine* 'em all, cuz there are no items to assign...
  238. for (; ai != args.cend(); ++ai) {
  239. makefile.RemoveDefinition(*ai);
  240. }
  241. }
  242. return true;
  243. }
  244. bool HandlePopFrontCommand(std::vector<std::string> const& args,
  245. cmExecutionStatus& status)
  246. {
  247. assert(args.size() >= 2);
  248. cmMakefile& makefile = status.GetMakefile();
  249. auto ai = args.cbegin();
  250. ++ai; // Skip subcommand name
  251. std::string const& listName = *ai++;
  252. std::vector<std::string> varArgsExpanded;
  253. if (!GetList(varArgsExpanded, listName, makefile)) {
  254. // Can't get the list definition... undefine any vars given after.
  255. for (; ai != args.cend(); ++ai) {
  256. makefile.RemoveDefinition(*ai);
  257. }
  258. return true;
  259. }
  260. if (!varArgsExpanded.empty()) {
  261. if (ai == args.cend()) {
  262. // No variables are given... Just remove one element.
  263. varArgsExpanded.erase(varArgsExpanded.begin());
  264. } else {
  265. // Ok, assign elements to be removed to the given variables
  266. auto vi = varArgsExpanded.begin();
  267. for (; vi != varArgsExpanded.end() && ai != args.cend(); ++ai, ++vi) {
  268. assert(!ai->empty());
  269. makefile.AddDefinition(*ai, *vi);
  270. }
  271. varArgsExpanded.erase(varArgsExpanded.begin(), vi);
  272. // Undefine the rest variables if the list gets empty earlier...
  273. for (; ai != args.cend(); ++ai) {
  274. makefile.RemoveDefinition(*ai);
  275. }
  276. }
  277. makefile.AddDefinition(listName, cmJoin(varArgsExpanded, ";"));
  278. } else if (ai !=
  279. args.cend()) { // The list is empty, but some args were given
  280. // Need to *undefine* 'em all, cuz there are no items to assign...
  281. for (; ai != args.cend(); ++ai) {
  282. makefile.RemoveDefinition(*ai);
  283. }
  284. }
  285. return true;
  286. }
  287. bool HandleFindCommand(std::vector<std::string> const& args,
  288. cmExecutionStatus& status)
  289. {
  290. if (args.size() != 4) {
  291. status.SetError("sub-command FIND requires three arguments.");
  292. return false;
  293. }
  294. const std::string& listName = args[1];
  295. const std::string& variableName = args.back();
  296. // expand the variable
  297. std::vector<std::string> varArgsExpanded;
  298. if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
  299. status.GetMakefile().AddDefinition(variableName, "-1");
  300. return true;
  301. }
  302. std::vector<std::string>::iterator it =
  303. std::find(varArgsExpanded.begin(), varArgsExpanded.end(), args[2]);
  304. if (it != varArgsExpanded.end()) {
  305. status.GetMakefile().AddDefinition(
  306. variableName,
  307. std::to_string(std::distance(varArgsExpanded.begin(), it)));
  308. return true;
  309. }
  310. status.GetMakefile().AddDefinition(variableName, "-1");
  311. return true;
  312. }
  313. bool HandleInsertCommand(std::vector<std::string> const& args,
  314. cmExecutionStatus& status)
  315. {
  316. if (args.size() < 4) {
  317. status.SetError("sub-command INSERT requires at least three arguments.");
  318. return false;
  319. }
  320. const std::string& listName = args[1];
  321. // expand the variable
  322. int item = atoi(args[2].c_str());
  323. std::vector<std::string> varArgsExpanded;
  324. if ((!GetList(varArgsExpanded, listName, status.GetMakefile()) ||
  325. varArgsExpanded.empty()) &&
  326. item != 0) {
  327. std::ostringstream str;
  328. str << "index: " << item << " out of range (0, 0)";
  329. status.SetError(str.str());
  330. return false;
  331. }
  332. if (!varArgsExpanded.empty()) {
  333. size_t nitem = varArgsExpanded.size();
  334. if (item < 0) {
  335. item = static_cast<int>(nitem) + item;
  336. }
  337. if (item < 0 || nitem < static_cast<size_t>(item)) {
  338. std::ostringstream str;
  339. str << "index: " << item << " out of range (-" << varArgsExpanded.size()
  340. << ", " << varArgsExpanded.size() << ")";
  341. status.SetError(str.str());
  342. return false;
  343. }
  344. }
  345. varArgsExpanded.insert(varArgsExpanded.begin() + item, args.begin() + 3,
  346. args.end());
  347. std::string value = cmJoin(varArgsExpanded, ";");
  348. status.GetMakefile().AddDefinition(listName, value);
  349. return true;
  350. }
  351. bool HandleJoinCommand(std::vector<std::string> const& args,
  352. cmExecutionStatus& status)
  353. {
  354. if (args.size() != 4) {
  355. std::ostringstream error;
  356. error << "sub-command JOIN requires three arguments (" << args.size() - 1
  357. << " found).";
  358. status.SetError(error.str());
  359. return false;
  360. }
  361. const std::string& listName = args[1];
  362. const std::string& glue = args[2];
  363. const std::string& variableName = args[3];
  364. // expand the variable
  365. std::vector<std::string> varArgsExpanded;
  366. if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
  367. status.GetMakefile().AddDefinition(variableName, "");
  368. return true;
  369. }
  370. std::string value =
  371. cmJoin(cmMakeRange(varArgsExpanded.begin(), varArgsExpanded.end()), glue);
  372. status.GetMakefile().AddDefinition(variableName, value);
  373. return true;
  374. }
  375. bool HandleRemoveItemCommand(std::vector<std::string> const& args,
  376. cmExecutionStatus& status)
  377. {
  378. if (args.size() < 3) {
  379. status.SetError("sub-command REMOVE_ITEM requires two or more arguments.");
  380. return false;
  381. }
  382. const std::string& listName = args[1];
  383. // expand the variable
  384. std::vector<std::string> varArgsExpanded;
  385. if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
  386. return true;
  387. }
  388. std::vector<std::string> remove(args.begin() + 2, args.end());
  389. std::sort(remove.begin(), remove.end());
  390. std::vector<std::string>::const_iterator remEnd =
  391. std::unique(remove.begin(), remove.end());
  392. std::vector<std::string>::const_iterator remBegin = remove.begin();
  393. std::vector<std::string>::const_iterator argsEnd =
  394. cmRemoveMatching(varArgsExpanded, cmMakeRange(remBegin, remEnd));
  395. std::vector<std::string>::const_iterator argsBegin = varArgsExpanded.begin();
  396. std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";");
  397. status.GetMakefile().AddDefinition(listName, value);
  398. return true;
  399. }
  400. bool HandleReverseCommand(std::vector<std::string> const& args,
  401. cmExecutionStatus& status)
  402. {
  403. assert(args.size() >= 2);
  404. if (args.size() > 2) {
  405. status.SetError("sub-command REVERSE only takes one argument.");
  406. return false;
  407. }
  408. const std::string& listName = args[1];
  409. // expand the variable
  410. std::vector<std::string> varArgsExpanded;
  411. if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
  412. return true;
  413. }
  414. std::string value = cmJoin(cmReverseRange(varArgsExpanded), ";");
  415. status.GetMakefile().AddDefinition(listName, value);
  416. return true;
  417. }
  418. bool HandleRemoveDuplicatesCommand(std::vector<std::string> const& args,
  419. cmExecutionStatus& status)
  420. {
  421. assert(args.size() >= 2);
  422. if (args.size() > 2) {
  423. status.SetError("sub-command REMOVE_DUPLICATES only takes one argument.");
  424. return false;
  425. }
  426. const std::string& listName = args[1];
  427. // expand the variable
  428. std::vector<std::string> varArgsExpanded;
  429. if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
  430. return true;
  431. }
  432. std::vector<std::string>::const_iterator argsEnd =
  433. cmRemoveDuplicates(varArgsExpanded);
  434. std::vector<std::string>::const_iterator argsBegin = varArgsExpanded.begin();
  435. std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";");
  436. status.GetMakefile().AddDefinition(listName, value);
  437. return true;
  438. }
  439. // Helpers for list(TRANSFORM <list> ...)
  440. using transform_type = std::function<std::string(const std::string&)>;
  441. class transform_error : public std::runtime_error
  442. {
  443. public:
  444. transform_error(const std::string& error)
  445. : std::runtime_error(error)
  446. {
  447. }
  448. };
  449. class TransformSelector
  450. {
  451. public:
  452. virtual ~TransformSelector() = default;
  453. std::string Tag;
  454. virtual bool Validate(std::size_t count = 0) = 0;
  455. virtual bool InSelection(const std::string&) = 0;
  456. virtual void Transform(std::vector<std::string>& list,
  457. const transform_type& transform)
  458. {
  459. std::transform(list.begin(), list.end(), list.begin(), transform);
  460. }
  461. protected:
  462. TransformSelector(std::string&& tag)
  463. : Tag(std::move(tag))
  464. {
  465. }
  466. };
  467. class TransformNoSelector : public TransformSelector
  468. {
  469. public:
  470. TransformNoSelector()
  471. : TransformSelector("NO SELECTOR")
  472. {
  473. }
  474. bool Validate(std::size_t) override { return true; }
  475. bool InSelection(const std::string&) override { return true; }
  476. };
  477. class TransformSelectorRegex : public TransformSelector
  478. {
  479. public:
  480. TransformSelectorRegex(const std::string& regex)
  481. : TransformSelector("REGEX")
  482. , Regex(regex)
  483. {
  484. }
  485. bool Validate(std::size_t) override { return this->Regex.is_valid(); }
  486. bool InSelection(const std::string& value) override
  487. {
  488. return this->Regex.find(value);
  489. }
  490. cmsys::RegularExpression Regex;
  491. };
  492. class TransformSelectorIndexes : public TransformSelector
  493. {
  494. public:
  495. std::vector<int> Indexes;
  496. bool InSelection(const std::string&) override { return true; }
  497. void Transform(std::vector<std::string>& list,
  498. const transform_type& transform) override
  499. {
  500. this->Validate(list.size());
  501. for (auto index : this->Indexes) {
  502. list[index] = transform(list[index]);
  503. }
  504. }
  505. protected:
  506. TransformSelectorIndexes(std::string&& tag)
  507. : TransformSelector(std::move(tag))
  508. {
  509. }
  510. TransformSelectorIndexes(std::string&& tag, std::vector<int>&& indexes)
  511. : TransformSelector(std::move(tag))
  512. , Indexes(indexes)
  513. {
  514. }
  515. int NormalizeIndex(int index, std::size_t count)
  516. {
  517. if (index < 0) {
  518. index = static_cast<int>(count) + index;
  519. }
  520. if (index < 0 || count <= static_cast<std::size_t>(index)) {
  521. std::ostringstream str;
  522. str << "sub-command TRANSFORM, selector " << this->Tag
  523. << ", index: " << index << " out of range (-" << count << ", "
  524. << count - 1 << ").";
  525. throw transform_error(str.str());
  526. }
  527. return index;
  528. }
  529. };
  530. class TransformSelectorAt : public TransformSelectorIndexes
  531. {
  532. public:
  533. TransformSelectorAt(std::vector<int>&& indexes)
  534. : TransformSelectorIndexes("AT", std::move(indexes))
  535. {
  536. }
  537. bool Validate(std::size_t count) override
  538. {
  539. decltype(Indexes) indexes;
  540. for (auto index : Indexes) {
  541. indexes.push_back(this->NormalizeIndex(index, count));
  542. }
  543. this->Indexes = std::move(indexes);
  544. return true;
  545. }
  546. };
  547. class TransformSelectorFor : public TransformSelectorIndexes
  548. {
  549. public:
  550. TransformSelectorFor(int start, int stop, int step)
  551. : TransformSelectorIndexes("FOR")
  552. , Start(start)
  553. , Stop(stop)
  554. , Step(step)
  555. {
  556. }
  557. bool Validate(std::size_t count) override
  558. {
  559. this->Start = this->NormalizeIndex(this->Start, count);
  560. this->Stop = this->NormalizeIndex(this->Stop, count);
  561. // compute indexes
  562. auto size = (this->Stop - this->Start + 1) / this->Step;
  563. if ((this->Stop - this->Start + 1) % this->Step != 0) {
  564. size += 1;
  565. }
  566. this->Indexes.resize(size);
  567. auto start = this->Start;
  568. auto step = this->Step;
  569. std::generate(this->Indexes.begin(), this->Indexes.end(),
  570. [&start, step]() -> int {
  571. auto r = start;
  572. start += step;
  573. return r;
  574. });
  575. return true;
  576. }
  577. private:
  578. int Start, Stop, Step;
  579. };
  580. class TransformAction
  581. {
  582. public:
  583. virtual ~TransformAction() = default;
  584. virtual std::string Transform(const std::string& input) = 0;
  585. };
  586. class TransformReplace : public TransformAction
  587. {
  588. public:
  589. TransformReplace(const std::vector<std::string>& arguments,
  590. cmMakefile* makefile)
  591. : ReplaceHelper(arguments[0], arguments[1], makefile)
  592. {
  593. makefile->ClearMatches();
  594. if (!this->ReplaceHelper.IsRegularExpressionValid()) {
  595. std::ostringstream error;
  596. error
  597. << "sub-command TRANSFORM, action REPLACE: Failed to compile regex \""
  598. << arguments[0] << "\".";
  599. throw transform_error(error.str());
  600. }
  601. if (!this->ReplaceHelper.IsReplaceExpressionValid()) {
  602. std::ostringstream error;
  603. error << "sub-command TRANSFORM, action REPLACE: "
  604. << this->ReplaceHelper.GetError() << ".";
  605. throw transform_error(error.str());
  606. }
  607. }
  608. std::string Transform(const std::string& input) override
  609. {
  610. // Scan through the input for all matches.
  611. std::string output;
  612. if (!this->ReplaceHelper.Replace(input, output)) {
  613. std::ostringstream error;
  614. error << "sub-command TRANSFORM, action REPLACE: "
  615. << this->ReplaceHelper.GetError() << ".";
  616. throw transform_error(error.str());
  617. }
  618. return output;
  619. }
  620. private:
  621. cmStringReplaceHelper ReplaceHelper;
  622. };
  623. bool HandleTransformCommand(std::vector<std::string> const& args,
  624. cmExecutionStatus& status)
  625. {
  626. if (args.size() < 3) {
  627. status.SetError(
  628. "sub-command TRANSFORM requires an action to be specified.");
  629. return false;
  630. }
  631. // Structure collecting all elements of the command
  632. struct Command
  633. {
  634. Command(const std::string& listName)
  635. : ListName(listName)
  636. , OutputName(listName)
  637. {
  638. }
  639. std::string Name;
  640. std::string ListName;
  641. std::vector<std::string> Arguments;
  642. std::unique_ptr<TransformAction> Action;
  643. std::unique_ptr<TransformSelector> Selector;
  644. std::string OutputName;
  645. } command(args[1]);
  646. // Descriptor of action
  647. // Arity: number of arguments required for the action
  648. // Transform: lambda function implementing the action
  649. struct ActionDescriptor
  650. {
  651. ActionDescriptor(std::string name)
  652. : Name(std::move(name))
  653. {
  654. }
  655. ActionDescriptor(std::string name, int arity, transform_type transform)
  656. : Name(std::move(name))
  657. , Arity(arity)
  658. #if defined(__GNUC__) && __GNUC__ == 6 && defined(__aarch64__)
  659. // std::function move constructor miscompiles on this architecture
  660. , Transform(transform)
  661. #else
  662. , Transform(std::move(transform))
  663. #endif
  664. {
  665. }
  666. operator const std::string&() const { return Name; }
  667. std::string Name;
  668. int Arity = 0;
  669. transform_type Transform;
  670. };
  671. // Build a set of supported actions.
  672. std::set<ActionDescriptor,
  673. std::function<bool(const std::string&, const std::string&)>>
  674. descriptors(
  675. [](const std::string& x, const std::string& y) { return x < y; });
  676. descriptors = { { "APPEND", 1,
  677. [&command](const std::string& s) -> std::string {
  678. if (command.Selector->InSelection(s)) {
  679. return s + command.Arguments[0];
  680. }
  681. return s;
  682. } },
  683. { "PREPEND", 1,
  684. [&command](const std::string& s) -> std::string {
  685. if (command.Selector->InSelection(s)) {
  686. return command.Arguments[0] + s;
  687. }
  688. return s;
  689. } },
  690. { "TOUPPER", 0,
  691. [&command](const std::string& s) -> std::string {
  692. if (command.Selector->InSelection(s)) {
  693. return cmSystemTools::UpperCase(s);
  694. }
  695. return s;
  696. } },
  697. { "TOLOWER", 0,
  698. [&command](const std::string& s) -> std::string {
  699. if (command.Selector->InSelection(s)) {
  700. return cmSystemTools::LowerCase(s);
  701. }
  702. return s;
  703. } },
  704. { "STRIP", 0,
  705. [&command](const std::string& s) -> std::string {
  706. if (command.Selector->InSelection(s)) {
  707. return cmTrimWhitespace(s);
  708. }
  709. return s;
  710. } },
  711. { "GENEX_STRIP", 0,
  712. [&command](const std::string& s) -> std::string {
  713. if (command.Selector->InSelection(s)) {
  714. return cmGeneratorExpression::Preprocess(
  715. s,
  716. cmGeneratorExpression::StripAllGeneratorExpressions);
  717. }
  718. return s;
  719. } },
  720. { "REPLACE", 2,
  721. [&command](const std::string& s) -> std::string {
  722. if (command.Selector->InSelection(s)) {
  723. return command.Action->Transform(s);
  724. }
  725. return s;
  726. } } };
  727. using size_type = std::vector<std::string>::size_type;
  728. size_type index = 2;
  729. // Parse all possible function parameters
  730. auto descriptor = descriptors.find(args[index]);
  731. if (descriptor == descriptors.end()) {
  732. std::ostringstream error;
  733. error << " sub-command TRANSFORM, " << args[index] << " invalid action.";
  734. status.SetError(error.str());
  735. return false;
  736. }
  737. // Action arguments
  738. index += 1;
  739. if (args.size() < index + descriptor->Arity) {
  740. std::ostringstream error;
  741. error << "sub-command TRANSFORM, action " << descriptor->Name
  742. << " expects " << descriptor->Arity << " argument(s).";
  743. status.SetError(error.str());
  744. return false;
  745. }
  746. command.Name = descriptor->Name;
  747. index += descriptor->Arity;
  748. if (descriptor->Arity > 0) {
  749. command.Arguments =
  750. std::vector<std::string>(args.begin() + 3, args.begin() + index);
  751. }
  752. if (command.Name == "REPLACE") {
  753. try {
  754. command.Action = cm::make_unique<TransformReplace>(
  755. command.Arguments, &status.GetMakefile());
  756. } catch (const transform_error& e) {
  757. status.SetError(e.what());
  758. return false;
  759. }
  760. }
  761. const std::string REGEX{ "REGEX" };
  762. const std::string AT{ "AT" };
  763. const std::string FOR{ "FOR" };
  764. const std::string OUTPUT_VARIABLE{ "OUTPUT_VARIABLE" };
  765. // handle optional arguments
  766. while (args.size() > index) {
  767. if ((args[index] == REGEX || args[index] == AT || args[index] == FOR) &&
  768. command.Selector) {
  769. std::ostringstream error;
  770. error << "sub-command TRANSFORM, selector already specified ("
  771. << command.Selector->Tag << ").";
  772. status.SetError(error.str());
  773. return false;
  774. }
  775. // REGEX selector
  776. if (args[index] == REGEX) {
  777. if (args.size() == ++index) {
  778. status.SetError("sub-command TRANSFORM, selector REGEX expects "
  779. "'regular expression' argument.");
  780. return false;
  781. }
  782. command.Selector = cm::make_unique<TransformSelectorRegex>(args[index]);
  783. if (!command.Selector->Validate()) {
  784. std::ostringstream error;
  785. error << "sub-command TRANSFORM, selector REGEX failed to compile "
  786. "regex \"";
  787. error << args[index] << "\".";
  788. status.SetError(error.str());
  789. return false;
  790. }
  791. index += 1;
  792. continue;
  793. }
  794. // AT selector
  795. if (args[index] == AT) {
  796. // get all specified indexes
  797. std::vector<int> indexes;
  798. while (args.size() > ++index) {
  799. std::size_t pos;
  800. int value;
  801. try {
  802. value = std::stoi(args[index], &pos);
  803. if (pos != args[index].length()) {
  804. // this is not a number, stop processing
  805. break;
  806. }
  807. indexes.push_back(value);
  808. } catch (const std::invalid_argument&) {
  809. // this is not a number, stop processing
  810. break;
  811. }
  812. }
  813. if (indexes.empty()) {
  814. status.SetError(
  815. "sub-command TRANSFORM, selector AT expects at least one "
  816. "numeric value.");
  817. return false;
  818. }
  819. command.Selector =
  820. cm::make_unique<TransformSelectorAt>(std::move(indexes));
  821. continue;
  822. }
  823. // FOR selector
  824. if (args[index] == FOR) {
  825. if (args.size() <= ++index + 1) {
  826. status.SetError(
  827. "sub-command TRANSFORM, selector FOR expects, at least,"
  828. " two arguments.");
  829. return false;
  830. }
  831. int start = 0;
  832. int stop = 0;
  833. int step = 1;
  834. bool valid = true;
  835. try {
  836. std::size_t pos;
  837. start = std::stoi(args[index], &pos);
  838. if (pos != args[index].length()) {
  839. // this is not a number
  840. valid = false;
  841. } else {
  842. stop = std::stoi(args[++index], &pos);
  843. if (pos != args[index].length()) {
  844. // this is not a number
  845. valid = false;
  846. }
  847. }
  848. } catch (const std::invalid_argument&) {
  849. // this is not numbers
  850. valid = false;
  851. }
  852. if (!valid) {
  853. status.SetError("sub-command TRANSFORM, selector FOR expects, "
  854. "at least, two numeric values.");
  855. return false;
  856. }
  857. // try to read a third numeric value for step
  858. if (args.size() > ++index) {
  859. try {
  860. std::size_t pos;
  861. step = std::stoi(args[index], &pos);
  862. if (pos != args[index].length()) {
  863. // this is not a number
  864. step = 1;
  865. } else {
  866. index += 1;
  867. }
  868. } catch (const std::invalid_argument&) {
  869. // this is not number, ignore exception
  870. }
  871. }
  872. if (step < 0) {
  873. status.SetError("sub-command TRANSFORM, selector FOR expects "
  874. "non negative numeric value for <step>.");
  875. }
  876. command.Selector =
  877. cm::make_unique<TransformSelectorFor>(start, stop, step);
  878. continue;
  879. }
  880. // output variable
  881. if (args[index] == OUTPUT_VARIABLE) {
  882. if (args.size() == ++index) {
  883. status.SetError("sub-command TRANSFORM, OUTPUT_VARIABLE "
  884. "expects variable name argument.");
  885. return false;
  886. }
  887. command.OutputName = args[index++];
  888. continue;
  889. }
  890. std::ostringstream error;
  891. error << "sub-command TRANSFORM, '"
  892. << cmJoin(cmMakeRange(args).advance(index), " ")
  893. << "': unexpected argument(s).";
  894. status.SetError(error.str());
  895. return false;
  896. }
  897. // expand the list variable
  898. std::vector<std::string> varArgsExpanded;
  899. if (!GetList(varArgsExpanded, command.ListName, status.GetMakefile())) {
  900. status.GetMakefile().AddDefinition(command.OutputName, "");
  901. return true;
  902. }
  903. if (!command.Selector) {
  904. // no selector specified, apply transformation to all elements
  905. command.Selector = cm::make_unique<TransformNoSelector>();
  906. }
  907. try {
  908. command.Selector->Transform(varArgsExpanded, descriptor->Transform);
  909. } catch (const transform_error& e) {
  910. status.SetError(e.what());
  911. return false;
  912. }
  913. status.GetMakefile().AddDefinition(command.OutputName,
  914. cmJoin(varArgsExpanded, ";"));
  915. return true;
  916. }
  917. class cmStringSorter
  918. {
  919. public:
  920. enum class Order
  921. {
  922. UNINITIALIZED,
  923. ASCENDING,
  924. DESCENDING,
  925. };
  926. enum class Compare
  927. {
  928. UNINITIALIZED,
  929. STRING,
  930. FILE_BASENAME,
  931. };
  932. enum class CaseSensitivity
  933. {
  934. UNINITIALIZED,
  935. SENSITIVE,
  936. INSENSITIVE,
  937. };
  938. protected:
  939. typedef std::string (*StringFilter)(const std::string& in);
  940. StringFilter GetCompareFilter(Compare compare)
  941. {
  942. return (compare == Compare::FILE_BASENAME) ? cmSystemTools::GetFilenameName
  943. : nullptr;
  944. }
  945. StringFilter GetCaseFilter(CaseSensitivity sensitivity)
  946. {
  947. return (sensitivity == CaseSensitivity::INSENSITIVE)
  948. ? cmSystemTools::LowerCase
  949. : nullptr;
  950. }
  951. public:
  952. cmStringSorter(Compare compare, CaseSensitivity caseSensitivity,
  953. Order desc = Order::ASCENDING)
  954. : filters{ GetCompareFilter(compare), GetCaseFilter(caseSensitivity) }
  955. , descending(desc == Order::DESCENDING)
  956. {
  957. }
  958. std::string ApplyFilter(const std::string& argument)
  959. {
  960. std::string result = argument;
  961. for (auto filter : filters) {
  962. if (filter != nullptr) {
  963. result = filter(result);
  964. }
  965. }
  966. return result;
  967. }
  968. bool operator()(const std::string& a, const std::string& b)
  969. {
  970. std::string af = ApplyFilter(a);
  971. std::string bf = ApplyFilter(b);
  972. bool result;
  973. if (descending) {
  974. result = bf < af;
  975. } else {
  976. result = af < bf;
  977. }
  978. return result;
  979. }
  980. protected:
  981. StringFilter filters[2] = { nullptr, nullptr };
  982. bool descending;
  983. };
  984. bool HandleSortCommand(std::vector<std::string> const& args,
  985. cmExecutionStatus& status)
  986. {
  987. assert(args.size() >= 2);
  988. if (args.size() > 8) {
  989. status.SetError("sub-command SORT only takes up to six arguments.");
  990. return false;
  991. }
  992. auto sortCompare = cmStringSorter::Compare::UNINITIALIZED;
  993. auto sortCaseSensitivity = cmStringSorter::CaseSensitivity::UNINITIALIZED;
  994. auto sortOrder = cmStringSorter::Order::UNINITIALIZED;
  995. size_t argumentIndex = 2;
  996. const std::string messageHint = "sub-command SORT ";
  997. while (argumentIndex < args.size()) {
  998. const std::string option = args[argumentIndex++];
  999. if (option == "COMPARE") {
  1000. if (sortCompare != cmStringSorter::Compare::UNINITIALIZED) {
  1001. std::string error = cmStrCat(messageHint, "option \"", option,
  1002. "\" has been specified multiple times.");
  1003. status.SetError(error);
  1004. return false;
  1005. }
  1006. if (argumentIndex < args.size()) {
  1007. const std::string argument = args[argumentIndex++];
  1008. if (argument == "STRING") {
  1009. sortCompare = cmStringSorter::Compare::STRING;
  1010. } else if (argument == "FILE_BASENAME") {
  1011. sortCompare = cmStringSorter::Compare::FILE_BASENAME;
  1012. } else {
  1013. std::string error =
  1014. cmStrCat(messageHint, "value \"", argument, "\" for option \"",
  1015. option, "\" is invalid.");
  1016. status.SetError(error);
  1017. return false;
  1018. }
  1019. } else {
  1020. status.SetError(cmStrCat(messageHint, "missing argument for option \"",
  1021. option, "\"."));
  1022. return false;
  1023. }
  1024. } else if (option == "CASE") {
  1025. if (sortCaseSensitivity !=
  1026. cmStringSorter::CaseSensitivity::UNINITIALIZED) {
  1027. status.SetError(cmStrCat(messageHint, "option \"", option,
  1028. "\" has been specified multiple times."));
  1029. return false;
  1030. }
  1031. if (argumentIndex < args.size()) {
  1032. const std::string argument = args[argumentIndex++];
  1033. if (argument == "SENSITIVE") {
  1034. sortCaseSensitivity = cmStringSorter::CaseSensitivity::SENSITIVE;
  1035. } else if (argument == "INSENSITIVE") {
  1036. sortCaseSensitivity = cmStringSorter::CaseSensitivity::INSENSITIVE;
  1037. } else {
  1038. status.SetError(cmStrCat(messageHint, "value \"", argument,
  1039. "\" for option \"", option,
  1040. "\" is invalid."));
  1041. return false;
  1042. }
  1043. } else {
  1044. status.SetError(cmStrCat(messageHint, "missing argument for option \"",
  1045. option, "\"."));
  1046. return false;
  1047. }
  1048. } else if (option == "ORDER") {
  1049. if (sortOrder != cmStringSorter::Order::UNINITIALIZED) {
  1050. status.SetError(cmStrCat(messageHint, "option \"", option,
  1051. "\" has been specified multiple times."));
  1052. return false;
  1053. }
  1054. if (argumentIndex < args.size()) {
  1055. const std::string argument = args[argumentIndex++];
  1056. if (argument == "ASCENDING") {
  1057. sortOrder = cmStringSorter::Order::ASCENDING;
  1058. } else if (argument == "DESCENDING") {
  1059. sortOrder = cmStringSorter::Order::DESCENDING;
  1060. } else {
  1061. status.SetError(cmStrCat(messageHint, "value \"", argument,
  1062. "\" for option \"", option,
  1063. "\" is invalid."));
  1064. return false;
  1065. }
  1066. } else {
  1067. status.SetError(cmStrCat(messageHint, "missing argument for option \"",
  1068. option, "\"."));
  1069. return false;
  1070. }
  1071. } else {
  1072. status.SetError(
  1073. cmStrCat(messageHint, "option \"", option, "\" is unknown."));
  1074. return false;
  1075. }
  1076. }
  1077. // set Default Values if Option is not given
  1078. if (sortCompare == cmStringSorter::Compare::UNINITIALIZED) {
  1079. sortCompare = cmStringSorter::Compare::STRING;
  1080. }
  1081. if (sortCaseSensitivity == cmStringSorter::CaseSensitivity::UNINITIALIZED) {
  1082. sortCaseSensitivity = cmStringSorter::CaseSensitivity::SENSITIVE;
  1083. }
  1084. if (sortOrder == cmStringSorter::Order::UNINITIALIZED) {
  1085. sortOrder = cmStringSorter::Order::ASCENDING;
  1086. }
  1087. const std::string& listName = args[1];
  1088. // expand the variable
  1089. std::vector<std::string> varArgsExpanded;
  1090. if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
  1091. return true;
  1092. }
  1093. if ((sortCompare == cmStringSorter::Compare::STRING) &&
  1094. (sortCaseSensitivity == cmStringSorter::CaseSensitivity::SENSITIVE) &&
  1095. (sortOrder == cmStringSorter::Order::ASCENDING)) {
  1096. std::sort(varArgsExpanded.begin(), varArgsExpanded.end());
  1097. } else {
  1098. cmStringSorter sorter(sortCompare, sortCaseSensitivity, sortOrder);
  1099. std::sort(varArgsExpanded.begin(), varArgsExpanded.end(), sorter);
  1100. }
  1101. std::string value = cmJoin(varArgsExpanded, ";");
  1102. status.GetMakefile().AddDefinition(listName, value);
  1103. return true;
  1104. }
  1105. bool HandleSublistCommand(std::vector<std::string> const& args,
  1106. cmExecutionStatus& status)
  1107. {
  1108. if (args.size() != 5) {
  1109. std::ostringstream error;
  1110. error << "sub-command SUBLIST requires four arguments (" << args.size() - 1
  1111. << " found).";
  1112. status.SetError(error.str());
  1113. return false;
  1114. }
  1115. const std::string& listName = args[1];
  1116. const std::string& variableName = args.back();
  1117. // expand the variable
  1118. std::vector<std::string> varArgsExpanded;
  1119. if (!GetList(varArgsExpanded, listName, status.GetMakefile()) ||
  1120. varArgsExpanded.empty()) {
  1121. status.GetMakefile().AddDefinition(variableName, "");
  1122. return true;
  1123. }
  1124. const int start = atoi(args[2].c_str());
  1125. const int length = atoi(args[3].c_str());
  1126. using size_type = decltype(varArgsExpanded)::size_type;
  1127. if (start < 0 || size_type(start) >= varArgsExpanded.size()) {
  1128. std::ostringstream error;
  1129. error << "begin index: " << start << " is out of range 0 - "
  1130. << varArgsExpanded.size() - 1;
  1131. status.SetError(error.str());
  1132. return false;
  1133. }
  1134. if (length < -1) {
  1135. std::ostringstream error;
  1136. error << "length: " << length << " should be -1 or greater";
  1137. status.SetError(error.str());
  1138. return false;
  1139. }
  1140. const size_type end =
  1141. (length == -1 || size_type(start + length) > varArgsExpanded.size())
  1142. ? varArgsExpanded.size()
  1143. : size_type(start + length);
  1144. std::vector<std::string> sublist(varArgsExpanded.begin() + start,
  1145. varArgsExpanded.begin() + end);
  1146. status.GetMakefile().AddDefinition(variableName, cmJoin(sublist, ";"));
  1147. return true;
  1148. }
  1149. bool HandleRemoveAtCommand(std::vector<std::string> const& args,
  1150. cmExecutionStatus& status)
  1151. {
  1152. if (args.size() < 3) {
  1153. status.SetError("sub-command REMOVE_AT requires at least "
  1154. "two arguments.");
  1155. return false;
  1156. }
  1157. const std::string& listName = args[1];
  1158. // expand the variable
  1159. std::vector<std::string> varArgsExpanded;
  1160. if (!GetList(varArgsExpanded, listName, status.GetMakefile()) ||
  1161. varArgsExpanded.empty()) {
  1162. std::ostringstream str;
  1163. str << "index: ";
  1164. for (size_t i = 1; i < args.size(); ++i) {
  1165. str << args[i];
  1166. if (i != args.size() - 1) {
  1167. str << ", ";
  1168. }
  1169. }
  1170. str << " out of range (0, 0)";
  1171. status.SetError(str.str());
  1172. return false;
  1173. }
  1174. size_t cc;
  1175. std::vector<size_t> removed;
  1176. size_t nitem = varArgsExpanded.size();
  1177. for (cc = 2; cc < args.size(); ++cc) {
  1178. int item = atoi(args[cc].c_str());
  1179. if (item < 0) {
  1180. item = static_cast<int>(nitem) + item;
  1181. }
  1182. if (item < 0 || nitem <= static_cast<size_t>(item)) {
  1183. std::ostringstream str;
  1184. str << "index: " << item << " out of range (-" << nitem << ", "
  1185. << nitem - 1 << ")";
  1186. status.SetError(str.str());
  1187. return false;
  1188. }
  1189. removed.push_back(static_cast<size_t>(item));
  1190. }
  1191. std::sort(removed.begin(), removed.end());
  1192. std::vector<size_t>::const_iterator remEnd =
  1193. std::unique(removed.begin(), removed.end());
  1194. std::vector<size_t>::const_iterator remBegin = removed.begin();
  1195. std::vector<std::string>::const_iterator argsEnd =
  1196. cmRemoveIndices(varArgsExpanded, cmMakeRange(remBegin, remEnd));
  1197. std::vector<std::string>::const_iterator argsBegin = varArgsExpanded.begin();
  1198. std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";");
  1199. status.GetMakefile().AddDefinition(listName, value);
  1200. return true;
  1201. }
  1202. bool HandleFilterCommand(std::vector<std::string> const& args,
  1203. cmExecutionStatus& status)
  1204. {
  1205. if (args.size() < 2) {
  1206. status.SetError("sub-command FILTER requires a list to be specified.");
  1207. return false;
  1208. }
  1209. if (args.size() < 3) {
  1210. status.SetError(
  1211. "sub-command FILTER requires an operator to be specified.");
  1212. return false;
  1213. }
  1214. if (args.size() < 4) {
  1215. status.SetError("sub-command FILTER requires a mode to be specified.");
  1216. return false;
  1217. }
  1218. const std::string& op = args[2];
  1219. bool includeMatches;
  1220. if (op == "INCLUDE") {
  1221. includeMatches = true;
  1222. } else if (op == "EXCLUDE") {
  1223. includeMatches = false;
  1224. } else {
  1225. status.SetError("sub-command FILTER does not recognize operator " + op);
  1226. return false;
  1227. }
  1228. const std::string& listName = args[1];
  1229. // expand the variable
  1230. std::vector<std::string> varArgsExpanded;
  1231. if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
  1232. return true;
  1233. }
  1234. const std::string& mode = args[3];
  1235. if (mode == "REGEX") {
  1236. if (args.size() != 5) {
  1237. status.SetError("sub-command FILTER, mode REGEX "
  1238. "requires five arguments.");
  1239. return false;
  1240. }
  1241. return FilterRegex(args, includeMatches, listName, varArgsExpanded,
  1242. status);
  1243. }
  1244. status.SetError("sub-command FILTER does not recognize mode " + mode);
  1245. return false;
  1246. }
  1247. class MatchesRegex
  1248. {
  1249. public:
  1250. MatchesRegex(cmsys::RegularExpression& in_regex, bool in_includeMatches)
  1251. : regex(in_regex)
  1252. , includeMatches(in_includeMatches)
  1253. {
  1254. }
  1255. bool operator()(const std::string& target)
  1256. {
  1257. return regex.find(target) ^ includeMatches;
  1258. }
  1259. private:
  1260. cmsys::RegularExpression& regex;
  1261. const bool includeMatches;
  1262. };
  1263. bool FilterRegex(std::vector<std::string> const& args, bool includeMatches,
  1264. std::string const& listName,
  1265. std::vector<std::string>& varArgsExpanded,
  1266. cmExecutionStatus& status)
  1267. {
  1268. const std::string& pattern = args[4];
  1269. cmsys::RegularExpression regex(pattern);
  1270. if (!regex.is_valid()) {
  1271. std::string error =
  1272. cmStrCat("sub-command FILTER, mode REGEX failed to compile regex \"",
  1273. pattern, "\".");
  1274. status.SetError(error);
  1275. return false;
  1276. }
  1277. std::vector<std::string>::iterator argsBegin = varArgsExpanded.begin();
  1278. std::vector<std::string>::iterator argsEnd = varArgsExpanded.end();
  1279. std::vector<std::string>::iterator newArgsEnd =
  1280. std::remove_if(argsBegin, argsEnd, MatchesRegex(regex, includeMatches));
  1281. std::string value = cmJoin(cmMakeRange(argsBegin, newArgsEnd), ";");
  1282. status.GetMakefile().AddDefinition(listName, value);
  1283. return true;
  1284. }
  1285. } // namespace
  1286. bool cmListCommand(std::vector<std::string> const& args,
  1287. cmExecutionStatus& status)
  1288. {
  1289. if (args.size() < 2) {
  1290. status.SetError("must be called with at least two arguments.");
  1291. return false;
  1292. }
  1293. static cmSubcommandTable const subcommand{
  1294. { "LENGTH"_s, HandleLengthCommand },
  1295. { "GET"_s, HandleGetCommand },
  1296. { "APPEND"_s, HandleAppendCommand },
  1297. { "PREPEND"_s, HandlePrependCommand },
  1298. { "POP_BACK"_s, HandlePopBackCommand },
  1299. { "POP_FRONT"_s, HandlePopFrontCommand },
  1300. { "FIND"_s, HandleFindCommand },
  1301. { "INSERT"_s, HandleInsertCommand },
  1302. { "JOIN"_s, HandleJoinCommand },
  1303. { "REMOVE_AT"_s, HandleRemoveAtCommand },
  1304. { "REMOVE_ITEM"_s, HandleRemoveItemCommand },
  1305. { "REMOVE_DUPLICATES"_s, HandleRemoveDuplicatesCommand },
  1306. { "TRANSFORM"_s, HandleTransformCommand },
  1307. { "SORT"_s, HandleSortCommand },
  1308. { "SUBLIST"_s, HandleSublistCommand },
  1309. { "REVERSE"_s, HandleReverseCommand },
  1310. { "FILTER"_s, HandleFilterCommand },
  1311. };
  1312. return subcommand(args[0], args, status);
  1313. }