interpreter.cpp 53 KB

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