action_stack.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "explorer/interpreter/action_stack.h"
  5. #include "common/error.h"
  6. #include "explorer/interpreter/action.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "llvm/Support/Casting.h"
  9. #include "llvm/Support/Error.h"
  10. namespace Carbon {
  11. void ActionStack::Print(llvm::raw_ostream& out) const {
  12. llvm::ListSeparator sep(" ## ");
  13. for (const std::unique_ptr<Action>& action : todo_) {
  14. out << sep << *action;
  15. }
  16. }
  17. // OBSOLETE
  18. void ActionStack::PrintScopes(llvm::raw_ostream& out) const {
  19. llvm::ListSeparator sep(" ## ");
  20. for (const std::unique_ptr<Action>& action : todo_) {
  21. if (action->scope().has_value()) {
  22. out << sep << *action->scope();
  23. }
  24. }
  25. if (globals_.has_value()) {
  26. out << sep << *globals_;
  27. }
  28. // TODO: should we print constants as well?
  29. }
  30. void ActionStack::Start(std::unique_ptr<Action> action) {
  31. result_ = std::nullopt;
  32. CARBON_CHECK(todo_.IsEmpty());
  33. todo_.Push(std::move(action));
  34. }
  35. void ActionStack::Initialize(ValueNodeView value_node,
  36. Nonnull<const Value*> value) {
  37. for (const std::unique_ptr<Action>& action : todo_) {
  38. if (action->scope().has_value()) {
  39. action->scope()->Initialize(value_node, value);
  40. return;
  41. }
  42. }
  43. globals_->Initialize(value_node, value);
  44. }
  45. auto ActionStack::ValueOfNode(ValueNodeView value_node,
  46. SourceLocation source_loc) const
  47. -> ErrorOr<Nonnull<const Value*>> {
  48. std::optional<const Value*> constant_value = value_node.constant_value();
  49. if (constant_value.has_value()) {
  50. return *constant_value;
  51. }
  52. for (const std::unique_ptr<Action>& action : todo_) {
  53. // TODO: have static name resolution identify the scope of value_node
  54. // as an AstNode, and then perform lookup _only_ on the Action associated
  55. // with that node. This will help keep unwanted dynamic-scoping behavior
  56. // from sneaking in.
  57. if (action->scope().has_value()) {
  58. std::optional<Nonnull<const Value*>> result =
  59. action->scope()->Get(value_node);
  60. if (result.has_value()) {
  61. return *result;
  62. }
  63. }
  64. }
  65. if (globals_.has_value()) {
  66. std::optional<Nonnull<const Value*>> result = globals_->Get(value_node);
  67. if (result.has_value()) {
  68. return *result;
  69. }
  70. }
  71. // We don't know the value of this node, but at compile time we may still be
  72. // able to form a symbolic value for it. For example, in
  73. //
  74. // fn F[T:! Type](x: T) {}
  75. //
  76. // ... we don't know the value of `T` but can still symbolically evaluate it
  77. // to a `VariableType`. At runtime we need actual values.
  78. if (phase_ == Phase::CompileTime) {
  79. std::optional<const Value*> symbolic_identity =
  80. value_node.symbolic_identity();
  81. if (symbolic_identity.has_value()) {
  82. return *symbolic_identity;
  83. }
  84. }
  85. // TODO: Move these errors to compile time and explain them more clearly.
  86. return ProgramError(source_loc)
  87. << "could not find `" << value_node.base() << "`";
  88. }
  89. void ActionStack::MergeScope(RuntimeScope scope) {
  90. for (const std::unique_ptr<Action>& action : todo_) {
  91. if (action->scope().has_value()) {
  92. action->scope()->Merge(std::move(scope));
  93. return;
  94. }
  95. }
  96. if (globals_.has_value()) {
  97. globals_->Merge(std::move(scope));
  98. return;
  99. }
  100. CARBON_FATAL() << "No current scope";
  101. }
  102. void ActionStack::InitializeFragment(ContinuationValue::StackFragment& fragment,
  103. Nonnull<const Statement*> body) {
  104. std::vector<Nonnull<const RuntimeScope*>> scopes;
  105. for (const std::unique_ptr<Action>& action : todo_) {
  106. if (action->scope().has_value()) {
  107. scopes.push_back(&*action->scope());
  108. }
  109. }
  110. // We don't capture globals_ or constants_ because they're global.
  111. std::vector<std::unique_ptr<Action>> reversed_todo;
  112. reversed_todo.push_back(std::make_unique<StatementAction>(body));
  113. reversed_todo.push_back(
  114. std::make_unique<ScopeAction>(RuntimeScope::Capture(scopes)));
  115. fragment.StoreReversed(std::move(reversed_todo));
  116. }
  117. namespace {
  118. // The way in which FinishAction should be called for a particular kind of
  119. // action.
  120. enum class FinishActionKind {
  121. // FinishAction should not be passed a value.
  122. NoValue,
  123. // FinishAction should be passed a value.
  124. Value,
  125. // FinishAction should not be called. The Action needs custom handling.
  126. NeverCalled,
  127. };
  128. } // namespace
  129. static auto FinishActionKindFor(Action::Kind kind) -> FinishActionKind {
  130. switch (kind) {
  131. case Action::Kind::ExpressionAction:
  132. case Action::Kind::WitnessAction:
  133. case Action::Kind::LValAction:
  134. case Action::Kind::PatternAction:
  135. return FinishActionKind::Value;
  136. case Action::Kind::StatementAction:
  137. case Action::Kind::DeclarationAction:
  138. case Action::Kind::RecursiveAction:
  139. return FinishActionKind::NoValue;
  140. case Action::Kind::ScopeAction:
  141. case Action::Kind::CleanUpAction:
  142. case Action::Kind::DestroyAction:
  143. return FinishActionKind::NeverCalled;
  144. }
  145. }
  146. auto ActionStack::FinishAction() -> ErrorOr<Success> {
  147. std::stack<std::unique_ptr<Action>> scopes_to_destroy;
  148. std::unique_ptr<Action> act = todo_.Pop();
  149. switch (FinishActionKindFor(act->kind())) {
  150. case FinishActionKind::Value:
  151. CARBON_FATAL() << "This kind of action must produce a result: " << *act;
  152. case FinishActionKind::NeverCalled:
  153. CARBON_FATAL() << "Should not call FinishAction for: " << *act;
  154. case FinishActionKind::NoValue:
  155. PopScopes(scopes_to_destroy);
  156. break;
  157. }
  158. PushCleanUpAction(std::move(act));
  159. PushCleanUpActions(std::move(scopes_to_destroy));
  160. return Success();
  161. }
  162. auto ActionStack::FinishAction(Nonnull<const Value*> result)
  163. -> ErrorOr<Success> {
  164. std::stack<std::unique_ptr<Action>> scopes_to_destroy;
  165. std::unique_ptr<Action> act = todo_.Pop();
  166. switch (FinishActionKindFor(act->kind())) {
  167. case FinishActionKind::NoValue:
  168. CARBON_FATAL() << "This kind of action cannot produce results: " << *act;
  169. case FinishActionKind::NeverCalled:
  170. CARBON_FATAL() << "Should not call FinishAction for: " << *act;
  171. case FinishActionKind::Value:
  172. PopScopes(scopes_to_destroy);
  173. SetResult(result);
  174. break;
  175. }
  176. PushCleanUpAction(std::move(act));
  177. PushCleanUpActions(std::move(scopes_to_destroy));
  178. return Success();
  179. }
  180. auto ActionStack::Spawn(std::unique_ptr<Action> child) -> ErrorOr<Success> {
  181. Action& action = *todo_.Top();
  182. action.set_pos(action.pos() + 1);
  183. todo_.Push(std::move(child));
  184. return Success();
  185. }
  186. auto ActionStack::Spawn(std::unique_ptr<Action> child, RuntimeScope scope)
  187. -> ErrorOr<Success> {
  188. Action& action = *todo_.Top();
  189. action.set_pos(action.pos() + 1);
  190. todo_.Push(std::make_unique<ScopeAction>(std::move(scope)));
  191. todo_.Push(std::move(child));
  192. return Success();
  193. }
  194. auto ActionStack::ReplaceWith(std::unique_ptr<Action> replacement)
  195. -> ErrorOr<Success> {
  196. std::unique_ptr<Action> old = todo_.Pop();
  197. CARBON_CHECK(FinishActionKindFor(old->kind()) ==
  198. FinishActionKindFor(replacement->kind()))
  199. << "Can't replace action " << *old << " with " << *replacement;
  200. todo_.Push(std::move(replacement));
  201. return Success();
  202. }
  203. auto ActionStack::RunAgain() -> ErrorOr<Success> {
  204. Action& action = *todo_.Top();
  205. action.set_pos(action.pos() + 1);
  206. return Success();
  207. }
  208. auto ActionStack::UnwindToWithCaptureScopesToDestroy(
  209. Nonnull<const Statement*> ast_node) -> std::stack<std::unique_ptr<Action>> {
  210. std::stack<std::unique_ptr<Action>> scopes_to_destroy;
  211. while (true) {
  212. if (const auto* statement_action =
  213. llvm::dyn_cast<StatementAction>(todo_.Top().get());
  214. statement_action != nullptr &&
  215. &statement_action->statement() == ast_node) {
  216. break;
  217. }
  218. auto item = todo_.Pop();
  219. auto& scope = item->scope();
  220. if (scope && item->kind() != Action::Kind::CleanUpAction) {
  221. std::unique_ptr<Action> cleanup_action =
  222. std::make_unique<CleanupAction>(std::move(*scope));
  223. scopes_to_destroy.push(std::move(cleanup_action));
  224. }
  225. }
  226. return scopes_to_destroy;
  227. }
  228. auto ActionStack::UnwindTo(Nonnull<const Statement*> ast_node)
  229. -> ErrorOr<Success> {
  230. std::stack<std::unique_ptr<Action>> scopes_to_destroy =
  231. UnwindToWithCaptureScopesToDestroy(ast_node);
  232. PushCleanUpActions(std::move(scopes_to_destroy));
  233. return Success();
  234. }
  235. auto ActionStack::UnwindPast(Nonnull<const Statement*> ast_node)
  236. -> ErrorOr<Success> {
  237. std::stack<std::unique_ptr<Action>> scopes_to_destroy =
  238. UnwindPastWithCaptureScopesToDestroy(ast_node);
  239. PushCleanUpActions(std::move(scopes_to_destroy));
  240. return Success();
  241. }
  242. auto ActionStack::UnwindPastWithCaptureScopesToDestroy(
  243. Nonnull<const Statement*> ast_node) -> std::stack<std::unique_ptr<Action>> {
  244. std::stack<std::unique_ptr<Action>> scopes_to_destroy =
  245. UnwindToWithCaptureScopesToDestroy(ast_node);
  246. auto item = todo_.Pop();
  247. scopes_to_destroy.push(std::move(item));
  248. PopScopes(scopes_to_destroy);
  249. return scopes_to_destroy;
  250. }
  251. auto ActionStack::UnwindPast(Nonnull<const Statement*> ast_node,
  252. Nonnull<const Value*> result) -> ErrorOr<Success> {
  253. std::stack<std::unique_ptr<Action>> scopes_to_destroy =
  254. UnwindPastWithCaptureScopesToDestroy(ast_node);
  255. SetResult(result);
  256. PushCleanUpActions(std::move(scopes_to_destroy));
  257. return Success();
  258. }
  259. auto ActionStack::Resume(Nonnull<const ContinuationValue*> continuation)
  260. -> ErrorOr<Success> {
  261. Action& action = *todo_.Top();
  262. action.set_pos(action.pos() + 1);
  263. continuation->stack().RestoreTo(todo_);
  264. return Success();
  265. }
  266. static auto IsRunAction(const Action& action) -> bool {
  267. const auto* statement = llvm::dyn_cast<StatementAction>(&action);
  268. return statement != nullptr && llvm::isa<Run>(statement->statement());
  269. }
  270. auto ActionStack::Suspend() -> ErrorOr<Success> {
  271. // Pause the current continuation
  272. todo_.Pop();
  273. std::vector<std::unique_ptr<Action>> paused;
  274. while (!IsRunAction(*todo_.Top())) {
  275. paused.push_back(todo_.Pop());
  276. }
  277. const auto& continuation =
  278. llvm::cast<const ContinuationValue>(*todo_.Top()->results()[0]);
  279. // Update the continuation with the paused stack.
  280. continuation.stack().StoreReversed(std::move(paused));
  281. return Success();
  282. }
  283. void ActionStack::PopScopes(
  284. std::stack<std::unique_ptr<Action>>& cleanup_stack) {
  285. while (!todo_.IsEmpty() && llvm::isa<ScopeAction>(*todo_.Top())) {
  286. auto act = todo_.Pop();
  287. if (act->scope()) {
  288. cleanup_stack.push(std::move(act));
  289. }
  290. }
  291. }
  292. void ActionStack::SetResult(Nonnull<const Value*> result) {
  293. if (todo_.IsEmpty()) {
  294. result_ = result;
  295. } else {
  296. todo_.Top()->AddResult(result);
  297. }
  298. }
  299. void ActionStack::PushCleanUpActions(
  300. std::stack<std::unique_ptr<Action>> actions) {
  301. while (!actions.empty()) {
  302. auto& act = actions.top();
  303. if (act->scope()) {
  304. std::unique_ptr<Action> cleanup_action =
  305. std::make_unique<CleanupAction>(std::move(*act->scope()));
  306. todo_.Push(std::move(cleanup_action));
  307. }
  308. actions.pop();
  309. }
  310. }
  311. void ActionStack::PushCleanUpAction(std::unique_ptr<Action> act) {
  312. auto& scope = act->scope();
  313. if (scope && act->kind() != Action::Kind::CleanUpAction) {
  314. std::unique_ptr<Action> cleanup_action =
  315. std::make_unique<CleanupAction>(std::move(*scope));
  316. todo_.Push(std::move(cleanup_action));
  317. }
  318. }
  319. } // namespace Carbon