action.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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 {
  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. auto kind_string() const -> std::string_view;
  124. // The position or state of the action. Starts at 0 and is typically
  125. // incremented after each step.
  126. auto pos() const -> int { return pos_; }
  127. void set_pos(int pos) { this->pos_ = pos; }
  128. // The results of any Actions spawned by this Action.
  129. auto results() const -> const std::vector<Nonnull<const Value*>>& {
  130. return results_;
  131. }
  132. void ReplaceResult(std::size_t index, Nonnull<const Value*> value) {
  133. CARBON_CHECK(index < results_.size());
  134. results_[index] = value;
  135. }
  136. // Appends `result` to `results`.
  137. void AddResult(Nonnull<const Value*> result) { results_.push_back(result); }
  138. // Returns the scope associated with this Action, if any.
  139. auto scope() -> std::optional<RuntimeScope>& { return scope_; }
  140. auto scope() const -> const std::optional<RuntimeScope>& { return scope_; }
  141. // Associates this action with a new scope, with initial state `scope`.
  142. // Values that are local to this scope will be deallocated when this
  143. // Action is completed or unwound. Can only be called once on a given
  144. // Action.
  145. void StartScope(RuntimeScope scope) {
  146. CARBON_CHECK(!scope_.has_value());
  147. scope_ = std::move(scope);
  148. }
  149. auto source_loc() const -> std::optional<SourceLocation> {
  150. return source_loc_;
  151. }
  152. protected:
  153. // Constructs an Action. `kind` must be the enumerator corresponding to the
  154. // most-derived type being constructed.
  155. explicit Action(std::optional<SourceLocation> source_loc, Kind kind)
  156. : source_loc_(source_loc), kind_(kind) {}
  157. std::optional<SourceLocation> source_loc_;
  158. private:
  159. int pos_ = 0;
  160. std::vector<Nonnull<const Value*>> results_;
  161. std::optional<RuntimeScope> scope_;
  162. const Kind kind_;
  163. };
  164. // An Action which implements evaluation of an Expression to produce an
  165. // LocationValue.
  166. class LocationAction : public Action {
  167. public:
  168. explicit LocationAction(Nonnull<const Expression*> expression)
  169. : Action(expression->source_loc(), Kind::LocationAction),
  170. expression_(expression) {}
  171. static auto classof(const Action* action) -> bool {
  172. return action->kind() == Kind::LocationAction;
  173. }
  174. // The Expression this Action evaluates.
  175. auto expression() const -> const Expression& { return *expression_; }
  176. private:
  177. Nonnull<const Expression*> expression_;
  178. };
  179. // An Action which implements evaluation of an Expression to produce a `Value*`.
  180. class ValueExpressionAction : public Action {
  181. public:
  182. explicit ValueExpressionAction(
  183. Nonnull<const Expression*> expression,
  184. std::optional<AllocationId> initialized_location = std::nullopt)
  185. : Action(expression->source_loc(), Kind::ValueExpressionAction),
  186. expression_(expression),
  187. location_received_(initialized_location) {}
  188. static auto classof(const Action* action) -> bool {
  189. return action->kind() == Kind::ValueExpressionAction;
  190. }
  191. // The Expression this Action evaluates.
  192. auto expression() const -> const Expression& { return *expression_; }
  193. // The location provided for the initializing expression, if any.
  194. auto location_received() const -> std::optional<AllocationId> {
  195. return location_received_;
  196. }
  197. private:
  198. Nonnull<const Expression*> expression_;
  199. std::optional<AllocationId> location_received_;
  200. };
  201. // An Action which implements evaluation of a reference Expression to produce an
  202. // `ReferenceExpressionValue*`. The `preserve_nested_categories` flag can be
  203. // used to preserve values as `ReferenceExpressionValue` in nested value types,
  204. // such as tuples.
  205. class ExpressionAction : public Action {
  206. public:
  207. ExpressionAction(
  208. Nonnull<const Expression*> expression, bool preserve_nested_categories,
  209. std::optional<AllocationId> initialized_location = std::nullopt)
  210. : Action(expression->source_loc(), Kind::ExpressionAction),
  211. expression_(expression),
  212. location_received_(initialized_location),
  213. preserve_nested_categories_(preserve_nested_categories) {}
  214. static auto classof(const Action* action) -> bool {
  215. return action->kind() == Kind::ExpressionAction;
  216. }
  217. // The Expression this Action evaluates.
  218. auto expression() const -> const Expression& { return *expression_; }
  219. // Returns whether direct descendent actions should preserve values as
  220. // `ReferenceExpressionValue*`s.
  221. auto preserve_nested_categories() const -> bool {
  222. return preserve_nested_categories_;
  223. }
  224. // The location provided for the initializing expression, if any.
  225. auto location_received() const -> std::optional<AllocationId> {
  226. return location_received_;
  227. }
  228. private:
  229. Nonnull<const Expression*> expression_;
  230. std::optional<AllocationId> location_received_;
  231. bool preserve_nested_categories_;
  232. };
  233. // An Action which implements the Instantiation of Type. The result is expressed
  234. // as a Value.
  235. class TypeInstantiationAction : public Action {
  236. public:
  237. explicit TypeInstantiationAction(Nonnull<const Value*> type,
  238. SourceLocation source_loc)
  239. : Action(source_loc, Kind::TypeInstantiationAction),
  240. type_(type),
  241. source_loc_(source_loc) {}
  242. static auto classof(const Action* action) -> bool {
  243. return action->kind() == Kind::TypeInstantiationAction;
  244. }
  245. auto type() const -> Nonnull<const Value*> { return type_; }
  246. auto source_loc() const -> SourceLocation { return source_loc_; }
  247. private:
  248. Nonnull<const Value*> type_;
  249. SourceLocation source_loc_;
  250. };
  251. // An Action which implements evaluation of a Witness to resolve it in the
  252. // local context.
  253. class WitnessAction : public Action {
  254. public:
  255. explicit WitnessAction(Nonnull<const Witness*> witness,
  256. SourceLocation source_loc)
  257. : Action(source_loc, Kind::WitnessAction), witness_(witness) {}
  258. static auto classof(const Action* action) -> bool {
  259. return action->kind() == Kind::WitnessAction;
  260. }
  261. auto source_loc() -> SourceLocation {
  262. CARBON_CHECK(source_loc_);
  263. return *source_loc_;
  264. }
  265. // The Witness this Action resolves.
  266. auto witness() const -> Nonnull<const Witness*> { return witness_; }
  267. private:
  268. Nonnull<const Witness*> witness_;
  269. };
  270. // An Action which implements execution of a Statement. Does not produce a
  271. // result.
  272. class StatementAction : public Action {
  273. public:
  274. explicit StatementAction(Nonnull<const Statement*> statement,
  275. std::optional<AllocationId> location_received)
  276. : Action(statement->source_loc(), Kind::StatementAction),
  277. statement_(statement),
  278. location_received_(location_received) {}
  279. static auto classof(const Action* action) -> bool {
  280. return action->kind() == Kind::StatementAction;
  281. }
  282. // The Statement this Action executes.
  283. auto statement() const -> const Statement& { return *statement_; }
  284. // The location provided for the initializing expression, if any.
  285. auto location_received() const -> std::optional<AllocationId> {
  286. return location_received_;
  287. }
  288. // Sets the location provided to an initializing expression.
  289. auto set_location_created(AllocationId location_created) {
  290. CARBON_CHECK(!location_created_) << "location created set twice";
  291. location_created_ = location_created;
  292. }
  293. // Returns the location provided to an initializing expression, if any.
  294. auto location_created() const -> std::optional<AllocationId> {
  295. return location_created_;
  296. }
  297. private:
  298. Nonnull<const Statement*> statement_;
  299. std::optional<AllocationId> location_received_;
  300. std::optional<AllocationId> location_created_;
  301. };
  302. // Action which implements the run-time effects of executing a Declaration.
  303. // Does not produce a result.
  304. class DeclarationAction : public Action {
  305. public:
  306. explicit DeclarationAction(Nonnull<const Declaration*> declaration)
  307. : Action(declaration->source_loc(), Kind::DeclarationAction),
  308. declaration_(declaration) {}
  309. static auto classof(const Action* action) -> bool {
  310. return action->kind() == Kind::DeclarationAction;
  311. }
  312. // The Declaration this Action executes.
  313. auto declaration() const -> const Declaration& { return *declaration_; }
  314. private:
  315. Nonnull<const Declaration*> declaration_;
  316. };
  317. // An Action which implements destroying all local allocations in a scope.
  318. class CleanUpAction : public Action {
  319. public:
  320. explicit CleanUpAction(RuntimeScope scope, SourceLocation source_loc)
  321. : Action(source_loc, Kind::CleanUpAction),
  322. allocations_count_(scope.allocations().size()) {
  323. StartScope(std::move(scope));
  324. }
  325. auto allocations_count() const -> int { return allocations_count_; }
  326. static auto classof(const Action* action) -> bool {
  327. return action->kind() == Kind::CleanUpAction;
  328. }
  329. private:
  330. int allocations_count_;
  331. };
  332. // An Action which implements destroying a single value, including all nested
  333. // values.
  334. class DestroyAction : public Action {
  335. public:
  336. // location: Location of the object to be destroyed
  337. // value: The value to be destroyed
  338. // In most cases the location address points to value
  339. // In the case that the member of a class is to be destroyed,
  340. // the location points to the address of the class object
  341. // and the value is the member of the class
  342. explicit DestroyAction(Nonnull<const LocationValue*> location,
  343. Nonnull<const Value*> value)
  344. : Action(std::nullopt, Kind::DestroyAction),
  345. location_(location),
  346. value_(value) {}
  347. static auto classof(const Action* action) -> bool {
  348. return action->kind() == Kind::DestroyAction;
  349. }
  350. auto location() const -> Nonnull<const LocationValue*> { return location_; }
  351. auto value() const -> Nonnull<const Value*> { return value_; }
  352. private:
  353. Nonnull<const LocationValue*> location_;
  354. Nonnull<const Value*> value_;
  355. };
  356. // Action which does nothing except introduce a new scope into the action
  357. // stack. This is useful when a distinct scope doesn't otherwise have an
  358. // Action it can naturally be associated with. ScopeActions are not associated
  359. // with AST nodes.
  360. class ScopeAction : public Action {
  361. public:
  362. explicit ScopeAction(RuntimeScope scope)
  363. : Action(std::nullopt, Kind::ScopeAction) {
  364. StartScope(std::move(scope));
  365. }
  366. static auto classof(const Action* action) -> bool {
  367. return action->kind() == Kind::ScopeAction;
  368. }
  369. };
  370. // Action which contains another action and does nothing further once that
  371. // action completes. This action therefore acts as a marker on the action stack
  372. // that indicates that the interpreter should stop when the inner action has
  373. // finished, and holds the result of that inner action. This is useful to allow
  374. // a sequence of steps for an action to be run immediately rather than as part
  375. // of the normal step queue.
  376. //
  377. // Should be avoided where possible.
  378. class RecursiveAction : public Action {
  379. public:
  380. explicit RecursiveAction() : Action(std::nullopt, Kind::RecursiveAction) {}
  381. static auto classof(const Action* action) -> bool {
  382. return action->kind() == Kind::RecursiveAction;
  383. }
  384. };
  385. } // namespace Carbon
  386. #endif // CARBON_EXPLORER_INTERPRETER_ACTION_H_