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