interpreter.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  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 "explorer/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 "explorer/ast/declaration.h"
  13. #include "explorer/ast/expression.h"
  14. #include "explorer/common/arena.h"
  15. #include "explorer/common/error_builders.h"
  16. #include "explorer/interpreter/action.h"
  17. #include "explorer/interpreter/action_stack.h"
  18. #include "explorer/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::ParameterizedEntityName:
  447. case Value::Kind::ChoiceType:
  448. case Value::Kind::ContinuationType:
  449. case Value::Kind::VariableType:
  450. case Value::Kind::BindingPlaceholderValue:
  451. case Value::Kind::AlternativeConstructorValue:
  452. case Value::Kind::ContinuationValue:
  453. case Value::Kind::StringType:
  454. case Value::Kind::StringValue:
  455. case Value::Kind::TypeOfClassType:
  456. case Value::Kind::TypeOfInterfaceType:
  457. case Value::Kind::TypeOfChoiceType:
  458. case Value::Kind::TypeOfParameterizedEntityName:
  459. case Value::Kind::StaticArrayType:
  460. // TODO: add `CHECK(TypeEqual(type, value->dynamic_type()))`, once we
  461. // have Value::dynamic_type.
  462. return value;
  463. case Value::Kind::StructValue: {
  464. const auto& struct_val = cast<StructValue>(*value);
  465. switch (destination_type->kind()) {
  466. case Value::Kind::StructType: {
  467. const auto& destination_struct_type =
  468. cast<StructType>(*destination_type);
  469. std::vector<NamedValue> new_elements;
  470. for (const auto& [field_name, field_type] :
  471. destination_struct_type.fields()) {
  472. std::optional<Nonnull<const Value*>> old_value =
  473. struct_val.FindField(field_name);
  474. ASSIGN_OR_RETURN(Nonnull<const Value*> val,
  475. Convert(*old_value, field_type, source_loc));
  476. new_elements.push_back({.name = field_name, .value = val});
  477. }
  478. return arena_->New<StructValue>(std::move(new_elements));
  479. }
  480. case Value::Kind::NominalClassType: {
  481. // Instantiate the `destintation_type` to obtain the runtime
  482. // type of the object.
  483. ASSIGN_OR_RETURN(Nonnull<const Value*> inst_dest,
  484. InstantiateType(destination_type, source_loc));
  485. return arena_->New<NominalClassValue>(inst_dest, value);
  486. }
  487. default:
  488. FATAL() << "Can't convert value " << *value << " to type "
  489. << *destination_type;
  490. }
  491. }
  492. case Value::Kind::TupleValue: {
  493. const auto& tuple = cast<TupleValue>(value);
  494. std::vector<Nonnull<const Value*>> destination_element_types;
  495. switch (destination_type->kind()) {
  496. case Value::Kind::TupleValue:
  497. destination_element_types =
  498. cast<TupleValue>(destination_type)->elements();
  499. break;
  500. case Value::Kind::StaticArrayType: {
  501. const auto& array_type = cast<StaticArrayType>(*destination_type);
  502. destination_element_types.resize(array_type.size(),
  503. &array_type.element_type());
  504. break;
  505. }
  506. default:
  507. FATAL() << "Can't convert value " << *value << " to type "
  508. << *destination_type;
  509. }
  510. CHECK(tuple->elements().size() == destination_element_types.size());
  511. std::vector<Nonnull<const Value*>> new_elements;
  512. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  513. ASSIGN_OR_RETURN(Nonnull<const Value*> val,
  514. Convert(tuple->elements()[i],
  515. destination_element_types[i], source_loc));
  516. new_elements.push_back(val);
  517. }
  518. return arena_->New<TupleValue>(std::move(new_elements));
  519. }
  520. }
  521. }
  522. auto Interpreter::CallFunction(const CallExpression& call,
  523. Nonnull<const Value*> fun,
  524. Nonnull<const Value*> arg,
  525. const ImplWitnessMap& witnesses)
  526. -> ErrorOr<Success> {
  527. if (trace_stream_) {
  528. **trace_stream_ << "calling function: " << *fun << "\n";
  529. }
  530. switch (fun->kind()) {
  531. case Value::Kind::AlternativeConstructorValue: {
  532. const auto& alt = cast<AlternativeConstructorValue>(*fun);
  533. return todo_.FinishAction(arena_->New<AlternativeValue>(
  534. alt.alt_name(), alt.choice_name(), arg));
  535. }
  536. case Value::Kind::FunctionValue: {
  537. const FunctionValue& fun_val = cast<FunctionValue>(*fun);
  538. const FunctionDeclaration& function = fun_val.declaration();
  539. ASSIGN_OR_RETURN(Nonnull<const Value*> converted_args,
  540. Convert(arg, &function.param_pattern().static_type(),
  541. call.source_loc()));
  542. RuntimeScope function_scope(&heap_);
  543. // Bring the class type arguments into scope.
  544. for (const auto& [bind, val] : fun_val.type_args()) {
  545. function_scope.Initialize(bind, val);
  546. }
  547. // Bring the deduced type arguments into scope.
  548. for (const auto& [bind, val] : call.deduced_args()) {
  549. function_scope.Initialize(bind, val);
  550. }
  551. // Bring the impl witness tables into scope.
  552. for (const auto& [impl_bind, witness] : witnesses) {
  553. function_scope.Initialize(impl_bind, witness);
  554. }
  555. for (const auto& [impl_bind, witness] : fun_val.witnesses()) {
  556. function_scope.Initialize(impl_bind, witness);
  557. }
  558. BindingMap generic_args;
  559. CHECK(PatternMatch(&function.param_pattern().value(), converted_args,
  560. call.source_loc(), &function_scope, generic_args,
  561. trace_stream_));
  562. CHECK(function.body().has_value())
  563. << "Calling a function that's missing a body";
  564. return todo_.Spawn(std::make_unique<StatementAction>(*function.body()),
  565. std::move(function_scope));
  566. }
  567. case Value::Kind::BoundMethodValue: {
  568. const auto& m = cast<BoundMethodValue>(*fun);
  569. const FunctionDeclaration& method = m.declaration();
  570. CHECK(method.is_method());
  571. ASSIGN_OR_RETURN(Nonnull<const Value*> converted_args,
  572. Convert(arg, &method.param_pattern().static_type(),
  573. call.source_loc()));
  574. RuntimeScope method_scope(&heap_);
  575. BindingMap generic_args;
  576. CHECK(PatternMatch(&method.me_pattern().value(), m.receiver(),
  577. call.source_loc(), &method_scope, generic_args,
  578. trace_stream_));
  579. CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  580. call.source_loc(), &method_scope, generic_args,
  581. trace_stream_));
  582. // Bring the class type arguments into scope.
  583. for (const auto& [bind, val] : m.type_args()) {
  584. method_scope.Initialize(bind, val);
  585. }
  586. // Bring the impl witness tables into scope.
  587. for (const auto& [impl_bind, witness] : m.witnesses()) {
  588. method_scope.Initialize(impl_bind, witness);
  589. }
  590. CHECK(method.body().has_value())
  591. << "Calling a method that's missing a body";
  592. return todo_.Spawn(std::make_unique<StatementAction>(*method.body()),
  593. std::move(method_scope));
  594. }
  595. case Value::Kind::ParameterizedEntityName: {
  596. const auto& name = cast<ParameterizedEntityName>(*fun);
  597. const Declaration& decl = name.declaration();
  598. RuntimeScope params_scope(&heap_);
  599. BindingMap generic_args;
  600. CHECK(PatternMatch(&name.params().value(), arg, call.source_loc(),
  601. &params_scope, generic_args, trace_stream_));
  602. switch (decl.kind()) {
  603. case DeclarationKind::ClassDeclaration: {
  604. switch (phase()) {
  605. case Phase::RunTime:
  606. return todo_.FinishAction(arena_->New<NominalClassType>(
  607. &cast<ClassDeclaration>(decl), generic_args, witnesses));
  608. case Phase::CompileTime:
  609. return todo_.FinishAction(arena_->New<NominalClassType>(
  610. &cast<ClassDeclaration>(decl), generic_args, call.impls()));
  611. }
  612. }
  613. case DeclarationKind::InterfaceDeclaration: {
  614. switch (phase()) {
  615. case Phase::RunTime:
  616. return todo_.FinishAction(arena_->New<InterfaceType>(
  617. &cast<InterfaceDeclaration>(decl), generic_args, witnesses));
  618. case Phase::CompileTime:
  619. return todo_.FinishAction(
  620. arena_->New<InterfaceType>(&cast<InterfaceDeclaration>(decl),
  621. generic_args, call.impls()));
  622. }
  623. }
  624. default:
  625. FATAL() << "unknown kind of ParameterizedEntityName " << decl;
  626. }
  627. }
  628. default:
  629. return RuntimeError(call.source_loc())
  630. << "in call, expected a function, not " << *fun;
  631. }
  632. }
  633. auto Interpreter::StepExp() -> ErrorOr<Success> {
  634. Action& act = todo_.CurrentAction();
  635. const Expression& exp = cast<ExpressionAction>(act).expression();
  636. if (trace_stream_) {
  637. **trace_stream_ << "--- step exp " << exp << " (" << exp.source_loc()
  638. << ") --->\n";
  639. }
  640. switch (exp.kind()) {
  641. case ExpressionKind::InstantiateImpl: {
  642. const InstantiateImpl& inst_impl = cast<InstantiateImpl>(exp);
  643. if (act.pos() == 0) {
  644. return todo_.Spawn(
  645. std::make_unique<ExpressionAction>(inst_impl.generic_impl()));
  646. } else if (act.pos() - 1 < int(inst_impl.impls().size())) {
  647. auto iter = inst_impl.impls().begin();
  648. std::advance(iter, act.pos() - 1);
  649. return todo_.Spawn(std::make_unique<ExpressionAction>(iter->second));
  650. } else {
  651. Nonnull<const Witness*> generic_witness =
  652. cast<Witness>(act.results()[0]);
  653. ImplWitnessMap witnesses;
  654. int i = 0;
  655. for (const auto& [impl_bind, impl_exp] : inst_impl.impls()) {
  656. witnesses[impl_bind] = cast<Witness>(act.results()[i + 1]);
  657. ++i;
  658. }
  659. return todo_.FinishAction(arena_->New<Witness>(
  660. &generic_witness->declaration(), inst_impl.type_args(), witnesses));
  661. }
  662. }
  663. case ExpressionKind::IndexExpression: {
  664. if (act.pos() == 0) {
  665. // { { e[i] :: C, E, F} :: S, H}
  666. // -> { { e :: [][i] :: C, E, F} :: S, H}
  667. return todo_.Spawn(std::make_unique<ExpressionAction>(
  668. &cast<IndexExpression>(exp).aggregate()));
  669. } else if (act.pos() == 1) {
  670. return todo_.Spawn(std::make_unique<ExpressionAction>(
  671. &cast<IndexExpression>(exp).offset()));
  672. } else {
  673. // { { v :: [][i] :: C, E, F} :: S, H}
  674. // -> { { v_i :: C, E, F} : S, H}
  675. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  676. int i = cast<IntValue>(*act.results()[1]).value();
  677. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  678. return RuntimeError(exp.source_loc())
  679. << "index " << i << " out of range in " << tuple;
  680. }
  681. return todo_.FinishAction(tuple.elements()[i]);
  682. }
  683. }
  684. case ExpressionKind::TupleLiteral: {
  685. if (act.pos() <
  686. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  687. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  688. // H}
  689. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  690. // H}
  691. return todo_.Spawn(std::make_unique<ExpressionAction>(
  692. cast<TupleLiteral>(exp).fields()[act.pos()]));
  693. } else {
  694. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  695. }
  696. }
  697. case ExpressionKind::StructLiteral: {
  698. const auto& literal = cast<StructLiteral>(exp);
  699. if (act.pos() < static_cast<int>(literal.fields().size())) {
  700. return todo_.Spawn(std::make_unique<ExpressionAction>(
  701. &literal.fields()[act.pos()].expression()));
  702. } else {
  703. return todo_.FinishAction(
  704. CreateStruct(literal.fields(), act.results()));
  705. }
  706. }
  707. case ExpressionKind::StructTypeLiteral: {
  708. const auto& struct_type = cast<StructTypeLiteral>(exp);
  709. if (act.pos() < static_cast<int>(struct_type.fields().size())) {
  710. return todo_.Spawn(std::make_unique<ExpressionAction>(
  711. &struct_type.fields()[act.pos()].expression()));
  712. } else {
  713. std::vector<NamedValue> fields;
  714. for (size_t i = 0; i < struct_type.fields().size(); ++i) {
  715. fields.push_back({struct_type.fields()[i].name(), act.results()[i]});
  716. }
  717. return todo_.FinishAction(arena_->New<StructType>(std::move(fields)));
  718. }
  719. }
  720. case ExpressionKind::FieldAccessExpression: {
  721. const auto& access = cast<FieldAccessExpression>(exp);
  722. if (act.pos() == 0) {
  723. // { { e.f :: C, E, F} :: S, H}
  724. // -> { { e :: [].f :: C, E, F} :: S, H}
  725. return todo_.Spawn(
  726. std::make_unique<ExpressionAction>(&access.aggregate()));
  727. } else {
  728. // { { v :: [].f :: C, E, F} :: S, H}
  729. // -> { { v_f :: C, E, F} : S, H}
  730. std::optional<Nonnull<const Witness*>> witness = std::nullopt;
  731. if (access.impl().has_value()) {
  732. ASSIGN_OR_RETURN(
  733. auto witness_addr,
  734. todo_.ValueOfNode(*access.impl(), access.source_loc()));
  735. ASSIGN_OR_RETURN(
  736. Nonnull<const Value*> witness_value,
  737. heap_.Read(llvm::cast<LValue>(witness_addr)->address(),
  738. access.source_loc()));
  739. witness = cast<Witness>(witness_value);
  740. }
  741. FieldPath::Component field(access.field(), witness);
  742. ASSIGN_OR_RETURN(Nonnull<const Value*> member,
  743. act.results()[0]->GetField(arena_, FieldPath(field),
  744. exp.source_loc()));
  745. return todo_.FinishAction(member);
  746. }
  747. }
  748. case ExpressionKind::IdentifierExpression: {
  749. CHECK(act.pos() == 0);
  750. const auto& ident = cast<IdentifierExpression>(exp);
  751. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  752. ASSIGN_OR_RETURN(
  753. Nonnull<const Value*> value,
  754. todo_.ValueOfNode(ident.value_node(), ident.source_loc()));
  755. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  756. ASSIGN_OR_RETURN(value,
  757. heap_.Read(lvalue->address(), exp.source_loc()));
  758. }
  759. return todo_.FinishAction(value);
  760. }
  761. case ExpressionKind::IntLiteral:
  762. CHECK(act.pos() == 0);
  763. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  764. return todo_.FinishAction(
  765. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  766. case ExpressionKind::BoolLiteral:
  767. CHECK(act.pos() == 0);
  768. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  769. return todo_.FinishAction(
  770. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  771. case ExpressionKind::PrimitiveOperatorExpression: {
  772. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  773. if (act.pos() != static_cast<int>(op.arguments().size())) {
  774. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  775. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  776. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  777. if (op.op() == Operator::AddressOf) {
  778. return todo_.Spawn(std::make_unique<LValAction>(arg));
  779. } else {
  780. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  781. }
  782. } else {
  783. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  784. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  785. ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  786. EvalPrim(op.op(), act.results(), exp.source_loc()));
  787. return todo_.FinishAction(value);
  788. }
  789. }
  790. case ExpressionKind::CallExpression: {
  791. const CallExpression& call = cast<CallExpression>(exp);
  792. // Don't evaluate the impls at compile time?
  793. unsigned int num_impls =
  794. phase() == Phase::CompileTime ? 0 : call.impls().size();
  795. if (act.pos() == 0) {
  796. // { {e1(e2) :: C, E, F} :: S, H}
  797. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  798. return todo_.Spawn(
  799. std::make_unique<ExpressionAction>(&call.function()));
  800. } else if (act.pos() == 1) {
  801. // { { v :: [](e) :: C, E, F} :: S, H}
  802. // -> { { e :: v([]) :: C, E, F} :: S, H}
  803. return todo_.Spawn(
  804. std::make_unique<ExpressionAction>(&call.argument()));
  805. } else if (num_impls > 0 && act.pos() < 2 + int(num_impls)) {
  806. auto iter = call.impls().begin();
  807. std::advance(iter, act.pos() - 2);
  808. return todo_.Spawn(std::make_unique<ExpressionAction>(iter->second));
  809. } else if (act.pos() == 2 + int(num_impls)) {
  810. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  811. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  812. ImplWitnessMap witnesses;
  813. if (num_impls > 0) {
  814. int i = 2;
  815. for (const auto& [impl_bind, impl_exp] : call.impls()) {
  816. witnesses[impl_bind] = cast<Witness>(act.results()[i]);
  817. ++i;
  818. }
  819. }
  820. return CallFunction(call, act.results()[0], act.results()[1],
  821. witnesses);
  822. } else if (act.pos() == 3 + int(num_impls)) {
  823. if (act.results().size() < 3 + num_impls) {
  824. // Control fell through without explicit return.
  825. return todo_.FinishAction(TupleValue::Empty());
  826. } else {
  827. return todo_.FinishAction(act.results()[2 + int(num_impls)]);
  828. }
  829. } else {
  830. FATAL() << "in StepExp with Call pos " << act.pos();
  831. }
  832. }
  833. case ExpressionKind::IntrinsicExpression: {
  834. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  835. if (act.pos() == 0) {
  836. return todo_.Spawn(
  837. std::make_unique<ExpressionAction>(&intrinsic.args()));
  838. }
  839. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  840. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  841. case IntrinsicExpression::Intrinsic::Print: {
  842. const auto& args = cast<TupleValue>(*act.results()[0]);
  843. // TODO: This could eventually use something like llvm::formatv.
  844. llvm::outs() << cast<StringValue>(*args.elements()[0]).value();
  845. return todo_.FinishAction(TupleValue::Empty());
  846. }
  847. }
  848. }
  849. case ExpressionKind::IntTypeLiteral: {
  850. CHECK(act.pos() == 0);
  851. return todo_.FinishAction(arena_->New<IntType>());
  852. }
  853. case ExpressionKind::BoolTypeLiteral: {
  854. CHECK(act.pos() == 0);
  855. return todo_.FinishAction(arena_->New<BoolType>());
  856. }
  857. case ExpressionKind::TypeTypeLiteral: {
  858. CHECK(act.pos() == 0);
  859. return todo_.FinishAction(arena_->New<TypeType>());
  860. }
  861. case ExpressionKind::FunctionTypeLiteral: {
  862. if (act.pos() == 0) {
  863. return todo_.Spawn(std::make_unique<ExpressionAction>(
  864. &cast<FunctionTypeLiteral>(exp).parameter()));
  865. } else if (act.pos() == 1) {
  866. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  867. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  868. return todo_.Spawn(std::make_unique<ExpressionAction>(
  869. &cast<FunctionTypeLiteral>(exp).return_type()));
  870. } else {
  871. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  872. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  873. return todo_.FinishAction(arena_->New<FunctionType>(
  874. std::vector<Nonnull<const GenericBinding*>>(), act.results()[0],
  875. act.results()[1], std::vector<Nonnull<const ImplBinding*>>()));
  876. }
  877. }
  878. case ExpressionKind::ContinuationTypeLiteral: {
  879. CHECK(act.pos() == 0);
  880. return todo_.FinishAction(arena_->New<ContinuationType>());
  881. }
  882. case ExpressionKind::StringLiteral:
  883. CHECK(act.pos() == 0);
  884. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  885. return todo_.FinishAction(
  886. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  887. case ExpressionKind::StringTypeLiteral: {
  888. CHECK(act.pos() == 0);
  889. return todo_.FinishAction(arena_->New<StringType>());
  890. }
  891. case ExpressionKind::IfExpression: {
  892. const auto& if_expr = cast<IfExpression>(exp);
  893. if (act.pos() == 0) {
  894. return todo_.Spawn(
  895. std::make_unique<ExpressionAction>(&if_expr.condition()));
  896. } else if (act.pos() == 1) {
  897. const auto& condition = cast<BoolValue>(*act.results()[0]);
  898. return todo_.Spawn(std::make_unique<ExpressionAction>(
  899. condition.value() ? &if_expr.then_expression()
  900. : &if_expr.else_expression()));
  901. } else {
  902. return todo_.FinishAction(act.results()[1]);
  903. }
  904. break;
  905. }
  906. case ExpressionKind::UnimplementedExpression:
  907. FATAL() << "Unimplemented: " << exp;
  908. case ExpressionKind::ArrayTypeLiteral: {
  909. const auto& array_literal = cast<ArrayTypeLiteral>(exp);
  910. if (act.pos() == 0) {
  911. return todo_.Spawn(std::make_unique<ExpressionAction>(
  912. &array_literal.element_type_expression()));
  913. } else if (act.pos() == 1) {
  914. return todo_.Spawn(std::make_unique<ExpressionAction>(
  915. &array_literal.size_expression()));
  916. } else {
  917. return todo_.FinishAction(arena_->New<StaticArrayType>(
  918. act.results()[0], cast<IntValue>(act.results()[1])->value()));
  919. }
  920. }
  921. } // switch (exp->kind)
  922. }
  923. auto Interpreter::StepPattern() -> ErrorOr<Success> {
  924. Action& act = todo_.CurrentAction();
  925. const Pattern& pattern = cast<PatternAction>(act).pattern();
  926. if (trace_stream_) {
  927. **trace_stream_ << "--- step pattern " << pattern << " ("
  928. << pattern.source_loc() << ") --->\n";
  929. }
  930. switch (pattern.kind()) {
  931. case PatternKind::AutoPattern: {
  932. CHECK(act.pos() == 0);
  933. return todo_.FinishAction(arena_->New<AutoType>());
  934. }
  935. case PatternKind::BindingPattern: {
  936. const auto& binding = cast<BindingPattern>(pattern);
  937. if (binding.name() != AnonymousName) {
  938. return todo_.FinishAction(
  939. arena_->New<BindingPlaceholderValue>(&binding));
  940. } else {
  941. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  942. }
  943. }
  944. case PatternKind::GenericBinding: {
  945. const auto& binding = cast<GenericBinding>(pattern);
  946. return todo_.FinishAction(arena_->New<VariableType>(&binding));
  947. }
  948. case PatternKind::TuplePattern: {
  949. const auto& tuple = cast<TuplePattern>(pattern);
  950. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  951. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  952. // H}
  953. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  954. // H}
  955. return todo_.Spawn(
  956. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  957. } else {
  958. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  959. }
  960. }
  961. case PatternKind::AlternativePattern: {
  962. const auto& alternative = cast<AlternativePattern>(pattern);
  963. if (act.pos() == 0) {
  964. return todo_.Spawn(
  965. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  966. } else if (act.pos() == 1) {
  967. return todo_.Spawn(
  968. std::make_unique<PatternAction>(&alternative.arguments()));
  969. } else {
  970. CHECK(act.pos() == 2);
  971. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  972. return todo_.FinishAction(arena_->New<AlternativeValue>(
  973. alternative.alternative_name(), choice_type.name(),
  974. act.results()[1]));
  975. }
  976. }
  977. case PatternKind::ExpressionPattern:
  978. if (act.pos() == 0) {
  979. return todo_.Spawn(std::make_unique<ExpressionAction>(
  980. &cast<ExpressionPattern>(pattern).expression()));
  981. } else {
  982. return todo_.FinishAction(act.results()[0]);
  983. }
  984. case PatternKind::VarPattern:
  985. if (act.pos() == 0) {
  986. return todo_.Spawn(std::make_unique<PatternAction>(
  987. &cast<VarPattern>(pattern).pattern()));
  988. } else {
  989. return todo_.FinishAction(act.results()[0]);
  990. }
  991. }
  992. }
  993. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  994. Action& act = todo_.CurrentAction();
  995. const Statement& stmt = cast<StatementAction>(act).statement();
  996. if (trace_stream_) {
  997. **trace_stream_ << "--- step stmt ";
  998. stmt.PrintDepth(1, **trace_stream_);
  999. **trace_stream_ << " (" << stmt.source_loc() << ") --->\n";
  1000. }
  1001. switch (stmt.kind()) {
  1002. case StatementKind::Match: {
  1003. const auto& match_stmt = cast<Match>(stmt);
  1004. if (act.pos() == 0) {
  1005. // { { (match (e) ...) :: C, E, F} :: S, H}
  1006. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  1007. act.StartScope(RuntimeScope(&heap_));
  1008. return todo_.Spawn(
  1009. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  1010. } else {
  1011. int clause_num = act.pos() - 1;
  1012. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  1013. return todo_.FinishAction();
  1014. }
  1015. auto c = match_stmt.clauses()[clause_num];
  1016. RuntimeScope matches(&heap_);
  1017. BindingMap generic_args;
  1018. ASSIGN_OR_RETURN(Nonnull<const Value*> val,
  1019. Convert(act.results()[0], &c.pattern().static_type(),
  1020. stmt.source_loc()));
  1021. if (PatternMatch(&c.pattern().value(), val, stmt.source_loc(), &matches,
  1022. generic_args, trace_stream_)) {
  1023. // Ensure we don't process any more clauses.
  1024. act.set_pos(match_stmt.clauses().size() + 1);
  1025. todo_.MergeScope(std::move(matches));
  1026. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  1027. } else {
  1028. return todo_.RunAgain();
  1029. }
  1030. }
  1031. }
  1032. case StatementKind::While:
  1033. if (act.pos() % 2 == 0) {
  1034. // { { (while (e) s) :: C, E, F} :: S, H}
  1035. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  1036. act.Clear();
  1037. return todo_.Spawn(
  1038. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  1039. } else {
  1040. ASSIGN_OR_RETURN(Nonnull<const Value*> condition,
  1041. Convert(act.results().back(), arena_->New<BoolType>(),
  1042. stmt.source_loc()));
  1043. if (cast<BoolValue>(*condition).value()) {
  1044. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1045. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1046. return todo_.Spawn(
  1047. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  1048. } else {
  1049. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1050. // -> { { C, E, F } :: S, H}
  1051. return todo_.FinishAction();
  1052. }
  1053. }
  1054. case StatementKind::Break: {
  1055. CHECK(act.pos() == 0);
  1056. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1057. // -> { { C, E', F} :: S, H}
  1058. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  1059. }
  1060. case StatementKind::Continue: {
  1061. CHECK(act.pos() == 0);
  1062. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1063. // -> { { (while (e) s) :: C, E', F} :: S, H}
  1064. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  1065. }
  1066. case StatementKind::Block: {
  1067. const auto& block = cast<Block>(stmt);
  1068. if (act.pos() >= static_cast<int>(block.statements().size())) {
  1069. // If the position is past the end of the block, end processing. Note
  1070. // that empty blocks immediately end.
  1071. return todo_.FinishAction();
  1072. }
  1073. // Initialize a scope when starting a block.
  1074. if (act.pos() == 0) {
  1075. act.StartScope(RuntimeScope(&heap_));
  1076. }
  1077. // Process the next statement in the block. The position will be
  1078. // incremented as part of Spawn.
  1079. return todo_.Spawn(
  1080. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  1081. }
  1082. case StatementKind::VariableDefinition: {
  1083. const auto& definition = cast<VariableDefinition>(stmt);
  1084. if (act.pos() == 0) {
  1085. // { {(var x = e) :: C, E, F} :: S, H}
  1086. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  1087. return todo_.Spawn(
  1088. std::make_unique<ExpressionAction>(&definition.init()));
  1089. } else {
  1090. // { { v :: (x = []) :: C, E, F} :: S, H}
  1091. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1092. ASSIGN_OR_RETURN(
  1093. Nonnull<const Value*> v,
  1094. Convert(act.results()[0], &definition.pattern().static_type(),
  1095. stmt.source_loc()));
  1096. Nonnull<const Value*> p =
  1097. &cast<VariableDefinition>(stmt).pattern().value();
  1098. RuntimeScope matches(&heap_);
  1099. BindingMap generic_args;
  1100. CHECK(PatternMatch(p, v, stmt.source_loc(), &matches, generic_args,
  1101. trace_stream_))
  1102. << stmt.source_loc()
  1103. << ": internal error in variable definition, match failed";
  1104. todo_.MergeScope(std::move(matches));
  1105. return todo_.FinishAction();
  1106. }
  1107. }
  1108. case StatementKind::ExpressionStatement:
  1109. if (act.pos() == 0) {
  1110. // { {e :: C, E, F} :: S, H}
  1111. // -> { {e :: C, E, F} :: S, H}
  1112. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1113. &cast<ExpressionStatement>(stmt).expression()));
  1114. } else {
  1115. return todo_.FinishAction();
  1116. }
  1117. case StatementKind::Assign: {
  1118. const auto& assign = cast<Assign>(stmt);
  1119. if (act.pos() == 0) {
  1120. // { {(lv = e) :: C, E, F} :: S, H}
  1121. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1122. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  1123. } else if (act.pos() == 1) {
  1124. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1125. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1126. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  1127. } else {
  1128. // { { v :: (a = []) :: C, E, F} :: S, H}
  1129. // -> { { C, E, F} :: S, H(a := v)}
  1130. const auto& lval = cast<LValue>(*act.results()[0]);
  1131. ASSIGN_OR_RETURN(Nonnull<const Value*> rval,
  1132. Convert(act.results()[1], &assign.lhs().static_type(),
  1133. stmt.source_loc()));
  1134. RETURN_IF_ERROR(heap_.Write(lval.address(), rval, stmt.source_loc()));
  1135. return todo_.FinishAction();
  1136. }
  1137. }
  1138. case StatementKind::If:
  1139. if (act.pos() == 0) {
  1140. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1141. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1142. return todo_.Spawn(
  1143. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  1144. } else if (act.pos() == 1) {
  1145. ASSIGN_OR_RETURN(Nonnull<const Value*> condition,
  1146. Convert(act.results()[0], arena_->New<BoolType>(),
  1147. stmt.source_loc()));
  1148. if (cast<BoolValue>(*condition).value()) {
  1149. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1150. // S, H}
  1151. // -> { { then_stmt :: C, E, F } :: S, H}
  1152. return todo_.Spawn(
  1153. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  1154. } else if (cast<If>(stmt).else_block()) {
  1155. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1156. // S, H}
  1157. // -> { { else_stmt :: C, E, F } :: S, H}
  1158. return todo_.Spawn(
  1159. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  1160. } else {
  1161. return todo_.FinishAction();
  1162. }
  1163. } else {
  1164. return todo_.FinishAction();
  1165. }
  1166. case StatementKind::Return:
  1167. if (act.pos() == 0) {
  1168. // { {return e :: C, E, F} :: S, H}
  1169. // -> { {e :: return [] :: C, E, F} :: S, H}
  1170. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1171. &cast<Return>(stmt).expression()));
  1172. } else {
  1173. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1174. // -> { {v :: C', E', F'} :: S, H}
  1175. const FunctionDeclaration& function = cast<Return>(stmt).function();
  1176. ASSIGN_OR_RETURN(
  1177. Nonnull<const Value*> return_value,
  1178. Convert(act.results()[0], &function.return_term().static_type(),
  1179. stmt.source_loc()));
  1180. return todo_.UnwindPast(*function.body(), return_value);
  1181. }
  1182. case StatementKind::Continuation: {
  1183. CHECK(act.pos() == 0);
  1184. const auto& continuation = cast<Continuation>(stmt);
  1185. // Create a continuation object by creating a frame similar the
  1186. // way one is created in a function call.
  1187. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  1188. stack_fragments_.push_back(fragment);
  1189. todo_.InitializeFragment(*fragment, &continuation.body());
  1190. // Bind the continuation object to the continuation variable
  1191. todo_.Initialize(&cast<Continuation>(stmt),
  1192. arena_->New<ContinuationValue>(fragment));
  1193. return todo_.FinishAction();
  1194. }
  1195. case StatementKind::Run: {
  1196. auto& run = cast<Run>(stmt);
  1197. if (act.pos() == 0) {
  1198. // Evaluate the argument of the run statement.
  1199. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  1200. } else if (act.pos() == 1) {
  1201. // Push the continuation onto the current stack.
  1202. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  1203. } else {
  1204. return todo_.FinishAction();
  1205. }
  1206. }
  1207. case StatementKind::Await:
  1208. CHECK(act.pos() == 0);
  1209. return todo_.Suspend();
  1210. }
  1211. }
  1212. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  1213. Action& act = todo_.CurrentAction();
  1214. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  1215. if (trace_stream_) {
  1216. **trace_stream_ << "--- step declaration (" << decl.source_loc()
  1217. << ") --->\n";
  1218. }
  1219. switch (decl.kind()) {
  1220. case DeclarationKind::VariableDeclaration: {
  1221. const auto& var_decl = cast<VariableDeclaration>(decl);
  1222. if (var_decl.has_initializer()) {
  1223. if (act.pos() == 0) {
  1224. return todo_.Spawn(
  1225. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  1226. } else {
  1227. todo_.Initialize(&var_decl.binding(), act.results()[0]);
  1228. return todo_.FinishAction();
  1229. }
  1230. } else {
  1231. return todo_.FinishAction();
  1232. }
  1233. }
  1234. case DeclarationKind::FunctionDeclaration:
  1235. case DeclarationKind::ClassDeclaration:
  1236. case DeclarationKind::ChoiceDeclaration:
  1237. case DeclarationKind::InterfaceDeclaration:
  1238. case DeclarationKind::ImplDeclaration:
  1239. // These declarations have no run-time effects.
  1240. return todo_.FinishAction();
  1241. }
  1242. }
  1243. // State transition.
  1244. auto Interpreter::Step() -> ErrorOr<Success> {
  1245. Action& act = todo_.CurrentAction();
  1246. switch (act.kind()) {
  1247. case Action::Kind::LValAction:
  1248. RETURN_IF_ERROR(StepLvalue());
  1249. break;
  1250. case Action::Kind::ExpressionAction:
  1251. RETURN_IF_ERROR(StepExp());
  1252. break;
  1253. case Action::Kind::PatternAction:
  1254. RETURN_IF_ERROR(StepPattern());
  1255. break;
  1256. case Action::Kind::StatementAction:
  1257. RETURN_IF_ERROR(StepStmt());
  1258. break;
  1259. case Action::Kind::DeclarationAction:
  1260. RETURN_IF_ERROR(StepDeclaration());
  1261. break;
  1262. case Action::Kind::ScopeAction:
  1263. FATAL() << "ScopeAction escaped ActionStack";
  1264. } // switch
  1265. return Success();
  1266. }
  1267. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  1268. -> ErrorOr<Success> {
  1269. if (trace_stream_) {
  1270. PrintState(**trace_stream_);
  1271. }
  1272. todo_.Start(std::move(action));
  1273. while (!todo_.IsEmpty()) {
  1274. RETURN_IF_ERROR(Step());
  1275. if (trace_stream_) {
  1276. PrintState(**trace_stream_);
  1277. }
  1278. }
  1279. return Success();
  1280. }
  1281. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena,
  1282. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1283. -> ErrorOr<int> {
  1284. Interpreter interpreter(Phase::RunTime, arena, trace_stream);
  1285. if (trace_stream) {
  1286. **trace_stream << "********** initializing globals **********\n";
  1287. }
  1288. for (Nonnull<Declaration*> declaration : ast.declarations) {
  1289. RETURN_IF_ERROR(interpreter.RunAllSteps(
  1290. std::make_unique<DeclarationAction>(declaration)));
  1291. }
  1292. if (trace_stream) {
  1293. **trace_stream << "********** calling main function **********\n";
  1294. }
  1295. RETURN_IF_ERROR(interpreter.RunAllSteps(
  1296. std::make_unique<ExpressionAction>(*ast.main_call)));
  1297. return cast<IntValue>(*interpreter.result()).value();
  1298. }
  1299. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena,
  1300. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1301. -> ErrorOr<Nonnull<const Value*>> {
  1302. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1303. RETURN_IF_ERROR(
  1304. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e)));
  1305. return interpreter.result();
  1306. }
  1307. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena,
  1308. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1309. -> ErrorOr<Nonnull<const Value*>> {
  1310. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1311. RETURN_IF_ERROR(interpreter.RunAllSteps(std::make_unique<PatternAction>(p)));
  1312. return interpreter.result();
  1313. }
  1314. } // namespace Carbon