cmForEachCommand.cxx 15 KB

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