action.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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_H_
  5. #define CARBON_EXPLORER_INTERPRETER_ACTION_H_
  6. #include <map>
  7. #include <vector>
  8. #include "common/ostream.h"
  9. #include "explorer/ast/expression.h"
  10. #include "explorer/ast/pattern.h"
  11. #include "explorer/ast/statement.h"
  12. #include "explorer/interpreter/dictionary.h"
  13. #include "explorer/interpreter/heap_allocation_interface.h"
  14. #include "explorer/interpreter/stack.h"
  15. #include "explorer/interpreter/value.h"
  16. #include "llvm/Support/Compiler.h"
  17. namespace Carbon {
  18. // A RuntimeScope manages and provides access to the storage for names that are
  19. // not compile-time constants.
  20. class RuntimeScope {
  21. public:
  22. // Returns a RuntimeScope whose Get() operation for a given name returns the
  23. // storage owned by the first entry in `scopes` that defines that name. This
  24. // behavior is closely analogous to a `[&]` capture in C++, hence the name.
  25. // `scopes` must contain at least one entry, and all entries must be backed
  26. // by the same Heap.
  27. static auto Capture(const std::vector<Nonnull<const RuntimeScope*>>& scopes)
  28. -> RuntimeScope;
  29. // Constructs a RuntimeScope that allocates storage in `heap`.
  30. explicit RuntimeScope(Nonnull<HeapAllocationInterface*> heap) : heap_(heap) {}
  31. // Moving a RuntimeScope transfers ownership of its allocations.
  32. RuntimeScope(RuntimeScope&&) noexcept;
  33. auto operator=(RuntimeScope&&) noexcept -> RuntimeScope&;
  34. // Deallocates any allocations in this scope from `heap`.
  35. ~RuntimeScope();
  36. void Print(llvm::raw_ostream& out) const;
  37. LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
  38. // Allocates storage for `value_node` in `heap`, and initializes it with
  39. // `value`.
  40. void Initialize(ValueNodeView value_node, Nonnull<const Value*> value);
  41. // Transfers the names and allocations from `other` into *this. The two
  42. // scopes must not define the same name, and must be backed by the same Heap.
  43. void Merge(RuntimeScope other);
  44. // Returns the local storage for value_node, if it has storage local to
  45. // this scope.
  46. auto Get(ValueNodeView value_node) const
  47. -> std::optional<Nonnull<const LValue*>>;
  48. private:
  49. std::map<ValueNodeView, Nonnull<const LValue*>> locals_;
  50. std::vector<AllocationId> allocations_;
  51. Nonnull<HeapAllocationInterface*> heap_;
  52. };
  53. // An Action represents the current state of a self-contained computation,
  54. // usually associated with some AST node, such as evaluation of an expression or
  55. // execution of a statement. Execution of an action is divided into a series of
  56. // steps, and the `pos` field typically counts the number of steps executed.
  57. //
  58. // They should be destroyed as soon as they are done executing, in order to
  59. // clean up the associated Carbon scope, and consequently they should not be
  60. // allocated on an Arena. Actions are typically owned by the ActionStack.
  61. //
  62. // The actual behavior of an Action step is defined by Interpreter::Step, not by
  63. // Action or its subclasses.
  64. // TODO: consider moving this logic to a virtual method `Step`.
  65. class Action {
  66. public:
  67. enum class Kind {
  68. LValAction,
  69. ExpressionAction,
  70. PatternAction,
  71. StatementAction,
  72. DeclarationAction,
  73. ScopeAction,
  74. RecursiveAction,
  75. };
  76. Action(const Value&) = delete;
  77. auto operator=(const Value&) -> Action& = delete;
  78. virtual ~Action() = default;
  79. void Print(llvm::raw_ostream& out) const;
  80. LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
  81. // Resets this Action to its initial state.
  82. void Clear() {
  83. CARBON_CHECK(!scope_.has_value());
  84. pos_ = 0;
  85. results_.clear();
  86. }
  87. // Returns the enumerator corresponding to the most-derived type of this
  88. // object.
  89. auto kind() const -> Kind { return kind_; }
  90. // The position or state of the action. Starts at 0 and is typically
  91. // incremented after each step.
  92. auto pos() const -> int { return pos_; }
  93. void set_pos(int pos) { this->pos_ = pos; }
  94. // The results of any Actions spawned by this Action.
  95. auto results() const -> const std::vector<Nonnull<const Value*>>& {
  96. return results_;
  97. }
  98. // Appends `result` to `results`.
  99. void AddResult(Nonnull<const Value*> result) { results_.push_back(result); }
  100. // Returns the scope associated with this Action, if any.
  101. auto scope() -> std::optional<RuntimeScope>& { return scope_; }
  102. auto scope() const -> const std::optional<RuntimeScope>& { return scope_; }
  103. // Associates this action with a new scope, with initial state `scope`.
  104. // Values that are local to this scope will be deallocated when this
  105. // Action is completed or unwound. Can only be called once on a given
  106. // Action.
  107. void StartScope(RuntimeScope scope) {
  108. CARBON_CHECK(!scope_.has_value());
  109. scope_ = std::move(scope);
  110. }
  111. protected:
  112. // Constructs an Action. `kind` must be the enumerator corresponding to the
  113. // most-derived type being constructed.
  114. explicit Action(Kind kind) : kind_(kind) {}
  115. private:
  116. int pos_ = 0;
  117. std::vector<Nonnull<const Value*>> results_;
  118. std::optional<RuntimeScope> scope_;
  119. const Kind kind_;
  120. };
  121. // An Action which implements evaluation of an Expression to produce an
  122. // LValue.
  123. class LValAction : public Action {
  124. public:
  125. explicit LValAction(Nonnull<const Expression*> expression)
  126. : Action(Kind::LValAction), expression_(expression) {}
  127. static auto classof(const Action* action) -> bool {
  128. return action->kind() == Kind::LValAction;
  129. }
  130. // The Expression this Action evaluates.
  131. auto expression() const -> const Expression& { return *expression_; }
  132. private:
  133. Nonnull<const Expression*> expression_;
  134. };
  135. // An Action which implements evaluation of an Expression to produce an
  136. // rvalue. The result is expressed as a Value.
  137. class ExpressionAction : public Action {
  138. public:
  139. explicit ExpressionAction(Nonnull<const Expression*> expression)
  140. : Action(Kind::ExpressionAction), expression_(expression) {}
  141. static auto classof(const Action* action) -> bool {
  142. return action->kind() == Kind::ExpressionAction;
  143. }
  144. // The Expression this Action evaluates.
  145. auto expression() const -> const Expression& { return *expression_; }
  146. private:
  147. Nonnull<const Expression*> expression_;
  148. };
  149. // An Action which implements evaluation of a Pattern. The result is expressed
  150. // as a Value.
  151. class PatternAction : public Action {
  152. public:
  153. explicit PatternAction(Nonnull<const Pattern*> pattern)
  154. : Action(Kind::PatternAction), pattern_(pattern) {}
  155. static auto classof(const Action* action) -> bool {
  156. return action->kind() == Kind::PatternAction;
  157. }
  158. // The Pattern this Action evaluates.
  159. auto pattern() const -> const Pattern& { return *pattern_; }
  160. private:
  161. Nonnull<const Pattern*> pattern_;
  162. };
  163. // An Action which implements execution of a Statement. Does not produce a
  164. // result.
  165. class StatementAction : public Action {
  166. public:
  167. explicit StatementAction(Nonnull<const Statement*> statement)
  168. : Action(Kind::StatementAction), statement_(statement) {}
  169. static auto classof(const Action* action) -> bool {
  170. return action->kind() == Kind::StatementAction;
  171. }
  172. // The Statement this Action executes.
  173. auto statement() const -> const Statement& { return *statement_; }
  174. private:
  175. Nonnull<const Statement*> statement_;
  176. };
  177. // Action which implements the run-time effects of executing a Declaration.
  178. // Does not produce a result.
  179. class DeclarationAction : public Action {
  180. public:
  181. explicit DeclarationAction(Nonnull<const Declaration*> declaration)
  182. : Action(Kind::DeclarationAction), declaration_(declaration) {}
  183. static auto classof(const Action* action) -> bool {
  184. return action->kind() == Kind::DeclarationAction;
  185. }
  186. // The Declaration this Action executes.
  187. auto declaration() const -> const Declaration& { return *declaration_; }
  188. private:
  189. Nonnull<const Declaration*> declaration_;
  190. };
  191. // Action which does nothing except introduce a new scope into the action
  192. // stack. This is useful when a distinct scope doesn't otherwise have an
  193. // Action it can naturally be associated with. ScopeActions are not associated
  194. // with AST nodes.
  195. class ScopeAction : public Action {
  196. public:
  197. explicit ScopeAction(RuntimeScope scope) : Action(Kind::ScopeAction) {
  198. StartScope(std::move(scope));
  199. }
  200. static auto classof(const Action* action) -> bool {
  201. return action->kind() == Kind::ScopeAction;
  202. }
  203. };
  204. // Action which contains another action and does nothing further once that
  205. // action completes. This action therefore acts as a marker on the action stack
  206. // that indicates that the interpreter should stop when the inner action has
  207. // finished, and holds the result of that inner action. This is useful to allow
  208. // a sequence of steps for an action to be run immediately rather than as part
  209. // of the normal step queue.
  210. //
  211. // Should be avoided where possible.
  212. class RecursiveAction : public Action {
  213. public:
  214. explicit RecursiveAction() : Action(Kind::RecursiveAction) {}
  215. static auto classof(const Action* action) -> bool {
  216. return action->kind() == Kind::RecursiveAction;
  217. }
  218. };
  219. } // namespace Carbon
  220. #endif // CARBON_EXPLORER_INTERPRETER_ACTION_H_