cmForEachCommand.cxx 15 KB

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