action_stack.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. return FinishActionKind::NeverCalled;
  143. }
  144. }
  145. auto ActionStack::FinishAction() -> ErrorOr<Success> {
  146. std::stack<std::unique_ptr<Action>> scopes_to_destroy;
  147. std::unique_ptr<Action> act = todo_.Pop();
  148. switch (FinishActionKindFor(act->kind())) {
  149. case FinishActionKind::Value:
  150. CARBON_FATAL() << "This kind of action must produce a result: " << *act;
  151. case FinishActionKind::NeverCalled:
  152. CARBON_FATAL() << "Should not call FinishAction for: " << *act;
  153. case FinishActionKind::NoValue:
  154. PopScopes(scopes_to_destroy);
  155. break;
  156. }
  157. PushCleanUpAction(std::move(act));
  158. PushCleanUpActions(std::move(scopes_to_destroy));
  159. return Success();
  160. }
  161. auto ActionStack::FinishAction(Nonnull<const Value*> result)
  162. -> ErrorOr<Success> {
  163. std::stack<std::unique_ptr<Action>> scopes_to_destroy;
  164. std::unique_ptr<Action> act = todo_.Pop();
  165. switch (FinishActionKindFor(act->kind())) {
  166. case FinishActionKind::NoValue:
  167. CARBON_FATAL() << "This kind of action cannot produce results: " << *act;
  168. case FinishActionKind::NeverCalled:
  169. CARBON_FATAL() << "Should not call FinishAction for: " << *act;
  170. case FinishActionKind::Value:
  171. PopScopes(scopes_to_destroy);
  172. SetResult(result);
  173. break;
  174. }
  175. PushCleanUpAction(std::move(act));
  176. PushCleanUpActions(std::move(scopes_to_destroy));
  177. return Success();
  178. }
  179. auto ActionStack::Spawn(std::unique_ptr<Action> child) -> ErrorOr<Success> {
  180. Action& action = *todo_.Top();
  181. action.set_pos(action.pos() + 1);
  182. todo_.Push(std::move(child));
  183. return Success();
  184. }
  185. auto ActionStack::Spawn(std::unique_ptr<Action> child, RuntimeScope scope)
  186. -> ErrorOr<Success> {
  187. Action& action = *todo_.Top();
  188. action.set_pos(action.pos() + 1);
  189. todo_.Push(std::make_unique<ScopeAction>(std::move(scope)));
  190. todo_.Push(std::move(child));
  191. return Success();
  192. }
  193. auto ActionStack::ReplaceWith(std::unique_ptr<Action> replacement)
  194. -> ErrorOr<Success> {
  195. std::unique_ptr<Action> old = todo_.Pop();
  196. CARBON_CHECK(FinishActionKindFor(old->kind()) ==
  197. FinishActionKindFor(replacement->kind()))
  198. << "Can't replace action " << *old << " with " << *replacement;
  199. todo_.Push(std::move(replacement));
  200. return Success();
  201. }
  202. auto ActionStack::RunAgain() -> ErrorOr<Success> {
  203. Action& action = *todo_.Top();
  204. action.set_pos(action.pos() + 1);
  205. return Success();
  206. }
  207. auto ActionStack::UnwindToWithCaptureScopesToDestroy(
  208. Nonnull<const Statement*> ast_node) -> std::stack<std::unique_ptr<Action>> {
  209. std::stack<std::unique_ptr<Action>> scopes_to_destroy;
  210. while (true) {
  211. if (const auto* statement_action =
  212. llvm::dyn_cast<StatementAction>(todo_.Top().get());
  213. statement_action != nullptr &&
  214. &statement_action->statement() == ast_node) {
  215. break;
  216. }
  217. auto item = todo_.Pop();
  218. auto& scope = item->scope();
  219. if (scope && item->kind() != Action::Kind::CleanUpAction) {
  220. std::unique_ptr<Action> cleanup_action =
  221. std::make_unique<CleanupAction>(std::move(*scope));
  222. scopes_to_destroy.push(std::move(cleanup_action));
  223. }
  224. }
  225. return scopes_to_destroy;
  226. }
  227. auto ActionStack::UnwindTo(Nonnull<const Statement*> ast_node)
  228. -> ErrorOr<Success> {
  229. std::stack<std::unique_ptr<Action>> scopes_to_destroy =
  230. UnwindToWithCaptureScopesToDestroy(ast_node);
  231. PushCleanUpActions(std::move(scopes_to_destroy));
  232. return Success();
  233. }
  234. auto ActionStack::UnwindPast(Nonnull<const Statement*> ast_node)
  235. -> ErrorOr<Success> {
  236. std::stack<std::unique_ptr<Action>> scopes_to_destroy =
  237. UnwindPastWithCaptureScopesToDestroy(ast_node);
  238. PushCleanUpActions(std::move(scopes_to_destroy));
  239. return Success();
  240. }
  241. auto ActionStack::UnwindPastWithCaptureScopesToDestroy(
  242. Nonnull<const Statement*> ast_node) -> std::stack<std::unique_ptr<Action>> {
  243. std::stack<std::unique_ptr<Action>> scopes_to_destroy =
  244. UnwindToWithCaptureScopesToDestroy(ast_node);
  245. auto item = todo_.Pop();
  246. scopes_to_destroy.push(std::move(item));
  247. PopScopes(scopes_to_destroy);
  248. return scopes_to_destroy;
  249. }
  250. auto ActionStack::UnwindPast(Nonnull<const Statement*> ast_node,
  251. Nonnull<const Value*> result) -> ErrorOr<Success> {
  252. std::stack<std::unique_ptr<Action>> scopes_to_destroy =
  253. UnwindPastWithCaptureScopesToDestroy(ast_node);
  254. SetResult(result);
  255. PushCleanUpActions(std::move(scopes_to_destroy));
  256. return Success();
  257. }
  258. auto ActionStack::Resume(Nonnull<const ContinuationValue*> continuation)
  259. -> ErrorOr<Success> {
  260. Action& action = *todo_.Top();
  261. action.set_pos(action.pos() + 1);
  262. continuation->stack().RestoreTo(todo_);
  263. return Success();
  264. }
  265. static auto IsRunAction(const Action& action) -> bool {
  266. const auto* statement = llvm::dyn_cast<StatementAction>(&action);
  267. return statement != nullptr && llvm::isa<Run>(statement->statement());
  268. }
  269. auto ActionStack::Suspend() -> ErrorOr<Success> {
  270. // Pause the current continuation
  271. todo_.Pop();
  272. std::vector<std::unique_ptr<Action>> paused;
  273. while (!IsRunAction(*todo_.Top())) {
  274. paused.push_back(todo_.Pop());
  275. }
  276. const auto& continuation =
  277. llvm::cast<const ContinuationValue>(*todo_.Top()->results()[0]);
  278. // Update the continuation with the paused stack.
  279. continuation.stack().StoreReversed(std::move(paused));
  280. return Success();
  281. }
  282. void ActionStack::PopScopes(
  283. std::stack<std::unique_ptr<Action>>& cleanup_stack) {
  284. while (!todo_.IsEmpty() && llvm::isa<ScopeAction>(*todo_.Top())) {
  285. auto act = todo_.Pop();
  286. if (act->scope()) {
  287. if ((*act->scope()).DestructionState() <
  288. RuntimeScope::State::CleanUpped) {
  289. (*act->scope()).TransitState();
  290. cleanup_stack.push(std::move(act));
  291. }
  292. }
  293. }
  294. }
  295. void ActionStack::SetResult(Nonnull<const Value*> result) {
  296. if (todo_.IsEmpty()) {
  297. result_ = result;
  298. } else {
  299. todo_.Top()->AddResult(result);
  300. }
  301. }
  302. void ActionStack::PushCleanUpActions(
  303. std::stack<std::unique_ptr<Action>> actions) {
  304. while (!actions.empty()) {
  305. auto& act = actions.top();
  306. if (act->scope()) {
  307. std::unique_ptr<Action> cleanup_action =
  308. std::make_unique<CleanupAction>(std::move(*act->scope()));
  309. todo_.Push(std::move(cleanup_action));
  310. }
  311. actions.pop();
  312. }
  313. }
  314. void ActionStack::PushCleanUpAction(std::unique_ptr<Action> act) {
  315. auto& scope = act->scope();
  316. if (scope && act->kind() != Action::Kind::CleanUpAction) {
  317. std::unique_ptr<Action> cleanup_action =
  318. std::make_unique<CleanupAction>(std::move(*scope));
  319. todo_.Push(std::move(cleanup_action));
  320. }
  321. }
  322. } // namespace Carbon