action.h 11 KB

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