cmForEachCommand.cxx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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 "cmForEachCommand.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstddef> // IWYU pragma: keep
  7. // NOTE The declaration of `std::abs` has moved to `cmath` since C++17
  8. // See https://en.cppreference.com/w/cpp/numeric/math/abs
  9. // ALERT But IWYU used to lint `#include`s do not "understand"
  10. // conditional compilation (i.e. `#if __cplusplus >= 201703L`)
  11. #include <cstdlib>
  12. #include <iterator>
  13. #include <map>
  14. #include <sstream>
  15. #include <stdexcept>
  16. #include <utility>
  17. #include <cm/memory>
  18. #include <cm/string_view>
  19. #include <cmext/string_view>
  20. #include "cmExecutionStatus.h"
  21. #include "cmFunctionBlocker.h"
  22. #include "cmListFileCache.h"
  23. #include "cmMakefile.h"
  24. #include "cmMessageType.h"
  25. #include "cmProperty.h"
  26. #include "cmRange.h"
  27. #include "cmStringAlgorithms.h"
  28. #include "cmSystemTools.h"
  29. namespace {
  30. class cmForEachFunctionBlocker : public cmFunctionBlocker
  31. {
  32. public:
  33. explicit cmForEachFunctionBlocker(cmMakefile* mf);
  34. ~cmForEachFunctionBlocker() override;
  35. cm::string_view StartCommandName() const override { return "foreach"_s; }
  36. cm::string_view EndCommandName() const override { return "endforeach"_s; }
  37. bool ArgumentsMatch(cmListFileFunction const& lff,
  38. cmMakefile& mf) const override;
  39. bool Replay(std::vector<cmListFileFunction> functions,
  40. cmExecutionStatus& inStatus) override;
  41. void SetIterationVarsCount(const std::size_t varsCount)
  42. {
  43. this->IterationVarsCount = varsCount;
  44. }
  45. void SetZipLists() { this->ZipLists = true; }
  46. std::vector<std::string> Args;
  47. private:
  48. struct InvokeResult
  49. {
  50. bool Restore;
  51. bool Break;
  52. };
  53. bool ReplayItems(std::vector<cmListFileFunction> const& functions,
  54. cmExecutionStatus& inStatus);
  55. bool ReplayZipLists(std::vector<cmListFileFunction> const& functions,
  56. cmExecutionStatus& inStatus);
  57. InvokeResult invoke(std::vector<cmListFileFunction> const& functions,
  58. cmExecutionStatus& inStatus, cmMakefile& mf);
  59. cmMakefile* Makefile;
  60. std::size_t IterationVarsCount = 0u;
  61. bool ZipLists = false;
  62. };
  63. cmForEachFunctionBlocker::cmForEachFunctionBlocker(cmMakefile* mf)
  64. : Makefile(mf)
  65. {
  66. this->Makefile->PushLoopBlock();
  67. }
  68. cmForEachFunctionBlocker::~cmForEachFunctionBlocker()
  69. {
  70. this->Makefile->PopLoopBlock();
  71. }
  72. bool cmForEachFunctionBlocker::ArgumentsMatch(cmListFileFunction const& lff,
  73. cmMakefile& mf) const
  74. {
  75. std::vector<std::string> expandedArguments;
  76. mf.ExpandArguments(lff.Arguments, expandedArguments);
  77. return expandedArguments.empty() ||
  78. expandedArguments.front() == this->Args.front();
  79. }
  80. bool cmForEachFunctionBlocker::Replay(
  81. std::vector<cmListFileFunction> functions, cmExecutionStatus& inStatus)
  82. {
  83. return this->ZipLists ? this->ReplayZipLists(functions, inStatus)
  84. : this->ReplayItems(functions, inStatus);
  85. }
  86. bool cmForEachFunctionBlocker::ReplayItems(
  87. std::vector<cmListFileFunction> const& functions,
  88. cmExecutionStatus& inStatus)
  89. {
  90. assert("Unexpected number of iteration variables" &&
  91. this->IterationVarsCount == 1);
  92. auto& mf = inStatus.GetMakefile();
  93. // At end of for each execute recorded commands
  94. // store the old value
  95. std::string oldDef;
  96. if (cmProp d = mf.GetDefinition(this->Args.front())) {
  97. oldDef = *d;
  98. }
  99. auto restore = false;
  100. for (std::string const& arg : cmMakeRange(this->Args).advance(1)) {
  101. // Set the variable to the loop value
  102. mf.AddDefinition(this->Args.front(), arg);
  103. // Invoke all the functions that were collected in the block.
  104. auto r = this->invoke(functions, inStatus, mf);
  105. restore = r.Restore;
  106. if (r.Break) {
  107. break;
  108. }
  109. }
  110. if (restore) {
  111. // restore the variable to its prior value
  112. mf.AddDefinition(this->Args.front(), oldDef);
  113. }
  114. return true;
  115. }
  116. bool cmForEachFunctionBlocker::ReplayZipLists(
  117. std::vector<cmListFileFunction> const& functions,
  118. cmExecutionStatus& inStatus)
  119. {
  120. assert("Unexpected number of iteration variables" &&
  121. this->IterationVarsCount >= 1);
  122. auto& mf = inStatus.GetMakefile();
  123. // Expand the list of list-variables into a list of lists of strings
  124. std::vector<std::vector<std::string>> values;
  125. values.reserve(this->Args.size() - this->IterationVarsCount);
  126. // Also track the longest list size
  127. std::size_t maxItems = 0u;
  128. for (auto const& var :
  129. cmMakeRange(this->Args).advance(this->IterationVarsCount)) {
  130. std::vector<std::string> items;
  131. auto const& value = mf.GetSafeDefinition(var);
  132. if (!value.empty()) {
  133. cmExpandList(value, items, true);
  134. }
  135. maxItems = std::max(maxItems, items.size());
  136. values.emplace_back(std::move(items));
  137. }
  138. // Form the list of iteration variables
  139. std::vector<std::string> iterationVars;
  140. if (this->IterationVarsCount > 1) {
  141. // If multiple iteration variables has given,
  142. // just copy them to the `iterationVars` list.
  143. iterationVars.reserve(values.size());
  144. std::copy(this->Args.begin(),
  145. this->Args.begin() + this->IterationVarsCount,
  146. std::back_inserter(iterationVars));
  147. } else {
  148. // In case of the only iteration variable,
  149. // generate names as `var_name_N`,
  150. // where `N` is the count of lists to zip
  151. iterationVars.resize(values.size());
  152. const auto iter_var_prefix = this->Args.front() + "_";
  153. auto i = 0u;
  154. std::generate(
  155. iterationVars.begin(), iterationVars.end(),
  156. [&]() -> std::string { return iter_var_prefix + std::to_string(i++); });
  157. }
  158. assert("Sanity check" && iterationVars.size() == values.size());
  159. // Store old values for iteration variables
  160. std::map<std::string, std::string> oldDefs;
  161. for (auto i = 0u; i < values.size(); ++i) {
  162. if (cmProp d = mf.GetDefinition(iterationVars[i])) {
  163. oldDefs.emplace(iterationVars[i], *d);
  164. }
  165. }
  166. // Form a vector of current positions in all lists (Ok, vectors) of values
  167. std::vector<decltype(values)::value_type::iterator> positions;
  168. positions.reserve(values.size());
  169. std::transform(
  170. values.begin(), values.end(), std::back_inserter(positions),
  171. // Set the initial position to the beginning of every list
  172. [](decltype(values)::value_type& list) { return list.begin(); });
  173. assert("Sanity check" && positions.size() == values.size());
  174. auto restore = false;
  175. // Iterate over all the lists simulateneously
  176. for (auto i = 0u; i < maxItems; ++i) {
  177. // Declare iteration variables
  178. for (auto j = 0u; j < values.size(); ++j) {
  179. // Define (or not) the iteration variable if the current position
  180. // still not at the end...
  181. if (positions[j] != values[j].end()) {
  182. mf.AddDefinition(iterationVars[j], *positions[j]);
  183. ++positions[j];
  184. } else {
  185. mf.RemoveDefinition(iterationVars[j]);
  186. }
  187. }
  188. // Invoke all the functions that were collected in the block.
  189. auto r = this->invoke(functions, inStatus, mf);
  190. restore = r.Restore;
  191. if (r.Break) {
  192. break;
  193. }
  194. }
  195. // Restore the variables to its prior value
  196. if (restore) {
  197. for (auto const& p : oldDefs) {
  198. mf.AddDefinition(p.first, p.second);
  199. }
  200. }
  201. return true;
  202. }
  203. auto cmForEachFunctionBlocker::invoke(
  204. std::vector<cmListFileFunction> const& functions,
  205. cmExecutionStatus& inStatus, cmMakefile& mf) -> InvokeResult
  206. {
  207. InvokeResult result = { true, false };
  208. // Invoke all the functions that were collected in the block.
  209. for (cmListFileFunction const& func : functions) {
  210. cmExecutionStatus status(mf);
  211. mf.ExecuteCommand(func, status);
  212. if (status.GetReturnInvoked()) {
  213. inStatus.SetReturnInvoked();
  214. result.Break = true;
  215. break;
  216. }
  217. if (status.GetBreakInvoked()) {
  218. result.Break = true;
  219. break;
  220. }
  221. if (status.GetContinueInvoked()) {
  222. break;
  223. }
  224. if (cmSystemTools::GetFatalErrorOccured()) {
  225. result.Restore = false;
  226. result.Break = true;
  227. break;
  228. }
  229. }
  230. return result;
  231. }
  232. bool HandleInMode(std::vector<std::string> const& args,
  233. std::vector<std::string>::const_iterator kwInIter,
  234. cmMakefile& makefile)
  235. {
  236. assert("A valid iterator expected" && kwInIter != args.end());
  237. auto fb = cm::make_unique<cmForEachFunctionBlocker>(&makefile);
  238. // Copy iteration variable names first
  239. std::copy(args.begin(), kwInIter, std::back_inserter(fb->Args));
  240. // Remember the count of given iteration variable names
  241. const auto varsCount = fb->Args.size();
  242. fb->SetIterationVarsCount(varsCount);
  243. enum Doing
  244. {
  245. DoingNone,
  246. DoingLists,
  247. DoingItems,
  248. DoingZipLists
  249. };
  250. Doing doing = DoingNone;
  251. // Iterate over arguments past the "IN" keyword
  252. for (std::string const& arg : cmMakeRange(++kwInIter, args.end())) {
  253. if (arg == "LISTS") {
  254. if (doing == DoingZipLists) {
  255. makefile.IssueMessage(MessageType::FATAL_ERROR,
  256. "ZIP_LISTS can not be used with LISTS or ITEMS");
  257. return true;
  258. }
  259. if (varsCount != 1u) {
  260. makefile.IssueMessage(
  261. MessageType::FATAL_ERROR,
  262. "ITEMS or LISTS require exactly one iteration variable");
  263. return true;
  264. }
  265. doing = DoingLists;
  266. } else if (arg == "ITEMS") {
  267. if (doing == DoingZipLists) {
  268. makefile.IssueMessage(MessageType::FATAL_ERROR,
  269. "ZIP_LISTS can not be used with LISTS or ITEMS");
  270. return true;
  271. }
  272. if (varsCount != 1u) {
  273. makefile.IssueMessage(
  274. MessageType::FATAL_ERROR,
  275. "ITEMS or LISTS require exactly one iteration variable");
  276. return true;
  277. }
  278. doing = DoingItems;
  279. } else if (arg == "ZIP_LISTS") {
  280. if (doing != DoingNone) {
  281. makefile.IssueMessage(MessageType::FATAL_ERROR,
  282. "ZIP_LISTS can not be used with LISTS or ITEMS");
  283. return true;
  284. }
  285. doing = DoingZipLists;
  286. fb->SetZipLists();
  287. } else if (doing == DoingLists) {
  288. auto const& value = makefile.GetSafeDefinition(arg);
  289. if (!value.empty()) {
  290. cmExpandList(value, fb->Args, true);
  291. }
  292. } else if (doing == DoingItems || doing == DoingZipLists) {
  293. fb->Args.push_back(arg);
  294. } else {
  295. makefile.IssueMessage(MessageType::FATAL_ERROR,
  296. cmStrCat("Unknown argument:\n", " ", arg, "\n"));
  297. return true;
  298. }
  299. }
  300. // If `ZIP_LISTS` given and variables count more than 1,
  301. // make sure the given lists count matches variables...
  302. if (doing == DoingZipLists && varsCount > 1u &&
  303. (2u * varsCount) != fb->Args.size()) {
  304. makefile.IssueMessage(
  305. MessageType::FATAL_ERROR,
  306. cmStrCat("Expected ", std::to_string(varsCount),
  307. " list variables, but given ",
  308. std::to_string(fb->Args.size() - varsCount)));
  309. return true;
  310. }
  311. makefile.AddFunctionBlocker(std::move(fb));
  312. return true;
  313. }
  314. bool TryParseInteger(cmExecutionStatus& status, const std::string& str, int& i)
  315. {
  316. try {
  317. i = std::stoi(str);
  318. } catch (std::invalid_argument&) {
  319. std::ostringstream e;
  320. e << "Invalid integer: '" << str << "'";
  321. status.SetError(e.str());
  322. cmSystemTools::SetFatalErrorOccured();
  323. return false;
  324. }
  325. return true;
  326. }
  327. } // anonymous namespace
  328. bool cmForEachCommand(std::vector<std::string> const& args,
  329. cmExecutionStatus& status)
  330. {
  331. if (args.empty()) {
  332. status.SetError("called with incorrect number of arguments");
  333. return false;
  334. }
  335. auto kwInIter = std::find(args.begin(), args.end(), "IN");
  336. if (kwInIter != args.end()) {
  337. return HandleInMode(args, kwInIter, status.GetMakefile());
  338. }
  339. // create a function blocker
  340. auto fb = cm::make_unique<cmForEachFunctionBlocker>(&status.GetMakefile());
  341. if (args.size() > 1) {
  342. if (args[1] == "RANGE") {
  343. int start = 0;
  344. int stop = 0;
  345. int step = 0;
  346. if (args.size() == 3) {
  347. if (!TryParseInteger(status, args[2], stop)) {
  348. return false;
  349. }
  350. }
  351. if (args.size() == 4) {
  352. if (!TryParseInteger(status, args[2], start)) {
  353. return false;
  354. }
  355. if (!TryParseInteger(status, args[3], stop)) {
  356. return false;
  357. }
  358. }
  359. if (args.size() == 5) {
  360. if (!TryParseInteger(status, args[2], start)) {
  361. return false;
  362. }
  363. if (!TryParseInteger(status, args[3], stop)) {
  364. return false;
  365. }
  366. if (!TryParseInteger(status, args[4], step)) {
  367. return false;
  368. }
  369. }
  370. if (step == 0) {
  371. if (start > stop) {
  372. step = -1;
  373. } else {
  374. step = 1;
  375. }
  376. }
  377. if ((start > stop && step > 0) || (start < stop && step < 0) ||
  378. step == 0) {
  379. status.SetError(
  380. cmStrCat("called with incorrect range specification: start ", start,
  381. ", stop ", stop, ", step ", step));
  382. cmSystemTools::SetFatalErrorOccured();
  383. return false;
  384. }
  385. // Calculate expected iterations count and reserve enough space
  386. // in the `fb->Args` vector. The first item is the iteration variable
  387. // name...
  388. const std::size_t iter_cnt = 2u +
  389. int(start < stop) * (stop - start) / std::abs(step) +
  390. int(start > stop) * (start - stop) / std::abs(step);
  391. fb->Args.resize(iter_cnt);
  392. fb->Args.front() = args.front();
  393. auto cc = start;
  394. auto generator = [&cc, step]() -> std::string {
  395. auto result = std::to_string(cc);
  396. cc += step;
  397. return result;
  398. };
  399. // Fill the `range` vector w/ generated string values
  400. // (starting from 2nd position)
  401. std::generate(++fb->Args.begin(), fb->Args.end(), generator);
  402. } else {
  403. fb->Args = args;
  404. }
  405. } else {
  406. fb->Args = args;
  407. }
  408. fb->SetIterationVarsCount(1u);
  409. status.GetMakefile().AddFunctionBlocker(std::move(fb));
  410. return true;
  411. }