cmListCommand.cxx 44 KB

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