cmForEachCommand.cxx 13 KB

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