cmListCommand.cxx 43 KB

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