action_stack.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. #ifndef CARBON_EXPLORER_INTERPRETER_ACTION_STACK_H_
  5. #define CARBON_EXPLORER_INTERPRETER_ACTION_STACK_H_
  6. #include <memory>
  7. #include <optional>
  8. #include <stack>
  9. #include "common/ostream.h"
  10. #include "explorer/ast/statement.h"
  11. #include "explorer/ast/value.h"
  12. #include "explorer/base/trace_stream.h"
  13. #include "explorer/interpreter/action.h"
  14. namespace Carbon {
  15. // Selects between compile-time and run-time behavior.
  16. enum class Phase { CompileTime, RunTime };
  17. // The stack of Actions currently being executed by the interpreter.
  18. class ActionStack {
  19. public:
  20. // Constructs an empty compile-time ActionStack.
  21. explicit ActionStack(Nonnull<TraceStream*> trace_stream)
  22. : phase_(Phase::CompileTime), trace_stream_(trace_stream) {}
  23. // Constructs an empty run-time ActionStack that allocates global variables
  24. // on `heap`.
  25. explicit ActionStack(Nonnull<TraceStream*> trace_stream,
  26. Nonnull<HeapAllocationInterface*> heap)
  27. : globals_(RuntimeScope(heap)),
  28. phase_(Phase::RunTime),
  29. trace_stream_(trace_stream) {}
  30. void Print(llvm::raw_ostream& out) const;
  31. LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
  32. // Starts execution with `action` at the top of the stack. Cannot be called
  33. // when IsEmpty() is false.
  34. void Start(std::unique_ptr<Action> action);
  35. // True if the stack is empty.
  36. auto empty() const -> bool { return todo_.empty(); }
  37. // The Action currently at the top of the stack. This will never be a
  38. // ScopeAction.
  39. auto CurrentAction() -> Action& { return *todo_.Top(); }
  40. // Allocates storage for `value_node`, and initializes it to `value`.
  41. void Initialize(ValueNodeView value_node, Nonnull<const Value*> value);
  42. // Returns the value bound to `value_node`. If `value_node` is a local
  43. // variable, this will be an LocationValue.
  44. auto ValueOfNode(ValueNodeView value_node, SourceLocation source_loc) const
  45. -> ErrorOr<Nonnull<const Value*>>;
  46. // Merges `scope` into the innermost scope currently on the stack.
  47. void MergeScope(RuntimeScope scope);
  48. // The result produced by the `action` argument of the most recent
  49. // Start call. Cannot be called if IsEmpty() is false, or if `action`
  50. // was an action that doesn't produce results.
  51. auto result() const -> Nonnull<const Value*> { return *result_; }
  52. // The following methods, called "transition methods", update the state of
  53. // the ActionStack and/or the current Action to reflect the effects of
  54. // executing a step of that Action. Execution of an Action step should always
  55. // invoke exactly one transition method, as the very last operation. This is a
  56. // matter of safety as well as convention: most transition methods modify the
  57. // state of the current action, and some of them destroy it. To help enforce
  58. // this requirement, we have a convention of making these methods return an
  59. // ErrorOr<Success> even when a method can't actually fail, and calling the
  60. // methods as part of return statements, e.g. `return todo_.FinishAction()`.
  61. // Finishes execution of the current Action. If `result` is specified, it
  62. // represents the result of that Action.
  63. auto FinishAction() -> ErrorOr<Success>;
  64. auto FinishAction(Nonnull<const Value*> result) -> ErrorOr<Success>;
  65. // Advances the current action one step, and push `child` onto the stack.
  66. // If `scope` is specified, `child` will be executed in that scope.
  67. auto Spawn(std::unique_ptr<Action> child) -> ErrorOr<Success>;
  68. auto Spawn(std::unique_ptr<Action> child, RuntimeScope scope)
  69. -> ErrorOr<Success>;
  70. // Replace the current action with another action that produces the same kind
  71. // of result and run it next.
  72. auto ReplaceWith(std::unique_ptr<Action> replacement) -> ErrorOr<Success>;
  73. // Start a new recursive action.
  74. auto BeginRecursiveAction() {
  75. todo_.Push(std::make_unique<RecursiveAction>());
  76. }
  77. // Advances the current action one step.
  78. auto RunAgain() -> ErrorOr<Success>;
  79. // Unwinds Actions from the stack until the StatementAction associated with
  80. // `ast_node` is at the top of the stack.
  81. auto UnwindTo(Nonnull<const Statement*> ast_node) -> ErrorOr<Success>;
  82. // Unwinds Actions from the stack until the StatementAction associated with
  83. // `ast_node` has been removed from the stack. If `result` is specified,
  84. // it represents the result of that Action (StatementActions normally cannot
  85. // produce results, but the body of a function can).
  86. auto UnwindPast(Nonnull<const Statement*> ast_node) -> ErrorOr<Success>;
  87. auto UnwindPast(Nonnull<const Statement*> ast_node,
  88. Nonnull<const Value*> result) -> ErrorOr<Success>;
  89. auto Pop() -> std::unique_ptr<Action> {
  90. auto popped_action = todo_.Pop();
  91. if (trace_stream_->is_enabled()) {
  92. trace_stream_->Pop() << "stack-pop: " << *popped_action << " ("
  93. << popped_action->source_loc() << ")\n";
  94. }
  95. return popped_action;
  96. }
  97. void Push(std::unique_ptr<Action> action) {
  98. if (trace_stream_->is_enabled()) {
  99. trace_stream_->Push()
  100. << "stack-push: " << *action << " (" << action->source_loc() << ")\n";
  101. }
  102. todo_.Push(std::move(action));
  103. }
  104. auto size() const -> int { return todo_.size(); }
  105. private:
  106. // Pop any ScopeActions from the top of the stack, propagating results as
  107. // needed, to restore the invariant that todo_.Top() is not a ScopeAction.
  108. // Store the popped scope action into cleanup_stack, so that the destructor
  109. // can be called for the variables
  110. void PopScopes(std::stack<std::unique_ptr<Action>>& cleanup_stack);
  111. // Set `result` as the result of the Action most recently removed from the
  112. // stack.
  113. void SetResult(Nonnull<const Value*> result);
  114. auto UnwindToWithCaptureScopesToDestroy(Nonnull<const Statement*> ast_node)
  115. -> std::stack<std::unique_ptr<Action>>;
  116. auto UnwindPastWithCaptureScopesToDestroy(Nonnull<const Statement*> ast_node)
  117. -> std::stack<std::unique_ptr<Action>>;
  118. // Create CleanUpActions for all actions
  119. void PushCleanUpActions(std::stack<std::unique_ptr<Action>> actions);
  120. // Create and push a CleanUpAction on the stack
  121. void PushCleanUpAction(std::unique_ptr<Action> act);
  122. // TODO: consider defining a non-nullable unique_ptr-like type to use here.
  123. Stack<std::unique_ptr<Action>> todo_;
  124. std::optional<Nonnull<const Value*>> result_;
  125. std::optional<RuntimeScope> globals_;
  126. Phase phase_;
  127. Nonnull<TraceStream*> trace_stream_;
  128. };
  129. } // namespace Carbon
  130. #endif // CARBON_EXPLORER_INTERPRETER_ACTION_STACK_H_