cmListCommand.cxx 39 KB

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