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