action.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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/ast/value.h"
  15. #include "explorer/interpreter/dictionary.h"
  16. #include "explorer/interpreter/heap_allocation_interface.h"
  17. #include "explorer/interpreter/stack.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 LocationValue*>>;
  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 LocationValue*>,
  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. LocationAction,
  79. ExpressionAction,
  80. WitnessAction,
  81. StatementAction,
  82. DeclarationAction,
  83. ScopeAction,
  84. RecursiveAction,
  85. CleanUpAction,
  86. DestroyAction,
  87. TypeInstantiationAction
  88. };
  89. Action(const Value&) = delete;
  90. auto operator=(const Value&) -> Action& = delete;
  91. virtual ~Action() = default;
  92. void Print(llvm::raw_ostream& out) const;
  93. LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
  94. // Resets this Action to its initial state.
  95. void Clear() {
  96. CARBON_CHECK(!scope_.has_value());
  97. pos_ = 0;
  98. results_.clear();
  99. }
  100. // Returns the enumerator corresponding to the most-derived type of this
  101. // object.
  102. auto kind() const -> Kind { return kind_; }
  103. // The position or state of the action. Starts at 0 and is typically
  104. // incremented after each step.
  105. auto pos() const -> int { return pos_; }
  106. void set_pos(int pos) { this->pos_ = pos; }
  107. // The results of any Actions spawned by this Action.
  108. auto results() const -> const std::vector<Nonnull<const Value*>>& {
  109. return results_;
  110. }
  111. void ReplaceResult(std::size_t index, Nonnull<const Value*> value) {
  112. CARBON_CHECK(index < results_.size());
  113. results_[index] = value;
  114. }
  115. // Appends `result` to `results`.
  116. void AddResult(Nonnull<const Value*> result) { results_.push_back(result); }
  117. // Returns the scope associated with this Action, if any.
  118. auto scope() -> std::optional<RuntimeScope>& { return scope_; }
  119. auto scope() const -> const std::optional<RuntimeScope>& { return scope_; }
  120. // Associates this action with a new scope, with initial state `scope`.
  121. // Values that are local to this scope will be deallocated when this
  122. // Action is completed or unwound. Can only be called once on a given
  123. // Action.
  124. void StartScope(RuntimeScope scope) {
  125. CARBON_CHECK(!scope_.has_value());
  126. scope_ = std::move(scope);
  127. }
  128. protected:
  129. // Constructs an Action. `kind` must be the enumerator corresponding to the
  130. // most-derived type being constructed.
  131. explicit Action(Kind kind) : kind_(kind) {}
  132. private:
  133. int pos_ = 0;
  134. std::vector<Nonnull<const Value*>> results_;
  135. std::optional<RuntimeScope> scope_;
  136. const Kind kind_;
  137. };
  138. // An Action which implements evaluation of an Expression to produce an
  139. // LocationValue.
  140. class LocationAction : public Action {
  141. public:
  142. explicit LocationAction(Nonnull<const Expression*> expression)
  143. : Action(Kind::LocationAction), expression_(expression) {}
  144. static auto classof(const Action* action) -> bool {
  145. return action->kind() == Kind::LocationAction;
  146. }
  147. // The Expression this Action evaluates.
  148. auto expression() const -> const Expression& { return *expression_; }
  149. private:
  150. Nonnull<const Expression*> expression_;
  151. };
  152. // An Action which implements evaluation of an Expression to produce 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 the Instantiation of Type. The result is expressed
  166. // as a Value.
  167. class TypeInstantiationAction : public Action {
  168. public:
  169. explicit TypeInstantiationAction(Nonnull<const Value*> type,
  170. SourceLocation source_loc)
  171. : Action(Kind::TypeInstantiationAction),
  172. type_(type),
  173. source_loc_(source_loc) {}
  174. static auto classof(const Action* action) -> bool {
  175. return action->kind() == Kind::TypeInstantiationAction;
  176. }
  177. auto type() const -> Nonnull<const Value*> { return type_; }
  178. auto source_loc() const -> SourceLocation { return source_loc_; }
  179. private:
  180. Nonnull<const Value*> type_;
  181. SourceLocation source_loc_;
  182. };
  183. // An Action which implements evaluation of a Witness to resolve it in the
  184. // local context.
  185. class WitnessAction : public Action {
  186. public:
  187. explicit WitnessAction(Nonnull<const Witness*> witness)
  188. : Action(Kind::WitnessAction), witness_(witness) {}
  189. static auto classof(const Action* action) -> bool {
  190. return action->kind() == Kind::WitnessAction;
  191. }
  192. // The Witness this Action resolves.
  193. auto witness() const -> Nonnull<const Witness*> { return witness_; }
  194. private:
  195. Nonnull<const Witness*> witness_;
  196. };
  197. // An Action which implements execution of a Statement. Does not produce a
  198. // result.
  199. class StatementAction : public Action {
  200. public:
  201. explicit StatementAction(Nonnull<const Statement*> statement)
  202. : Action(Kind::StatementAction), statement_(statement) {}
  203. static auto classof(const Action* action) -> bool {
  204. return action->kind() == Kind::StatementAction;
  205. }
  206. // The Statement this Action executes.
  207. auto statement() const -> const Statement& { return *statement_; }
  208. private:
  209. Nonnull<const Statement*> statement_;
  210. };
  211. // Action which implements the run-time effects of executing a Declaration.
  212. // Does not produce a result.
  213. class DeclarationAction : public Action {
  214. public:
  215. explicit DeclarationAction(Nonnull<const Declaration*> declaration)
  216. : Action(Kind::DeclarationAction), declaration_(declaration) {}
  217. static auto classof(const Action* action) -> bool {
  218. return action->kind() == Kind::DeclarationAction;
  219. }
  220. // The Declaration this Action executes.
  221. auto declaration() const -> const Declaration& { return *declaration_; }
  222. private:
  223. Nonnull<const Declaration*> declaration_;
  224. };
  225. // An Action which implements destroying all local allocations in a scope.
  226. class CleanUpAction : public Action {
  227. public:
  228. explicit CleanUpAction(RuntimeScope scope)
  229. : Action(Kind::CleanUpAction),
  230. allocations_count_(scope.allocations().size()) {
  231. StartScope(std::move(scope));
  232. }
  233. auto allocations_count() const -> int { return allocations_count_; }
  234. static auto classof(const Action* action) -> bool {
  235. return action->kind() == Kind::CleanUpAction;
  236. }
  237. private:
  238. int allocations_count_;
  239. };
  240. // An Action which implements destroying a single value, including all nested
  241. // values.
  242. class DestroyAction : public Action {
  243. public:
  244. // location: Location of the object to be destroyed
  245. // value: The value to be destroyed
  246. // In most cases the location address points to value
  247. // In the case that the member of a class is to be destroyed,
  248. // the location points to the address of the class object
  249. // and the value is the member of the class
  250. explicit DestroyAction(Nonnull<const LocationValue*> location,
  251. Nonnull<const Value*> value)
  252. : Action(Kind::DestroyAction), location_(location), value_(value) {}
  253. static auto classof(const Action* action) -> bool {
  254. return action->kind() == Kind::DestroyAction;
  255. }
  256. auto location() const -> Nonnull<const LocationValue*> { return location_; }
  257. auto value() const -> Nonnull<const Value*> { return value_; }
  258. private:
  259. Nonnull<const LocationValue*> location_;
  260. Nonnull<const Value*> value_;
  261. };
  262. // Action which does nothing except introduce a new scope into the action
  263. // stack. This is useful when a distinct scope doesn't otherwise have an
  264. // Action it can naturally be associated with. ScopeActions are not associated
  265. // with AST nodes.
  266. class ScopeAction : public Action {
  267. public:
  268. explicit ScopeAction(RuntimeScope scope) : Action(Kind::ScopeAction) {
  269. StartScope(std::move(scope));
  270. }
  271. static auto classof(const Action* action) -> bool {
  272. return action->kind() == Kind::ScopeAction;
  273. }
  274. };
  275. // Action which contains another action and does nothing further once that
  276. // action completes. This action therefore acts as a marker on the action stack
  277. // that indicates that the interpreter should stop when the inner action has
  278. // finished, and holds the result of that inner action. This is useful to allow
  279. // a sequence of steps for an action to be run immediately rather than as part
  280. // of the normal step queue.
  281. //
  282. // Should be avoided where possible.
  283. class RecursiveAction : public Action {
  284. public:
  285. explicit RecursiveAction() : Action(Kind::RecursiveAction) {}
  286. static auto classof(const Action* action) -> bool {
  287. return action->kind() == Kind::RecursiveAction;
  288. }
  289. };
  290. } // namespace Carbon
  291. #endif // CARBON_EXPLORER_INTERPRETER_ACTION_H_