interpreter.cpp 54 KB

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