cmListCommand.cxx 45 KB

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