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