action.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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 <optional>
  9. #include <tuple>
  10. #include <vector>
  11. #include "common/check.h"
  12. #include "common/ostream.h"
  13. #include "explorer/ast/address.h"
  14. #include "explorer/ast/expression.h"
  15. #include "explorer/ast/pattern.h"
  16. #include "explorer/ast/statement.h"
  17. #include "explorer/ast/value.h"
  18. #include "explorer/base/source_location.h"
  19. #include "explorer/interpreter/dictionary.h"
  20. #include "explorer/interpreter/heap_allocation_interface.h"
  21. #include "explorer/interpreter/stack.h"
  22. #include "llvm/ADT/DenseSet.h"
  23. #include "llvm/ADT/MapVector.h"
  24. #include "llvm/Support/Compiler.h"
  25. namespace Carbon {
  26. // A RuntimeScope manages and provides access to the storage for names that are
  27. // not compile-time constants.
  28. class RuntimeScope : public Printable<RuntimeScope> {
  29. public:
  30. // Returns a RuntimeScope whose Get() operation for a given name returns the
  31. // storage owned by the first entry in `scopes` that defines that name. This
  32. // behavior is closely analogous to a `[&]` capture in C++, hence the name.
  33. // `scopes` must contain at least one entry, and all entries must be backed
  34. // by the same Heap.
  35. static auto Capture(const std::vector<Nonnull<const RuntimeScope*>>& scopes)
  36. -> RuntimeScope;
  37. // Constructs a RuntimeScope that allocates storage in `heap`.
  38. explicit RuntimeScope(Nonnull<HeapAllocationInterface*> heap) : heap_(heap) {}
  39. // Moving a RuntimeScope transfers ownership of its allocations.
  40. RuntimeScope(RuntimeScope&&) noexcept;
  41. auto operator=(RuntimeScope&&) noexcept -> RuntimeScope&;
  42. void Print(llvm::raw_ostream& out) const;
  43. // Allocates storage for `value_node` in `heap`, and initializes it with
  44. // `value`.
  45. auto Initialize(ValueNodeView value_node, Nonnull<const Value*> value)
  46. -> Nonnull<const LocationValue*>;
  47. // Bind allocation lifetime to scope. Should only be called with unowned
  48. // allocations to avoid a double free.
  49. void BindLifetimeToScope(Address address);
  50. // Binds location `address` of a reference value to `value_node` without
  51. // allocating local storage.
  52. void Bind(ValueNodeView value_node, Address address);
  53. // Binds location `address` of a reference value to `value_node` without
  54. // allocating local storage, and pins the value, making it immutable.
  55. void BindAndPin(ValueNodeView value_node, Address address);
  56. // Binds unlocated `value` to `value_node` without allocating local storage.
  57. // TODO: BindValue should pin the lifetime of `value` and make sure it isn't
  58. // mutated.
  59. void BindValue(ValueNodeView value_node, Nonnull<const Value*> value);
  60. // Transfers the names and allocations from `other` into *this. The two
  61. // scopes must not define the same name, and must be backed by the same Heap.
  62. void Merge(RuntimeScope other);
  63. // Given node `value_node`, returns:
  64. // - its `LocationValue*` if bound to a reference expression in this scope,
  65. // - a `Value*` if bound to a value expression in this scope, or
  66. // - `nullptr` if not bound.
  67. auto Get(ValueNodeView value_node, SourceLocation source_loc) const
  68. -> ErrorOr<std::optional<Nonnull<const Value*>>>;
  69. // Returns the local values with allocation in created order.
  70. auto allocations() const -> const std::vector<AllocationId>& {
  71. return allocations_;
  72. }
  73. private:
  74. llvm::MapVector<ValueNodeView, Nonnull<const Value*>,
  75. std::map<ValueNodeView, unsigned>>
  76. locals_;
  77. llvm::DenseSet<const AstNode*> bound_values_;
  78. std::vector<AllocationId> allocations_;
  79. Nonnull<HeapAllocationInterface*> heap_;
  80. };
  81. // An Action represents the current state of a self-contained computation,
  82. // usually associated with some AST node, such as evaluation of an expression or
  83. // execution of a statement. Execution of an action is divided into a series of
  84. // steps, and the `pos` field typically counts the number of steps executed.
  85. //
  86. // They should be destroyed as soon as they are done executing, in order to
  87. // clean up the associated Carbon scope, and consequently they should not be
  88. // allocated on an Arena. Actions are typically owned by the ActionStack.
  89. //
  90. // The actual behavior of an Action step is defined by Interpreter::Step, not by
  91. // Action or its subclasses.
  92. // TODO: consider moving this logic to a virtual method `Step`.
  93. class Action : public Printable<Action> {
  94. public:
  95. enum class Kind {
  96. LocationAction,
  97. ValueExpressionAction,
  98. ExpressionAction,
  99. WitnessAction,
  100. StatementAction,
  101. DeclarationAction,
  102. ScopeAction,
  103. RecursiveAction,
  104. CleanUpAction,
  105. DestroyAction,
  106. TypeInstantiationAction
  107. };
  108. Action(const Value&) = delete;
  109. auto operator=(const Value&) -> Action& = delete;
  110. virtual ~Action() = default;
  111. void Print(llvm::raw_ostream& out) const;
  112. // Resets this Action to its initial state.
  113. void Clear() {
  114. CARBON_CHECK(!scope_.has_value());
  115. pos_ = 0;
  116. results_.clear();
  117. }
  118. // Returns the enumerator corresponding to the most-derived type of this
  119. // object.
  120. auto kind() const -> Kind { return kind_; }
  121. auto kind_string() const -> std::string_view;
  122. // The position or state of the action. Starts at 0 and is typically
  123. // incremented after each step.
  124. auto pos() const -> int { return pos_; }
  125. void set_pos(int pos) { this->pos_ = pos; }
  126. // The results of any Actions spawned by this Action.
  127. auto results() const -> const std::vector<Nonnull<const Value*>>& {
  128. return results_;
  129. }
  130. void ReplaceResult(std::size_t index, Nonnull<const Value*> value) {
  131. CARBON_CHECK(index < results_.size());
  132. results_[index] = value;
  133. }
  134. // Appends `result` to `results`.
  135. void AddResult(Nonnull<const Value*> result) { results_.push_back(result); }
  136. // Returns the scope associated with this Action, if any.
  137. auto scope() -> std::optional<RuntimeScope>& { return scope_; }
  138. auto scope() const -> const std::optional<RuntimeScope>& { return scope_; }
  139. // Associates this action with a new scope, with initial state `scope`.
  140. // Values that are local to this scope will be deallocated when this
  141. // Action is completed or unwound. Can only be called once on a given
  142. // Action.
  143. void StartScope(RuntimeScope scope) {
  144. CARBON_CHECK(!scope_.has_value());
  145. scope_ = std::move(scope);
  146. }
  147. auto source_loc() const -> std::optional<SourceLocation> {
  148. return source_loc_;
  149. }
  150. protected:
  151. // Constructs an Action. `kind` must be the enumerator corresponding to the
  152. // most-derived type being constructed.
  153. explicit Action(std::optional<SourceLocation> source_loc, Kind kind)
  154. : source_loc_(source_loc), kind_(kind) {}
  155. std::optional<SourceLocation> source_loc_;
  156. private:
  157. int pos_ = 0;
  158. std::vector<Nonnull<const Value*>> results_;
  159. std::optional<RuntimeScope> scope_;
  160. const Kind kind_;
  161. };
  162. // An Action which implements evaluation of an Expression to produce an
  163. // LocationValue.
  164. class LocationAction : public Action {
  165. public:
  166. explicit LocationAction(Nonnull<const Expression*> expression)
  167. : Action(expression->source_loc(), Kind::LocationAction),
  168. expression_(expression) {}
  169. static auto classof(const Action* action) -> bool {
  170. return action->kind() == Kind::LocationAction;
  171. }
  172. // The Expression this Action evaluates.
  173. auto expression() const -> const Expression& { return *expression_; }
  174. private:
  175. Nonnull<const Expression*> expression_;
  176. };
  177. // An Action which implements evaluation of an Expression to produce a `Value*`.
  178. class ValueExpressionAction : public Action {
  179. public:
  180. explicit ValueExpressionAction(
  181. Nonnull<const Expression*> expression,
  182. std::optional<AllocationId> initialized_location = std::nullopt)
  183. : Action(expression->source_loc(), Kind::ValueExpressionAction),
  184. expression_(expression),
  185. location_received_(initialized_location) {}
  186. static auto classof(const Action* action) -> bool {
  187. return action->kind() == Kind::ValueExpressionAction;
  188. }
  189. // The Expression this Action evaluates.
  190. auto expression() const -> const Expression& { return *expression_; }
  191. // The location provided for the initializing expression, if any.
  192. auto location_received() const -> std::optional<AllocationId> {
  193. return location_received_;
  194. }
  195. private:
  196. Nonnull<const Expression*> expression_;
  197. std::optional<AllocationId> location_received_;
  198. };
  199. // An Action which implements evaluation of a reference Expression to produce an
  200. // `ReferenceExpressionValue*`. The `preserve_nested_categories` flag can be
  201. // used to preserve values as `ReferenceExpressionValue` in nested value types,
  202. // such as tuples.
  203. class ExpressionAction : public Action {
  204. public:
  205. ExpressionAction(
  206. Nonnull<const Expression*> expression, bool preserve_nested_categories,
  207. std::optional<AllocationId> initialized_location = std::nullopt)
  208. : Action(expression->source_loc(), Kind::ExpressionAction),
  209. expression_(expression),
  210. location_received_(initialized_location),
  211. preserve_nested_categories_(preserve_nested_categories) {}
  212. static auto classof(const Action* action) -> bool {
  213. return action->kind() == Kind::ExpressionAction;
  214. }
  215. // The Expression this Action evaluates.
  216. auto expression() const -> const Expression& { return *expression_; }
  217. // Returns whether direct descendent actions should preserve values as
  218. // `ReferenceExpressionValue*`s.
  219. auto preserve_nested_categories() const -> bool {
  220. return preserve_nested_categories_;
  221. }
  222. // The location provided for the initializing expression, if any.
  223. auto location_received() const -> std::optional<AllocationId> {
  224. return location_received_;
  225. }
  226. private:
  227. Nonnull<const Expression*> expression_;
  228. std::optional<AllocationId> location_received_;
  229. bool preserve_nested_categories_;
  230. };
  231. // An Action which implements the Instantiation of Type. The result is expressed
  232. // as a Value.
  233. class TypeInstantiationAction : public Action {
  234. public:
  235. explicit TypeInstantiationAction(Nonnull<const Value*> type,
  236. SourceLocation source_loc)
  237. : Action(source_loc, Kind::TypeInstantiationAction),
  238. type_(type),
  239. source_loc_(source_loc) {}
  240. static auto classof(const Action* action) -> bool {
  241. return action->kind() == Kind::TypeInstantiationAction;
  242. }
  243. auto type() const -> Nonnull<const Value*> { return type_; }
  244. auto source_loc() const -> SourceLocation { return source_loc_; }
  245. private:
  246. Nonnull<const Value*> type_;
  247. SourceLocation source_loc_;
  248. };
  249. // An Action which implements evaluation of a Witness to resolve it in the
  250. // local context.
  251. class WitnessAction : public Action {
  252. public:
  253. explicit WitnessAction(Nonnull<const Witness*> witness,
  254. SourceLocation source_loc)
  255. : Action(source_loc, Kind::WitnessAction), witness_(witness) {}
  256. static auto classof(const Action* action) -> bool {
  257. return action->kind() == Kind::WitnessAction;
  258. }
  259. auto source_loc() -> SourceLocation {
  260. CARBON_CHECK(source_loc_);
  261. return *source_loc_;
  262. }
  263. // The Witness this Action resolves.
  264. auto witness() const -> Nonnull<const Witness*> { return witness_; }
  265. private:
  266. Nonnull<const Witness*> witness_;
  267. };
  268. // An Action which implements execution of a Statement. Does not produce a
  269. // result.
  270. class StatementAction : public Action {
  271. public:
  272. explicit StatementAction(Nonnull<const Statement*> statement,
  273. std::optional<AllocationId> location_received)
  274. : Action(statement->source_loc(), Kind::StatementAction),
  275. statement_(statement),
  276. location_received_(location_received) {}
  277. static auto classof(const Action* action) -> bool {
  278. return action->kind() == Kind::StatementAction;
  279. }
  280. // The Statement this Action executes.
  281. auto statement() const -> const Statement& { return *statement_; }
  282. // The location provided for the initializing expression, if any.
  283. auto location_received() const -> std::optional<AllocationId> {
  284. return location_received_;
  285. }
  286. // Sets the location provided to an initializing expression.
  287. auto set_location_created(AllocationId location_created) {
  288. CARBON_CHECK(!location_created_) << "location created set twice";
  289. location_created_ = location_created;
  290. }
  291. // Returns the location provided to an initializing expression, if any.
  292. auto location_created() const -> std::optional<AllocationId> {
  293. return location_created_;
  294. }
  295. private:
  296. Nonnull<const Statement*> statement_;
  297. std::optional<AllocationId> location_received_;
  298. std::optional<AllocationId> location_created_;
  299. };
  300. // Action which implements the run-time effects of executing a Declaration.
  301. // Does not produce a result.
  302. class DeclarationAction : public Action {
  303. public:
  304. explicit DeclarationAction(Nonnull<const Declaration*> declaration)
  305. : Action(declaration->source_loc(), Kind::DeclarationAction),
  306. declaration_(declaration) {}
  307. static auto classof(const Action* action) -> bool {
  308. return action->kind() == Kind::DeclarationAction;
  309. }
  310. // The Declaration this Action executes.
  311. auto declaration() const -> const Declaration& { return *declaration_; }
  312. private:
  313. Nonnull<const Declaration*> declaration_;
  314. };
  315. // An Action which implements destroying all local allocations in a scope.
  316. class CleanUpAction : public Action {
  317. public:
  318. explicit CleanUpAction(RuntimeScope scope, SourceLocation source_loc)
  319. : Action(source_loc, Kind::CleanUpAction),
  320. allocations_count_(scope.allocations().size()) {
  321. StartScope(std::move(scope));
  322. }
  323. auto allocations_count() const -> int { return allocations_count_; }
  324. static auto classof(const Action* action) -> bool {
  325. return action->kind() == Kind::CleanUpAction;
  326. }
  327. private:
  328. int allocations_count_;
  329. };
  330. // An Action which implements destroying a single value, including all nested
  331. // values.
  332. class DestroyAction : public Action {
  333. public:
  334. // location: Location of the object to be destroyed
  335. // value: The value to be destroyed
  336. // In most cases the location address points to value
  337. // In the case that the member of a class is to be destroyed,
  338. // the location points to the address of the class object
  339. // and the value is the member of the class
  340. explicit DestroyAction(Nonnull<const LocationValue*> location,
  341. Nonnull<const Value*> value)
  342. : Action(std::nullopt, Kind::DestroyAction),
  343. location_(location),
  344. value_(value) {}
  345. static auto classof(const Action* action) -> bool {
  346. return action->kind() == Kind::DestroyAction;
  347. }
  348. auto location() const -> Nonnull<const LocationValue*> { return location_; }
  349. auto value() const -> Nonnull<const Value*> { return value_; }
  350. private:
  351. Nonnull<const LocationValue*> location_;
  352. Nonnull<const Value*> value_;
  353. };
  354. // Action which does nothing except introduce a new scope into the action
  355. // stack. This is useful when a distinct scope doesn't otherwise have an
  356. // Action it can naturally be associated with. ScopeActions are not associated
  357. // with AST nodes.
  358. class ScopeAction : public Action {
  359. public:
  360. explicit ScopeAction(RuntimeScope scope)
  361. : Action(std::nullopt, Kind::ScopeAction) {
  362. StartScope(std::move(scope));
  363. }
  364. static auto classof(const Action* action) -> bool {
  365. return action->kind() == Kind::ScopeAction;
  366. }
  367. };
  368. // Action which contains another action and does nothing further once that
  369. // action completes. This action therefore acts as a marker on the action stack
  370. // that indicates that the interpreter should stop when the inner action has
  371. // finished, and holds the result of that inner action. This is useful to allow
  372. // a sequence of steps for an action to be run immediately rather than as part
  373. // of the normal step queue.
  374. //
  375. // Should be avoided where possible.
  376. class RecursiveAction : public Action {
  377. public:
  378. explicit RecursiveAction() : Action(std::nullopt, Kind::RecursiveAction) {}
  379. static auto classof(const Action* action) -> bool {
  380. return action->kind() == Kind::RecursiveAction;
  381. }
  382. };
  383. } // namespace Carbon
  384. #endif // CARBON_EXPLORER_INTERPRETER_ACTION_H_