action.h 11 KB

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