1
0

cmForEachCommand.cxx 15 KB

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