interpreter.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  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. #include "executable_semantics/interpreter/interpreter.h"
  5. #include <iterator>
  6. #include <map>
  7. #include <optional>
  8. #include <utility>
  9. #include <variant>
  10. #include <vector>
  11. #include "common/check.h"
  12. #include "executable_semantics/ast/declaration.h"
  13. #include "executable_semantics/ast/expression.h"
  14. #include "executable_semantics/common/arena.h"
  15. #include "executable_semantics/common/error_builders.h"
  16. #include "executable_semantics/interpreter/action.h"
  17. #include "executable_semantics/interpreter/action_stack.h"
  18. #include "executable_semantics/interpreter/stack.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/Support/Casting.h"
  21. #include "llvm/Support/Error.h"
  22. using llvm::cast;
  23. using llvm::dyn_cast;
  24. using llvm::isa;
  25. namespace Carbon {
  26. // Constructs an ActionStack suitable for the specified phase.
  27. static auto MakeTodo(Phase phase, Nonnull<Heap*> heap) -> ActionStack {
  28. switch (phase) {
  29. case Phase::CompileTime:
  30. return ActionStack();
  31. case Phase::RunTime:
  32. return ActionStack(heap);
  33. }
  34. }
  35. // An Interpreter represents an instance of the Carbon abstract machine. It
  36. // manages the state of the abstract machine, and executes the steps of Actions
  37. // passed to it.
  38. class Interpreter {
  39. public:
  40. // Constructs an Interpreter which allocates values on `arena`, and prints
  41. // traces if `trace` is true. `phase` indicates whether it executes at
  42. // compile time or run time.
  43. Interpreter(Phase phase, Nonnull<Arena*> arena,
  44. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  45. : arena_(arena),
  46. heap_(arena),
  47. todo_(MakeTodo(phase, &heap_)),
  48. trace_stream_(trace_stream),
  49. phase_(phase) {}
  50. ~Interpreter();
  51. // Runs all the steps of `action`.
  52. // It's not safe to call `RunAllSteps()` or `result()` after an error.
  53. auto RunAllSteps(std::unique_ptr<Action> action) -> ErrorOr<Success>;
  54. // The result produced by the `action` argument of the most recent
  55. // RunAllSteps call. Cannot be called if `action` was an action that doesn't
  56. // produce results.
  57. auto result() const -> Nonnull<const Value*> { return todo_.result(); }
  58. private:
  59. auto Step() -> ErrorOr<Success>;
  60. // State transitions for expressions.
  61. auto StepExp() -> ErrorOr<Success>;
  62. // State transitions for lvalues.
  63. auto StepLvalue() -> ErrorOr<Success>;
  64. // State transitions for patterns.
  65. auto StepPattern() -> ErrorOr<Success>;
  66. // State transition for statements.
  67. auto StepStmt() -> ErrorOr<Success>;
  68. // State transition for declarations.
  69. auto StepDeclaration() -> ErrorOr<Success>;
  70. auto CreateStruct(const std::vector<FieldInitializer>& fields,
  71. const std::vector<Nonnull<const Value*>>& values)
  72. -> Nonnull<const Value*>;
  73. auto EvalPrim(Operator op, const std::vector<Nonnull<const Value*>>& args,
  74. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  75. // Returns the result of converting `value` to type `destination_type`.
  76. auto Convert(Nonnull<const Value*> value,
  77. Nonnull<const Value*> destination_type,
  78. SourceLocation source_loc) const
  79. -> ErrorOr<Nonnull<const Value*>>;
  80. // Instantiate a type by replacing all type variables that occur inside the
  81. // type by the current values of those variables.
  82. //
  83. // For example, suppose T=i32 and U=Bool. Then
  84. // __Fn (Point(T)) -> Point(U)
  85. // becomes
  86. // __Fn (Point(i32)) -> Point(Bool)
  87. auto InstantiateType(Nonnull<const Value*> type,
  88. SourceLocation source_loc) const
  89. -> ErrorOr<Nonnull<const Value*>>;
  90. void PrintState(llvm::raw_ostream& out);
  91. Phase phase() const { return phase_; }
  92. Nonnull<Arena*> arena_;
  93. Heap heap_;
  94. ActionStack todo_;
  95. // The underlying states of continuation values. All StackFragments created
  96. // during execution are tracked here, in order to safely deallocate the
  97. // contents of any non-completed continuations at the end of execution.
  98. std::vector<Nonnull<ContinuationValue::StackFragment*>> stack_fragments_;
  99. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream_;
  100. Phase phase_;
  101. };
  102. Interpreter::~Interpreter() {
  103. // Clean up any remaining suspended continuations.
  104. for (Nonnull<ContinuationValue::StackFragment*> fragment : stack_fragments_) {
  105. fragment->Clear();
  106. }
  107. }
  108. //
  109. // State Operations
  110. //
  111. void Interpreter::PrintState(llvm::raw_ostream& out) {
  112. out << "{\nstack: " << todo_;
  113. out << "\nheap: " << heap_;
  114. if (!todo_.IsEmpty()) {
  115. out << "\nvalues: ";
  116. todo_.PrintScopes(out);
  117. }
  118. out << "\n}\n";
  119. }
  120. auto Interpreter::EvalPrim(Operator op,
  121. const std::vector<Nonnull<const Value*>>& args,
  122. SourceLocation source_loc)
  123. -> ErrorOr<Nonnull<const Value*>> {
  124. switch (op) {
  125. case Operator::Neg:
  126. return arena_->New<IntValue>(-cast<IntValue>(*args[0]).value());
  127. case Operator::Add:
  128. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() +
  129. cast<IntValue>(*args[1]).value());
  130. case Operator::Sub:
  131. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() -
  132. cast<IntValue>(*args[1]).value());
  133. case Operator::Mul:
  134. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() *
  135. cast<IntValue>(*args[1]).value());
  136. case Operator::Not:
  137. return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
  138. case Operator::And:
  139. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
  140. cast<BoolValue>(*args[1]).value());
  141. case Operator::Or:
  142. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
  143. cast<BoolValue>(*args[1]).value());
  144. case Operator::Eq:
  145. return arena_->New<BoolValue>(ValueEqual(args[0], args[1]));
  146. case Operator::Ptr:
  147. return arena_->New<PointerType>(args[0]);
  148. case Operator::Deref:
  149. return heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc);
  150. case Operator::AddressOf:
  151. return arena_->New<PointerValue>(cast<LValue>(*args[0]).address());
  152. }
  153. }
  154. auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
  155. const std::vector<Nonnull<const Value*>>& values)
  156. -> Nonnull<const Value*> {
  157. CHECK(fields.size() == values.size());
  158. std::vector<NamedValue> elements;
  159. for (size_t i = 0; i < fields.size(); ++i) {
  160. elements.push_back({.name = fields[i].name(), .value = values[i]});
  161. }
  162. return arena_->New<StructValue>(std::move(elements));
  163. }
  164. auto PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
  165. SourceLocation source_loc,
  166. std::optional<Nonnull<RuntimeScope*>> bindings,
  167. BindingMap& generic_args) -> bool {
  168. switch (p->kind()) {
  169. case Value::Kind::BindingPlaceholderValue: {
  170. CHECK(bindings.has_value());
  171. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  172. if (placeholder.value_node().has_value()) {
  173. (*bindings)->Initialize(*placeholder.value_node(), v);
  174. }
  175. return true;
  176. }
  177. case Value::Kind::VariableType: {
  178. const auto& var_type = cast<VariableType>(*p);
  179. generic_args[&var_type.binding()] = v;
  180. return true;
  181. }
  182. case Value::Kind::TupleValue:
  183. switch (v->kind()) {
  184. case Value::Kind::TupleValue: {
  185. const auto& p_tup = cast<TupleValue>(*p);
  186. const auto& v_tup = cast<TupleValue>(*v);
  187. CHECK(p_tup.elements().size() == v_tup.elements().size());
  188. for (size_t i = 0; i < p_tup.elements().size(); ++i) {
  189. if (!PatternMatch(p_tup.elements()[i], v_tup.elements()[i],
  190. source_loc, bindings, generic_args)) {
  191. return false;
  192. }
  193. } // for
  194. return true;
  195. }
  196. default:
  197. FATAL() << "expected a tuple value in pattern, not " << *v;
  198. }
  199. case Value::Kind::StructValue: {
  200. const auto& p_struct = cast<StructValue>(*p);
  201. const auto& v_struct = cast<StructValue>(*v);
  202. CHECK(p_struct.elements().size() == v_struct.elements().size());
  203. for (size_t i = 0; i < p_struct.elements().size(); ++i) {
  204. CHECK(p_struct.elements()[i].name == v_struct.elements()[i].name);
  205. if (!PatternMatch(p_struct.elements()[i].value,
  206. v_struct.elements()[i].value, source_loc, bindings,
  207. generic_args)) {
  208. return false;
  209. }
  210. }
  211. return true;
  212. }
  213. case Value::Kind::AlternativeValue:
  214. switch (v->kind()) {
  215. case Value::Kind::AlternativeValue: {
  216. const auto& p_alt = cast<AlternativeValue>(*p);
  217. const auto& v_alt = cast<AlternativeValue>(*v);
  218. if (p_alt.choice_name() != v_alt.choice_name() ||
  219. p_alt.alt_name() != v_alt.alt_name()) {
  220. return false;
  221. }
  222. return PatternMatch(&p_alt.argument(), &v_alt.argument(), source_loc,
  223. bindings, generic_args);
  224. }
  225. default:
  226. FATAL() << "expected a choice alternative in pattern, not " << *v;
  227. }
  228. case Value::Kind::FunctionType:
  229. switch (v->kind()) {
  230. case Value::Kind::FunctionType: {
  231. const auto& p_fn = cast<FunctionType>(*p);
  232. const auto& v_fn = cast<FunctionType>(*v);
  233. if (!PatternMatch(&p_fn.parameters(), &v_fn.parameters(), source_loc,
  234. bindings, generic_args)) {
  235. return false;
  236. }
  237. if (!PatternMatch(&p_fn.return_type(), &v_fn.return_type(),
  238. source_loc, bindings, generic_args)) {
  239. return false;
  240. }
  241. return true;
  242. }
  243. default:
  244. return false;
  245. }
  246. case Value::Kind::AutoType:
  247. // `auto` matches any type, without binding any new names. We rely
  248. // on the typechecker to ensure that `v` is a type.
  249. return true;
  250. default:
  251. return ValueEqual(p, v);
  252. }
  253. }
  254. auto Interpreter::StepLvalue() -> ErrorOr<Success> {
  255. Action& act = todo_.CurrentAction();
  256. const Expression& exp = cast<LValAction>(act).expression();
  257. if (trace_stream_) {
  258. **trace_stream_ << "--- step lvalue " << exp << " (" << exp.source_loc()
  259. << ") --->\n";
  260. }
  261. switch (exp.kind()) {
  262. case ExpressionKind::IdentifierExpression: {
  263. // { {x :: C, E, F} :: S, H}
  264. // -> { {E(x) :: C, E, F} :: S, H}
  265. ASSIGN_OR_RETURN(
  266. Nonnull<const Value*> value,
  267. todo_.ValueOfNode(cast<IdentifierExpression>(exp).value_node(),
  268. exp.source_loc()));
  269. CHECK(isa<LValue>(value)) << *value;
  270. return todo_.FinishAction(value);
  271. }
  272. case ExpressionKind::FieldAccessExpression: {
  273. if (act.pos() == 0) {
  274. // { {e.f :: C, E, F} :: S, H}
  275. // -> { e :: [].f :: C, E, F} :: S, H}
  276. return todo_.Spawn(std::make_unique<LValAction>(
  277. &cast<FieldAccessExpression>(exp).aggregate()));
  278. } else {
  279. // { v :: [].f :: C, E, F} :: S, H}
  280. // -> { { &v.f :: C, E, F} :: S, H }
  281. Address aggregate = cast<LValue>(*act.results()[0]).address();
  282. Address field = aggregate.SubobjectAddress(
  283. cast<FieldAccessExpression>(exp).field());
  284. return todo_.FinishAction(arena_->New<LValue>(field));
  285. }
  286. }
  287. case ExpressionKind::IndexExpression: {
  288. if (act.pos() == 0) {
  289. // { {e[i] :: C, E, F} :: S, H}
  290. // -> { e :: [][i] :: C, E, F} :: S, H}
  291. return todo_.Spawn(std::make_unique<LValAction>(
  292. &cast<IndexExpression>(exp).aggregate()));
  293. } else if (act.pos() == 1) {
  294. return todo_.Spawn(std::make_unique<ExpressionAction>(
  295. &cast<IndexExpression>(exp).offset()));
  296. } else {
  297. // { v :: [][i] :: C, E, F} :: S, H}
  298. // -> { { &v[i] :: C, E, F} :: S, H }
  299. Address aggregate = cast<LValue>(*act.results()[0]).address();
  300. std::string f =
  301. std::to_string(cast<IntValue>(*act.results()[1]).value());
  302. Address field = aggregate.SubobjectAddress(f);
  303. return todo_.FinishAction(arena_->New<LValue>(field));
  304. }
  305. }
  306. case ExpressionKind::PrimitiveOperatorExpression: {
  307. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  308. if (op.op() != Operator::Deref) {
  309. FATAL() << "Can't treat primitive operator expression as lvalue: "
  310. << exp;
  311. }
  312. if (act.pos() == 0) {
  313. return todo_.Spawn(
  314. std::make_unique<ExpressionAction>(op.arguments()[0]));
  315. } else {
  316. const auto& res = cast<PointerValue>(*act.results()[0]);
  317. return todo_.FinishAction(arena_->New<LValue>(res.address()));
  318. }
  319. break;
  320. }
  321. case ExpressionKind::TupleLiteral:
  322. case ExpressionKind::StructLiteral:
  323. case ExpressionKind::StructTypeLiteral:
  324. case ExpressionKind::IntLiteral:
  325. case ExpressionKind::BoolLiteral:
  326. case ExpressionKind::CallExpression:
  327. case ExpressionKind::IntTypeLiteral:
  328. case ExpressionKind::BoolTypeLiteral:
  329. case ExpressionKind::TypeTypeLiteral:
  330. case ExpressionKind::FunctionTypeLiteral:
  331. case ExpressionKind::ContinuationTypeLiteral:
  332. case ExpressionKind::StringLiteral:
  333. case ExpressionKind::StringTypeLiteral:
  334. case ExpressionKind::IntrinsicExpression:
  335. case ExpressionKind::IfExpression:
  336. case ExpressionKind::ArrayTypeLiteral:
  337. FATAL() << "Can't treat expression as lvalue: " << exp;
  338. case ExpressionKind::UnimplementedExpression:
  339. FATAL() << "Unimplemented: " << exp;
  340. }
  341. }
  342. auto Interpreter::InstantiateType(Nonnull<const Value*> type,
  343. SourceLocation source_loc) const
  344. -> ErrorOr<Nonnull<const Value*>> {
  345. if (trace_stream_) {
  346. **trace_stream_ << "instantiating: " << *type << "\n";
  347. }
  348. switch (type->kind()) {
  349. case Value::Kind::VariableType: {
  350. if (trace_stream_) {
  351. **trace_stream_ << "case VariableType\n";
  352. }
  353. ASSIGN_OR_RETURN(
  354. Nonnull<const Value*> value,
  355. todo_.ValueOfNode(&cast<VariableType>(*type).binding(), source_loc));
  356. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  357. ASSIGN_OR_RETURN(value, heap_.Read(lvalue->address(), source_loc));
  358. }
  359. return value;
  360. }
  361. case Value::Kind::NominalClassType: {
  362. if (trace_stream_) {
  363. **trace_stream_ << "case NominalClassType\n";
  364. }
  365. const auto& class_type = cast<NominalClassType>(*type);
  366. BindingMap inst_type_args;
  367. for (const auto& [ty_var, ty_arg] : class_type.type_args()) {
  368. ASSIGN_OR_RETURN(inst_type_args[ty_var],
  369. InstantiateType(ty_arg, source_loc));
  370. }
  371. if (trace_stream_) {
  372. **trace_stream_ << "finished instantiating ty_arg\n";
  373. }
  374. std::map<Nonnull<const ImplBinding*>, Nonnull<const Witness*>> witnesses;
  375. for (const auto& [bind, impl] : class_type.impls()) {
  376. ASSIGN_OR_RETURN(Nonnull<const Value*> witness_addr,
  377. todo_.ValueOfNode(impl, source_loc));
  378. if (trace_stream_) {
  379. **trace_stream_ << "witness_addr: " << *witness_addr << "\n";
  380. }
  381. // If the witness came directly from an `impl` declaration (via
  382. // `constant_value`), then it is a `Witness`. If the witness
  383. // came from the runtime scope, then the `Witness` got wrapped
  384. // in an `LValue` because that's what
  385. // `RuntimeScope::Initialize` does.
  386. Nonnull<const Witness*> witness;
  387. if (llvm::isa<Witness>(witness_addr)) {
  388. witness = cast<Witness>(witness_addr);
  389. } else if (llvm::isa<LValue>(witness_addr)) {
  390. ASSIGN_OR_RETURN(
  391. Nonnull<const Value*> witness_value,
  392. heap_.Read(llvm::cast<LValue>(witness_addr)->address(),
  393. source_loc));
  394. witness = cast<Witness>(witness_value);
  395. } else {
  396. FATAL() << "expected a witness or LValue of a witness";
  397. }
  398. witnesses[bind] = witness;
  399. }
  400. if (trace_stream_) {
  401. **trace_stream_ << "finished finding witnesses\n";
  402. }
  403. return arena_->New<NominalClassType>(&class_type.declaration(),
  404. inst_type_args, witnesses);
  405. }
  406. default:
  407. return type;
  408. }
  409. }
  410. auto Interpreter::Convert(Nonnull<const Value*> value,
  411. Nonnull<const Value*> destination_type,
  412. SourceLocation source_loc) const
  413. -> ErrorOr<Nonnull<const Value*>> {
  414. switch (value->kind()) {
  415. case Value::Kind::IntValue:
  416. case Value::Kind::FunctionValue:
  417. case Value::Kind::BoundMethodValue:
  418. case Value::Kind::PointerValue:
  419. case Value::Kind::LValue:
  420. case Value::Kind::BoolValue:
  421. case Value::Kind::NominalClassValue:
  422. case Value::Kind::AlternativeValue:
  423. case Value::Kind::IntType:
  424. case Value::Kind::BoolType:
  425. case Value::Kind::TypeType:
  426. case Value::Kind::FunctionType:
  427. case Value::Kind::PointerType:
  428. case Value::Kind::AutoType:
  429. case Value::Kind::StructType:
  430. case Value::Kind::NominalClassType:
  431. case Value::Kind::InterfaceType:
  432. case Value::Kind::Witness:
  433. case Value::Kind::ChoiceType:
  434. case Value::Kind::ContinuationType:
  435. case Value::Kind::VariableType:
  436. case Value::Kind::BindingPlaceholderValue:
  437. case Value::Kind::AlternativeConstructorValue:
  438. case Value::Kind::ContinuationValue:
  439. case Value::Kind::StringType:
  440. case Value::Kind::StringValue:
  441. case Value::Kind::TypeOfClassType:
  442. case Value::Kind::TypeOfInterfaceType:
  443. case Value::Kind::TypeOfChoiceType:
  444. case Value::Kind::StaticArrayType:
  445. // TODO: add `CHECK(TypeEqual(type, value->dynamic_type()))`, once we
  446. // have Value::dynamic_type.
  447. return value;
  448. case Value::Kind::StructValue: {
  449. const auto& struct_val = cast<StructValue>(*value);
  450. switch (destination_type->kind()) {
  451. case Value::Kind::StructType: {
  452. const auto& destination_struct_type =
  453. cast<StructType>(*destination_type);
  454. std::vector<NamedValue> new_elements;
  455. for (const auto& [field_name, field_type] :
  456. destination_struct_type.fields()) {
  457. std::optional<Nonnull<const Value*>> old_value =
  458. struct_val.FindField(field_name);
  459. ASSIGN_OR_RETURN(Nonnull<const Value*> val,
  460. Convert(*old_value, field_type, source_loc));
  461. new_elements.push_back({.name = field_name, .value = val});
  462. }
  463. return arena_->New<StructValue>(std::move(new_elements));
  464. }
  465. case Value::Kind::NominalClassType: {
  466. // Instantiate the `destintation_type` to obtain the runtime
  467. // type of the object.
  468. ASSIGN_OR_RETURN(Nonnull<const Value*> inst_dest,
  469. InstantiateType(destination_type, source_loc));
  470. return arena_->New<NominalClassValue>(inst_dest, value);
  471. }
  472. default:
  473. FATAL() << "Can't convert value " << *value << " to type "
  474. << *destination_type;
  475. }
  476. }
  477. case Value::Kind::TupleValue: {
  478. const auto& tuple = cast<TupleValue>(value);
  479. std::vector<Nonnull<const Value*>> destination_element_types;
  480. switch (destination_type->kind()) {
  481. case Value::Kind::TupleValue:
  482. destination_element_types =
  483. cast<TupleValue>(destination_type)->elements();
  484. break;
  485. case Value::Kind::StaticArrayType: {
  486. const auto& array_type = cast<StaticArrayType>(*destination_type);
  487. destination_element_types.resize(array_type.size(),
  488. &array_type.element_type());
  489. break;
  490. }
  491. default:
  492. FATAL() << "Can't convert value " << *value << " to type "
  493. << *destination_type;
  494. }
  495. CHECK(tuple->elements().size() == destination_element_types.size());
  496. std::vector<Nonnull<const Value*>> new_elements;
  497. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  498. ASSIGN_OR_RETURN(Nonnull<const Value*> val,
  499. Convert(tuple->elements()[i],
  500. destination_element_types[i], source_loc));
  501. new_elements.push_back(val);
  502. }
  503. return arena_->New<TupleValue>(std::move(new_elements));
  504. }
  505. }
  506. }
  507. auto Interpreter::StepExp() -> ErrorOr<Success> {
  508. Action& act = todo_.CurrentAction();
  509. const Expression& exp = cast<ExpressionAction>(act).expression();
  510. if (trace_stream_) {
  511. **trace_stream_ << "--- step exp " << exp << " (" << exp.source_loc()
  512. << ") --->\n";
  513. }
  514. switch (exp.kind()) {
  515. case ExpressionKind::IndexExpression: {
  516. if (act.pos() == 0) {
  517. // { { e[i] :: C, E, F} :: S, H}
  518. // -> { { e :: [][i] :: C, E, F} :: S, H}
  519. return todo_.Spawn(std::make_unique<ExpressionAction>(
  520. &cast<IndexExpression>(exp).aggregate()));
  521. } else if (act.pos() == 1) {
  522. return todo_.Spawn(std::make_unique<ExpressionAction>(
  523. &cast<IndexExpression>(exp).offset()));
  524. } else {
  525. // { { v :: [][i] :: C, E, F} :: S, H}
  526. // -> { { v_i :: C, E, F} : S, H}
  527. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  528. int i = cast<IntValue>(*act.results()[1]).value();
  529. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  530. return RuntimeError(exp.source_loc())
  531. << "index " << i << " out of range in " << tuple;
  532. }
  533. return todo_.FinishAction(tuple.elements()[i]);
  534. }
  535. }
  536. case ExpressionKind::TupleLiteral: {
  537. if (act.pos() <
  538. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  539. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  540. // H}
  541. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  542. // H}
  543. return todo_.Spawn(std::make_unique<ExpressionAction>(
  544. cast<TupleLiteral>(exp).fields()[act.pos()]));
  545. } else {
  546. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  547. }
  548. }
  549. case ExpressionKind::StructLiteral: {
  550. const auto& literal = cast<StructLiteral>(exp);
  551. if (act.pos() < static_cast<int>(literal.fields().size())) {
  552. return todo_.Spawn(std::make_unique<ExpressionAction>(
  553. &literal.fields()[act.pos()].expression()));
  554. } else {
  555. return todo_.FinishAction(
  556. CreateStruct(literal.fields(), act.results()));
  557. }
  558. }
  559. case ExpressionKind::StructTypeLiteral: {
  560. const auto& struct_type = cast<StructTypeLiteral>(exp);
  561. if (act.pos() < static_cast<int>(struct_type.fields().size())) {
  562. return todo_.Spawn(std::make_unique<ExpressionAction>(
  563. &struct_type.fields()[act.pos()].expression()));
  564. } else {
  565. std::vector<NamedValue> fields;
  566. for (size_t i = 0; i < struct_type.fields().size(); ++i) {
  567. fields.push_back({struct_type.fields()[i].name(), act.results()[i]});
  568. }
  569. return todo_.FinishAction(arena_->New<StructType>(std::move(fields)));
  570. }
  571. }
  572. case ExpressionKind::FieldAccessExpression: {
  573. const auto& access = cast<FieldAccessExpression>(exp);
  574. if (act.pos() == 0) {
  575. // { { e.f :: C, E, F} :: S, H}
  576. // -> { { e :: [].f :: C, E, F} :: S, H}
  577. return todo_.Spawn(
  578. std::make_unique<ExpressionAction>(&access.aggregate()));
  579. } else {
  580. // { { v :: [].f :: C, E, F} :: S, H}
  581. // -> { { v_f :: C, E, F} : S, H}
  582. std::optional<Nonnull<const Witness*>> witness = std::nullopt;
  583. if (access.impl().has_value()) {
  584. ASSIGN_OR_RETURN(
  585. auto witness_addr,
  586. todo_.ValueOfNode(*access.impl(), access.source_loc()));
  587. ASSIGN_OR_RETURN(
  588. Nonnull<const Value*> witness_value,
  589. heap_.Read(llvm::cast<LValue>(witness_addr)->address(),
  590. access.source_loc()));
  591. witness = cast<Witness>(witness_value);
  592. }
  593. FieldPath::Component field(access.field(), witness);
  594. ASSIGN_OR_RETURN(Nonnull<const Value*> member,
  595. act.results()[0]->GetField(arena_, FieldPath(field),
  596. exp.source_loc()));
  597. return todo_.FinishAction(member);
  598. }
  599. }
  600. case ExpressionKind::IdentifierExpression: {
  601. CHECK(act.pos() == 0);
  602. const auto& ident = cast<IdentifierExpression>(exp);
  603. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  604. ASSIGN_OR_RETURN(
  605. Nonnull<const Value*> value,
  606. todo_.ValueOfNode(ident.value_node(), ident.source_loc()));
  607. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  608. ASSIGN_OR_RETURN(value,
  609. heap_.Read(lvalue->address(), exp.source_loc()));
  610. }
  611. return todo_.FinishAction(value);
  612. }
  613. case ExpressionKind::IntLiteral:
  614. CHECK(act.pos() == 0);
  615. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  616. return todo_.FinishAction(
  617. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  618. case ExpressionKind::BoolLiteral:
  619. CHECK(act.pos() == 0);
  620. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  621. return todo_.FinishAction(
  622. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  623. case ExpressionKind::PrimitiveOperatorExpression: {
  624. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  625. if (act.pos() != static_cast<int>(op.arguments().size())) {
  626. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  627. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  628. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  629. if (op.op() == Operator::AddressOf) {
  630. return todo_.Spawn(std::make_unique<LValAction>(arg));
  631. } else {
  632. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  633. }
  634. } else {
  635. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  636. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  637. ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  638. EvalPrim(op.op(), act.results(), exp.source_loc()));
  639. return todo_.FinishAction(value);
  640. }
  641. }
  642. case ExpressionKind::CallExpression:
  643. if (act.pos() == 0) {
  644. // { {e1(e2) :: C, E, F} :: S, H}
  645. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  646. return todo_.Spawn(std::make_unique<ExpressionAction>(
  647. &cast<CallExpression>(exp).function()));
  648. } else if (act.pos() == 1) {
  649. // { { v :: [](e) :: C, E, F} :: S, H}
  650. // -> { { e :: v([]) :: C, E, F} :: S, H}
  651. return todo_.Spawn(std::make_unique<ExpressionAction>(
  652. &cast<CallExpression>(exp).argument()));
  653. } else if (act.pos() == 2) {
  654. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  655. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  656. switch (act.results()[0]->kind()) {
  657. case Value::Kind::AlternativeConstructorValue: {
  658. const auto& alt =
  659. cast<AlternativeConstructorValue>(*act.results()[0]);
  660. return todo_.FinishAction(arena_->New<AlternativeValue>(
  661. alt.alt_name(), alt.choice_name(), act.results()[1]));
  662. }
  663. case Value::Kind::FunctionValue: {
  664. const FunctionValue& fun_val =
  665. cast<FunctionValue>(*act.results()[0]);
  666. const FunctionDeclaration& function = fun_val.declaration();
  667. if (trace_stream_) {
  668. **trace_stream_ << "*** call function " << function.name()
  669. << "\n";
  670. }
  671. ASSIGN_OR_RETURN(Nonnull<const Value*> converted_args,
  672. Convert(act.results()[1],
  673. &function.param_pattern().static_type(),
  674. exp.source_loc()));
  675. RuntimeScope function_scope(&heap_);
  676. // Bring the class type arguments into scope.
  677. for (const auto& [bind, val] : fun_val.type_args()) {
  678. function_scope.Initialize(bind, val);
  679. }
  680. // Bring the deduced type arguments into scope.
  681. for (const auto& [bind, val] :
  682. cast<CallExpression>(exp).deduced_args()) {
  683. function_scope.Initialize(bind, val);
  684. }
  685. // Bring the impl witness tables into scope.
  686. for (const auto& [impl_bind, impl_node] :
  687. cast<CallExpression>(exp).impls()) {
  688. ASSIGN_OR_RETURN(Nonnull<const Value*> witness,
  689. todo_.ValueOfNode(impl_node, exp.source_loc()));
  690. if (witness->kind() == Value::Kind::LValue) {
  691. const auto& lval = cast<LValue>(*witness);
  692. ASSIGN_OR_RETURN(witness,
  693. heap_.Read(lval.address(), exp.source_loc()));
  694. }
  695. function_scope.Initialize(impl_bind, witness);
  696. }
  697. for (const auto& [impl_bind, witness] : fun_val.witnesses()) {
  698. function_scope.Initialize(impl_bind, witness);
  699. }
  700. BindingMap generic_args;
  701. CHECK(PatternMatch(&function.param_pattern().value(),
  702. converted_args, exp.source_loc(),
  703. &function_scope, generic_args));
  704. CHECK(function.body().has_value())
  705. << "Calling a function that's missing a body";
  706. return todo_.Spawn(
  707. std::make_unique<StatementAction>(*function.body()),
  708. std::move(function_scope));
  709. }
  710. case Value::Kind::BoundMethodValue: {
  711. const auto& m = cast<BoundMethodValue>(*act.results()[0]);
  712. const FunctionDeclaration& method = m.declaration();
  713. CHECK(method.is_method());
  714. ASSIGN_OR_RETURN(
  715. Nonnull<const Value*> converted_args,
  716. Convert(act.results()[1], &method.param_pattern().static_type(),
  717. exp.source_loc()));
  718. RuntimeScope method_scope(&heap_);
  719. BindingMap generic_args;
  720. CHECK(PatternMatch(&method.me_pattern().value(), m.receiver(),
  721. exp.source_loc(), &method_scope, generic_args));
  722. CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  723. exp.source_loc(), &method_scope, generic_args));
  724. // Bring the class type arguments into scope.
  725. for (const auto& [bind, val] : m.type_args()) {
  726. method_scope.Initialize(bind, val);
  727. }
  728. // Bring the impl witness tables into scope.
  729. for (const auto& [impl_bind, witness] : m.witnesses()) {
  730. method_scope.Initialize(impl_bind, witness);
  731. }
  732. CHECK(method.body().has_value())
  733. << "Calling a method that's missing a body";
  734. return todo_.Spawn(
  735. std::make_unique<StatementAction>(*method.body()),
  736. std::move(method_scope));
  737. }
  738. case Value::Kind::NominalClassType: {
  739. const NominalClassType& class_type =
  740. cast<NominalClassType>(*act.results()[0]);
  741. const ClassDeclaration& class_decl = class_type.declaration();
  742. RuntimeScope type_params_scope(&heap_);
  743. BindingMap generic_args;
  744. if (class_decl.type_params().has_value()) {
  745. CHECK(PatternMatch(&(*class_decl.type_params())->value(),
  746. act.results()[1], exp.source_loc(),
  747. &type_params_scope, generic_args));
  748. switch (phase()) {
  749. case Phase::RunTime: {
  750. std::map<Nonnull<const ImplBinding*>, const Witness*>
  751. witnesses;
  752. for (const auto& [impl_bind, impl_node] :
  753. cast<CallExpression>(exp).impls()) {
  754. ASSIGN_OR_RETURN(
  755. Nonnull<const Value*> witness,
  756. todo_.ValueOfNode(impl_node, exp.source_loc()));
  757. if (witness->kind() == Value::Kind::LValue) {
  758. const LValue& lval = cast<LValue>(*witness);
  759. ASSIGN_OR_RETURN(witness, heap_.Read(lval.address(),
  760. exp.source_loc()));
  761. }
  762. witnesses[impl_bind] = &cast<Witness>(*witness);
  763. }
  764. Nonnull<NominalClassType*> inst_class =
  765. arena_->New<NominalClassType>(&class_type.declaration(),
  766. generic_args, witnesses);
  767. return todo_.FinishAction(inst_class);
  768. }
  769. case Phase::CompileTime: {
  770. Nonnull<NominalClassType*> inst_class =
  771. arena_->New<NominalClassType>(
  772. &class_type.declaration(), generic_args,
  773. cast<CallExpression>(exp).impls());
  774. return todo_.FinishAction(inst_class);
  775. }
  776. }
  777. } else {
  778. FATAL() << "instantiation of non-generic class " << class_type;
  779. }
  780. }
  781. default:
  782. return RuntimeError(exp.source_loc())
  783. << "in call, expected a function, not " << *act.results()[0];
  784. }
  785. } else if (act.pos() == 3) {
  786. if (act.results().size() < 3) {
  787. // Control fell through without explicit return.
  788. return todo_.FinishAction(TupleValue::Empty());
  789. } else {
  790. return todo_.FinishAction(act.results()[2]);
  791. }
  792. } else {
  793. FATAL() << "in handle_value with Call pos " << act.pos();
  794. }
  795. case ExpressionKind::IntrinsicExpression: {
  796. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  797. if (act.pos() == 0) {
  798. return todo_.Spawn(
  799. std::make_unique<ExpressionAction>(&intrinsic.args()));
  800. }
  801. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  802. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  803. case IntrinsicExpression::Intrinsic::Print: {
  804. const auto& args = cast<TupleValue>(*act.results()[0]);
  805. // TODO: This could eventually use something like llvm::formatv.
  806. llvm::outs() << cast<StringValue>(*args.elements()[0]).value();
  807. return todo_.FinishAction(TupleValue::Empty());
  808. }
  809. }
  810. }
  811. case ExpressionKind::IntTypeLiteral: {
  812. CHECK(act.pos() == 0);
  813. return todo_.FinishAction(arena_->New<IntType>());
  814. }
  815. case ExpressionKind::BoolTypeLiteral: {
  816. CHECK(act.pos() == 0);
  817. return todo_.FinishAction(arena_->New<BoolType>());
  818. }
  819. case ExpressionKind::TypeTypeLiteral: {
  820. CHECK(act.pos() == 0);
  821. return todo_.FinishAction(arena_->New<TypeType>());
  822. }
  823. case ExpressionKind::FunctionTypeLiteral: {
  824. if (act.pos() == 0) {
  825. return todo_.Spawn(std::make_unique<ExpressionAction>(
  826. &cast<FunctionTypeLiteral>(exp).parameter()));
  827. } else if (act.pos() == 1) {
  828. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  829. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  830. return todo_.Spawn(std::make_unique<ExpressionAction>(
  831. &cast<FunctionTypeLiteral>(exp).return_type()));
  832. } else {
  833. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  834. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  835. return todo_.FinishAction(arena_->New<FunctionType>(
  836. std::vector<Nonnull<const GenericBinding*>>(), act.results()[0],
  837. act.results()[1], std::vector<Nonnull<const ImplBinding*>>()));
  838. }
  839. }
  840. case ExpressionKind::ContinuationTypeLiteral: {
  841. CHECK(act.pos() == 0);
  842. return todo_.FinishAction(arena_->New<ContinuationType>());
  843. }
  844. case ExpressionKind::StringLiteral:
  845. CHECK(act.pos() == 0);
  846. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  847. return todo_.FinishAction(
  848. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  849. case ExpressionKind::StringTypeLiteral: {
  850. CHECK(act.pos() == 0);
  851. return todo_.FinishAction(arena_->New<StringType>());
  852. }
  853. case ExpressionKind::IfExpression: {
  854. const auto& if_expr = cast<IfExpression>(exp);
  855. if (act.pos() == 0) {
  856. return todo_.Spawn(
  857. std::make_unique<ExpressionAction>(&if_expr.condition()));
  858. } else if (act.pos() == 1) {
  859. const auto& condition = cast<BoolValue>(*act.results()[0]);
  860. return todo_.Spawn(std::make_unique<ExpressionAction>(
  861. condition.value() ? &if_expr.then_expression()
  862. : &if_expr.else_expression()));
  863. } else {
  864. return todo_.FinishAction(act.results()[1]);
  865. }
  866. break;
  867. }
  868. case ExpressionKind::UnimplementedExpression:
  869. FATAL() << "Unimplemented: " << exp;
  870. case ExpressionKind::ArrayTypeLiteral: {
  871. const auto& array_literal = cast<ArrayTypeLiteral>(exp);
  872. if (act.pos() == 0) {
  873. return todo_.Spawn(std::make_unique<ExpressionAction>(
  874. &array_literal.element_type_expression()));
  875. } else if (act.pos() == 1) {
  876. return todo_.Spawn(std::make_unique<ExpressionAction>(
  877. &array_literal.size_expression()));
  878. } else {
  879. return todo_.FinishAction(arena_->New<StaticArrayType>(
  880. act.results()[0], cast<IntValue>(act.results()[1])->value()));
  881. }
  882. }
  883. } // switch (exp->kind)
  884. }
  885. auto Interpreter::StepPattern() -> ErrorOr<Success> {
  886. Action& act = todo_.CurrentAction();
  887. const Pattern& pattern = cast<PatternAction>(act).pattern();
  888. if (trace_stream_) {
  889. **trace_stream_ << "--- step pattern " << pattern << " ("
  890. << pattern.source_loc() << ") --->\n";
  891. }
  892. switch (pattern.kind()) {
  893. case PatternKind::AutoPattern: {
  894. CHECK(act.pos() == 0);
  895. return todo_.FinishAction(arena_->New<AutoType>());
  896. }
  897. case PatternKind::BindingPattern: {
  898. const auto& binding = cast<BindingPattern>(pattern);
  899. if (binding.name() != AnonymousName) {
  900. return todo_.FinishAction(
  901. arena_->New<BindingPlaceholderValue>(&binding));
  902. } else {
  903. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  904. }
  905. }
  906. case PatternKind::GenericBinding: {
  907. const auto& binding = cast<GenericBinding>(pattern);
  908. return todo_.FinishAction(arena_->New<VariableType>(&binding));
  909. }
  910. case PatternKind::TuplePattern: {
  911. const auto& tuple = cast<TuplePattern>(pattern);
  912. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  913. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  914. // H}
  915. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  916. // H}
  917. return todo_.Spawn(
  918. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  919. } else {
  920. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  921. }
  922. }
  923. case PatternKind::AlternativePattern: {
  924. const auto& alternative = cast<AlternativePattern>(pattern);
  925. if (act.pos() == 0) {
  926. return todo_.Spawn(
  927. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  928. } else if (act.pos() == 1) {
  929. return todo_.Spawn(
  930. std::make_unique<PatternAction>(&alternative.arguments()));
  931. } else {
  932. CHECK(act.pos() == 2);
  933. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  934. return todo_.FinishAction(arena_->New<AlternativeValue>(
  935. alternative.alternative_name(), choice_type.name(),
  936. act.results()[1]));
  937. }
  938. }
  939. case PatternKind::ExpressionPattern:
  940. if (act.pos() == 0) {
  941. return todo_.Spawn(std::make_unique<ExpressionAction>(
  942. &cast<ExpressionPattern>(pattern).expression()));
  943. } else {
  944. return todo_.FinishAction(act.results()[0]);
  945. }
  946. case PatternKind::VarPattern:
  947. if (act.pos() == 0) {
  948. return todo_.Spawn(std::make_unique<PatternAction>(
  949. &cast<VarPattern>(pattern).pattern()));
  950. } else {
  951. return todo_.FinishAction(act.results()[0]);
  952. }
  953. }
  954. }
  955. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  956. Action& act = todo_.CurrentAction();
  957. const Statement& stmt = cast<StatementAction>(act).statement();
  958. if (trace_stream_) {
  959. **trace_stream_ << "--- step stmt ";
  960. stmt.PrintDepth(1, **trace_stream_);
  961. **trace_stream_ << " (" << stmt.source_loc() << ") --->\n";
  962. }
  963. switch (stmt.kind()) {
  964. case StatementKind::Match: {
  965. const auto& match_stmt = cast<Match>(stmt);
  966. if (act.pos() == 0) {
  967. // { { (match (e) ...) :: C, E, F} :: S, H}
  968. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  969. act.StartScope(RuntimeScope(&heap_));
  970. return todo_.Spawn(
  971. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  972. } else {
  973. int clause_num = act.pos() - 1;
  974. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  975. return todo_.FinishAction();
  976. }
  977. auto c = match_stmt.clauses()[clause_num];
  978. RuntimeScope matches(&heap_);
  979. BindingMap generic_args;
  980. ASSIGN_OR_RETURN(Nonnull<const Value*> val,
  981. Convert(act.results()[0], &c.pattern().static_type(),
  982. stmt.source_loc()));
  983. if (PatternMatch(&c.pattern().value(), val, stmt.source_loc(), &matches,
  984. generic_args)) {
  985. // Ensure we don't process any more clauses.
  986. act.set_pos(match_stmt.clauses().size() + 1);
  987. todo_.MergeScope(std::move(matches));
  988. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  989. } else {
  990. return todo_.RunAgain();
  991. }
  992. }
  993. }
  994. case StatementKind::While:
  995. if (act.pos() % 2 == 0) {
  996. // { { (while (e) s) :: C, E, F} :: S, H}
  997. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  998. act.Clear();
  999. return todo_.Spawn(
  1000. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  1001. } else {
  1002. ASSIGN_OR_RETURN(Nonnull<const Value*> condition,
  1003. Convert(act.results().back(), arena_->New<BoolType>(),
  1004. stmt.source_loc()));
  1005. if (cast<BoolValue>(*condition).value()) {
  1006. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1007. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1008. return todo_.Spawn(
  1009. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  1010. } else {
  1011. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1012. // -> { { C, E, F } :: S, H}
  1013. return todo_.FinishAction();
  1014. }
  1015. }
  1016. case StatementKind::Break: {
  1017. CHECK(act.pos() == 0);
  1018. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1019. // -> { { C, E', F} :: S, H}
  1020. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  1021. }
  1022. case StatementKind::Continue: {
  1023. CHECK(act.pos() == 0);
  1024. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1025. // -> { { (while (e) s) :: C, E', F} :: S, H}
  1026. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  1027. }
  1028. case StatementKind::Block: {
  1029. const auto& block = cast<Block>(stmt);
  1030. if (act.pos() >= static_cast<int>(block.statements().size())) {
  1031. // If the position is past the end of the block, end processing. Note
  1032. // that empty blocks immediately end.
  1033. return todo_.FinishAction();
  1034. }
  1035. // Initialize a scope when starting a block.
  1036. if (act.pos() == 0) {
  1037. act.StartScope(RuntimeScope(&heap_));
  1038. }
  1039. // Process the next statement in the block. The position will be
  1040. // incremented as part of Spawn.
  1041. return todo_.Spawn(
  1042. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  1043. }
  1044. case StatementKind::VariableDefinition: {
  1045. const auto& definition = cast<VariableDefinition>(stmt);
  1046. if (act.pos() == 0) {
  1047. // { {(var x = e) :: C, E, F} :: S, H}
  1048. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  1049. return todo_.Spawn(
  1050. std::make_unique<ExpressionAction>(&definition.init()));
  1051. } else {
  1052. // { { v :: (x = []) :: C, E, F} :: S, H}
  1053. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1054. ASSIGN_OR_RETURN(
  1055. Nonnull<const Value*> v,
  1056. Convert(act.results()[0], &definition.pattern().static_type(),
  1057. stmt.source_loc()));
  1058. Nonnull<const Value*> p =
  1059. &cast<VariableDefinition>(stmt).pattern().value();
  1060. RuntimeScope matches(&heap_);
  1061. BindingMap generic_args;
  1062. CHECK(PatternMatch(p, v, stmt.source_loc(), &matches, generic_args))
  1063. << stmt.source_loc()
  1064. << ": internal error in variable definition, match failed";
  1065. todo_.MergeScope(std::move(matches));
  1066. return todo_.FinishAction();
  1067. }
  1068. }
  1069. case StatementKind::ExpressionStatement:
  1070. if (act.pos() == 0) {
  1071. // { {e :: C, E, F} :: S, H}
  1072. // -> { {e :: C, E, F} :: S, H}
  1073. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1074. &cast<ExpressionStatement>(stmt).expression()));
  1075. } else {
  1076. return todo_.FinishAction();
  1077. }
  1078. case StatementKind::Assign: {
  1079. const auto& assign = cast<Assign>(stmt);
  1080. if (act.pos() == 0) {
  1081. // { {(lv = e) :: C, E, F} :: S, H}
  1082. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1083. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  1084. } else if (act.pos() == 1) {
  1085. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1086. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1087. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  1088. } else {
  1089. // { { v :: (a = []) :: C, E, F} :: S, H}
  1090. // -> { { C, E, F} :: S, H(a := v)}
  1091. const auto& lval = cast<LValue>(*act.results()[0]);
  1092. ASSIGN_OR_RETURN(Nonnull<const Value*> rval,
  1093. Convert(act.results()[1], &assign.lhs().static_type(),
  1094. stmt.source_loc()));
  1095. RETURN_IF_ERROR(heap_.Write(lval.address(), rval, stmt.source_loc()));
  1096. return todo_.FinishAction();
  1097. }
  1098. }
  1099. case StatementKind::If:
  1100. if (act.pos() == 0) {
  1101. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1102. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1103. return todo_.Spawn(
  1104. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  1105. } else if (act.pos() == 1) {
  1106. ASSIGN_OR_RETURN(Nonnull<const Value*> condition,
  1107. Convert(act.results()[0], arena_->New<BoolType>(),
  1108. stmt.source_loc()));
  1109. if (cast<BoolValue>(*condition).value()) {
  1110. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1111. // S, H}
  1112. // -> { { then_stmt :: C, E, F } :: S, H}
  1113. return todo_.Spawn(
  1114. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  1115. } else if (cast<If>(stmt).else_block()) {
  1116. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1117. // S, H}
  1118. // -> { { else_stmt :: C, E, F } :: S, H}
  1119. return todo_.Spawn(
  1120. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  1121. } else {
  1122. return todo_.FinishAction();
  1123. }
  1124. } else {
  1125. return todo_.FinishAction();
  1126. }
  1127. case StatementKind::Return:
  1128. if (act.pos() == 0) {
  1129. // { {return e :: C, E, F} :: S, H}
  1130. // -> { {e :: return [] :: C, E, F} :: S, H}
  1131. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1132. &cast<Return>(stmt).expression()));
  1133. } else {
  1134. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1135. // -> { {v :: C', E', F'} :: S, H}
  1136. const FunctionDeclaration& function = cast<Return>(stmt).function();
  1137. ASSIGN_OR_RETURN(
  1138. Nonnull<const Value*> return_value,
  1139. Convert(act.results()[0], &function.return_term().static_type(),
  1140. stmt.source_loc()));
  1141. return todo_.UnwindPast(*function.body(), return_value);
  1142. }
  1143. case StatementKind::Continuation: {
  1144. CHECK(act.pos() == 0);
  1145. const auto& continuation = cast<Continuation>(stmt);
  1146. // Create a continuation object by creating a frame similar the
  1147. // way one is created in a function call.
  1148. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  1149. stack_fragments_.push_back(fragment);
  1150. todo_.InitializeFragment(*fragment, &continuation.body());
  1151. // Bind the continuation object to the continuation variable
  1152. todo_.Initialize(&cast<Continuation>(stmt),
  1153. arena_->New<ContinuationValue>(fragment));
  1154. return todo_.FinishAction();
  1155. }
  1156. case StatementKind::Run: {
  1157. auto& run = cast<Run>(stmt);
  1158. if (act.pos() == 0) {
  1159. // Evaluate the argument of the run statement.
  1160. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  1161. } else if (act.pos() == 1) {
  1162. // Push the continuation onto the current stack.
  1163. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  1164. } else {
  1165. return todo_.FinishAction();
  1166. }
  1167. }
  1168. case StatementKind::Await:
  1169. CHECK(act.pos() == 0);
  1170. return todo_.Suspend();
  1171. }
  1172. }
  1173. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  1174. Action& act = todo_.CurrentAction();
  1175. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  1176. if (trace_stream_) {
  1177. **trace_stream_ << "--- step declaration (" << decl.source_loc()
  1178. << ") --->\n";
  1179. }
  1180. switch (decl.kind()) {
  1181. case DeclarationKind::VariableDeclaration: {
  1182. const auto& var_decl = cast<VariableDeclaration>(decl);
  1183. if (var_decl.has_initializer()) {
  1184. if (act.pos() == 0) {
  1185. return todo_.Spawn(
  1186. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  1187. } else {
  1188. todo_.Initialize(&var_decl.binding(), act.results()[0]);
  1189. return todo_.FinishAction();
  1190. }
  1191. } else {
  1192. return todo_.FinishAction();
  1193. }
  1194. }
  1195. case DeclarationKind::FunctionDeclaration:
  1196. case DeclarationKind::ClassDeclaration:
  1197. case DeclarationKind::ChoiceDeclaration:
  1198. case DeclarationKind::InterfaceDeclaration:
  1199. case DeclarationKind::ImplDeclaration:
  1200. // These declarations have no run-time effects.
  1201. return todo_.FinishAction();
  1202. }
  1203. }
  1204. // State transition.
  1205. auto Interpreter::Step() -> ErrorOr<Success> {
  1206. Action& act = todo_.CurrentAction();
  1207. switch (act.kind()) {
  1208. case Action::Kind::LValAction:
  1209. RETURN_IF_ERROR(StepLvalue());
  1210. break;
  1211. case Action::Kind::ExpressionAction:
  1212. RETURN_IF_ERROR(StepExp());
  1213. break;
  1214. case Action::Kind::PatternAction:
  1215. RETURN_IF_ERROR(StepPattern());
  1216. break;
  1217. case Action::Kind::StatementAction:
  1218. RETURN_IF_ERROR(StepStmt());
  1219. break;
  1220. case Action::Kind::DeclarationAction:
  1221. RETURN_IF_ERROR(StepDeclaration());
  1222. break;
  1223. case Action::Kind::ScopeAction:
  1224. FATAL() << "ScopeAction escaped ActionStack";
  1225. } // switch
  1226. return Success();
  1227. }
  1228. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  1229. -> ErrorOr<Success> {
  1230. if (trace_stream_) {
  1231. PrintState(**trace_stream_);
  1232. }
  1233. todo_.Start(std::move(action));
  1234. while (!todo_.IsEmpty()) {
  1235. RETURN_IF_ERROR(Step());
  1236. if (trace_stream_) {
  1237. PrintState(**trace_stream_);
  1238. }
  1239. }
  1240. return Success();
  1241. }
  1242. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena,
  1243. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1244. -> ErrorOr<int> {
  1245. Interpreter interpreter(Phase::RunTime, arena, trace_stream);
  1246. if (trace_stream) {
  1247. **trace_stream << "********** initializing globals **********\n";
  1248. }
  1249. for (Nonnull<Declaration*> declaration : ast.declarations) {
  1250. RETURN_IF_ERROR(interpreter.RunAllSteps(
  1251. std::make_unique<DeclarationAction>(declaration)));
  1252. }
  1253. if (trace_stream) {
  1254. **trace_stream << "********** calling main function **********\n";
  1255. }
  1256. RETURN_IF_ERROR(interpreter.RunAllSteps(
  1257. std::make_unique<ExpressionAction>(*ast.main_call)));
  1258. return cast<IntValue>(*interpreter.result()).value();
  1259. }
  1260. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena,
  1261. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1262. -> ErrorOr<Nonnull<const Value*>> {
  1263. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1264. RETURN_IF_ERROR(
  1265. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e)));
  1266. return interpreter.result();
  1267. }
  1268. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena,
  1269. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1270. -> ErrorOr<Nonnull<const Value*>> {
  1271. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1272. RETURN_IF_ERROR(interpreter.RunAllSteps(std::make_unique<PatternAction>(p)));
  1273. return interpreter.result();
  1274. }
  1275. } // namespace Carbon