cmForEachCommand.cxx 11 KB

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