interpreter.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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 <list>
  7. #include <map>
  8. #include <optional>
  9. #include <utility>
  10. #include <vector>
  11. #include "common/check.h"
  12. #include "executable_semantics/ast/expression.h"
  13. #include "executable_semantics/ast/function_definition.h"
  14. #include "executable_semantics/common/arena.h"
  15. #include "executable_semantics/common/error.h"
  16. #include "executable_semantics/common/tracing_flag.h"
  17. #include "executable_semantics/interpreter/action.h"
  18. #include "executable_semantics/interpreter/frame.h"
  19. #include "executable_semantics/interpreter/stack.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/Support/Casting.h"
  22. using llvm::cast;
  23. namespace Carbon {
  24. State* state = nullptr;
  25. void Step();
  26. //
  27. // Auxiliary Functions
  28. //
  29. void PrintEnv(Env values, llvm::raw_ostream& out) {
  30. llvm::ListSeparator sep;
  31. for (const auto& [name, address] : values) {
  32. out << sep << name << ": ";
  33. state->heap.PrintAddress(address, out);
  34. }
  35. }
  36. //
  37. // State Operations
  38. //
  39. void PrintStack(const Stack<Ptr<Frame>>& ls, llvm::raw_ostream& out) {
  40. llvm::ListSeparator sep(" :: ");
  41. for (const auto& frame : ls) {
  42. out << sep << *frame;
  43. }
  44. }
  45. auto CurrentEnv(State* state) -> Env {
  46. Ptr<Frame> frame = state->stack.Top();
  47. return frame->scopes.Top()->values;
  48. }
  49. // Returns the given name from the environment, printing an error if not found.
  50. static auto GetFromEnv(int line_num, const std::string& name) -> Address {
  51. std::optional<Address> pointer = CurrentEnv(state).Get(name);
  52. if (!pointer) {
  53. FATAL_RUNTIME_ERROR(line_num) << "could not find `" << name << "`";
  54. }
  55. return *pointer;
  56. }
  57. void PrintState(llvm::raw_ostream& out) {
  58. out << "{\nstack: ";
  59. PrintStack(state->stack, out);
  60. out << "\nheap: " << state->heap;
  61. if (!state->stack.IsEmpty() && !state->stack.Top()->scopes.IsEmpty()) {
  62. out << "\nvalues: ";
  63. PrintEnv(CurrentEnv(state), out);
  64. }
  65. out << "\n}\n";
  66. }
  67. auto EvalPrim(Operator op, const std::vector<const Value*>& args, int line_num)
  68. -> const Value* {
  69. switch (op) {
  70. case Operator::Neg:
  71. return global_arena->RawNew<IntValue>(-cast<IntValue>(*args[0]).Val());
  72. case Operator::Add:
  73. return global_arena->RawNew<IntValue>(cast<IntValue>(*args[0]).Val() +
  74. cast<IntValue>(*args[1]).Val());
  75. case Operator::Sub:
  76. return global_arena->RawNew<IntValue>(cast<IntValue>(*args[0]).Val() -
  77. cast<IntValue>(*args[1]).Val());
  78. case Operator::Mul:
  79. return global_arena->RawNew<IntValue>(cast<IntValue>(*args[0]).Val() *
  80. cast<IntValue>(*args[1]).Val());
  81. case Operator::Not:
  82. return global_arena->RawNew<BoolValue>(!cast<BoolValue>(*args[0]).Val());
  83. case Operator::And:
  84. return global_arena->RawNew<BoolValue>(cast<BoolValue>(*args[0]).Val() &&
  85. cast<BoolValue>(*args[1]).Val());
  86. case Operator::Or:
  87. return global_arena->RawNew<BoolValue>(cast<BoolValue>(*args[0]).Val() ||
  88. cast<BoolValue>(*args[1]).Val());
  89. case Operator::Eq:
  90. return global_arena->RawNew<BoolValue>(
  91. ValueEqual(args[0], args[1], line_num));
  92. case Operator::Ptr:
  93. return global_arena->RawNew<PointerType>(args[0]);
  94. case Operator::Deref:
  95. FATAL() << "dereference not implemented yet";
  96. }
  97. }
  98. // Globally-defined entities, such as functions, structs, choices.
  99. static Env globals;
  100. void InitEnv(const Declaration& d, Env* env) {
  101. switch (d.Tag()) {
  102. case Declaration::Kind::FunctionDeclaration: {
  103. const FunctionDefinition& func_def =
  104. cast<FunctionDeclaration>(d).Definition();
  105. Env new_env = *env;
  106. // Bring the deduced parameters into scope.
  107. for (const auto& deduced : func_def.deduced_parameters) {
  108. Address a = state->heap.AllocateValue(
  109. global_arena->RawNew<VariableType>(deduced.name));
  110. new_env.Set(deduced.name, a);
  111. }
  112. auto pt = InterpPattern(new_env, func_def.param_pattern);
  113. auto f =
  114. global_arena->RawNew<FunctionValue>(func_def.name, pt, func_def.body);
  115. Address a = state->heap.AllocateValue(f);
  116. env->Set(func_def.name, a);
  117. break;
  118. }
  119. case Declaration::Kind::ClassDeclaration: {
  120. const ClassDefinition& class_def = cast<ClassDeclaration>(d).Definition();
  121. VarValues fields;
  122. VarValues methods;
  123. for (const Member* m : class_def.members) {
  124. switch (m->Tag()) {
  125. case Member::Kind::FieldMember: {
  126. const BindingPattern* binding = cast<FieldMember>(*m).Binding();
  127. const Expression* type_expression =
  128. cast<ExpressionPattern>(binding->Type())->Expression();
  129. auto type = InterpExp(Env(), type_expression);
  130. fields.push_back(make_pair(*binding->Name(), type));
  131. break;
  132. }
  133. }
  134. }
  135. auto st = global_arena->RawNew<ClassType>(
  136. class_def.name, std::move(fields), std::move(methods));
  137. auto a = state->heap.AllocateValue(st);
  138. env->Set(class_def.name, a);
  139. break;
  140. }
  141. case Declaration::Kind::ChoiceDeclaration: {
  142. const auto& choice = cast<ChoiceDeclaration>(d);
  143. VarValues alts;
  144. for (const auto& [name, signature] : choice.Alternatives()) {
  145. auto t = InterpExp(Env(), signature);
  146. alts.push_back(make_pair(name, t));
  147. }
  148. auto ct =
  149. global_arena->RawNew<ChoiceType>(choice.Name(), std::move(alts));
  150. auto a = state->heap.AllocateValue(ct);
  151. env->Set(choice.Name(), a);
  152. break;
  153. }
  154. case Declaration::Kind::VariableDeclaration: {
  155. const auto& var = cast<VariableDeclaration>(d);
  156. // Adds an entry in `globals` mapping the variable's name to the
  157. // result of evaluating the initializer.
  158. auto v = InterpExp(*env, var.Initializer());
  159. Address a = state->heap.AllocateValue(v);
  160. env->Set(*var.Binding()->Name(), a);
  161. break;
  162. }
  163. }
  164. }
  165. static void InitGlobals(const std::list<Ptr<const Declaration>>& fs) {
  166. for (const auto d : fs) {
  167. InitEnv(*d, &globals);
  168. }
  169. }
  170. // { S, H} -> { { C, E, F} :: S, H}
  171. // where C is the body of the function,
  172. // E is the environment (functions + parameters + locals)
  173. // F is the function
  174. void CallFunction(int line_num, std::vector<const Value*> operas,
  175. State* state) {
  176. switch (operas[0]->Tag()) {
  177. case Value::Kind::FunctionValue: {
  178. const auto& fn = cast<FunctionValue>(*operas[0]);
  179. // Bind arguments to parameters
  180. std::optional<Env> matches =
  181. PatternMatch(fn.Param(), operas[1], line_num);
  182. CHECK(matches) << "internal error in call_function, pattern match failed";
  183. // Create the new frame and push it on the stack
  184. Env values = globals;
  185. std::list<std::string> params;
  186. for (const auto& [name, value] : *matches) {
  187. values.Set(name, value);
  188. params.push_back(name);
  189. }
  190. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values, params));
  191. auto todo =
  192. Stack<Ptr<Action>>(global_arena->New<StatementAction>(fn.Body()));
  193. auto frame = global_arena->New<Frame>(fn.Name(), scopes, todo);
  194. state->stack.Push(frame);
  195. break;
  196. }
  197. case Value::Kind::ClassType: {
  198. const Value* arg = CopyVal(operas[1], line_num);
  199. const Value* sv = global_arena->RawNew<StructValue>(operas[0], arg);
  200. Ptr<Frame> frame = state->stack.Top();
  201. frame->todo.Push(global_arena->New<ValAction>(sv));
  202. break;
  203. }
  204. case Value::Kind::AlternativeConstructorValue: {
  205. const auto& alt = cast<AlternativeConstructorValue>(*operas[0]);
  206. const Value* arg = CopyVal(operas[1], line_num);
  207. const Value* av = global_arena->RawNew<AlternativeValue>(
  208. alt.AltName(), alt.ChoiceName(), arg);
  209. Ptr<Frame> frame = state->stack.Top();
  210. frame->todo.Push(global_arena->New<ValAction>(av));
  211. break;
  212. }
  213. default:
  214. FATAL_RUNTIME_ERROR(line_num)
  215. << "in call, expected a function, not " << *operas[0];
  216. }
  217. }
  218. void DeallocateScope(int line_num, Ptr<Scope> scope) {
  219. for (const auto& l : scope->locals) {
  220. std::optional<Address> a = scope->values.Get(l);
  221. CHECK(a);
  222. state->heap.Deallocate(*a);
  223. }
  224. }
  225. void DeallocateLocals(int line_num, Ptr<Frame> frame) {
  226. while (!frame->scopes.IsEmpty()) {
  227. DeallocateScope(line_num, frame->scopes.Top());
  228. frame->scopes.Pop();
  229. }
  230. }
  231. void CreateTuple(Ptr<Frame> frame, Ptr<Action> act, const Expression* exp) {
  232. // { { (v1,...,vn) :: C, E, F} :: S, H}
  233. // -> { { `(v1,...,vn) :: C, E, F} :: S, H}
  234. const auto& tup_lit = cast<TupleLiteral>(*exp);
  235. CHECK(act->Results().size() == tup_lit.Fields().size());
  236. std::vector<TupleElement> elements;
  237. for (size_t i = 0; i < act->Results().size(); ++i) {
  238. elements.push_back(
  239. {.name = tup_lit.Fields()[i].name, .value = act->Results()[i]});
  240. }
  241. const Value* tv = global_arena->RawNew<TupleValue>(std::move(elements));
  242. frame->todo.Pop(1);
  243. frame->todo.Push(global_arena->New<ValAction>(tv));
  244. }
  245. auto PatternMatch(const Value* p, const Value* v, int line_num)
  246. -> std::optional<Env> {
  247. switch (p->Tag()) {
  248. case Value::Kind::BindingPlaceholderValue: {
  249. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  250. Env values;
  251. if (placeholder.Name().has_value()) {
  252. Address a = state->heap.AllocateValue(CopyVal(v, line_num));
  253. values.Set(*placeholder.Name(), a);
  254. }
  255. return values;
  256. }
  257. case Value::Kind::TupleValue:
  258. switch (v->Tag()) {
  259. case Value::Kind::TupleValue: {
  260. const auto& p_tup = cast<TupleValue>(*p);
  261. const auto& v_tup = cast<TupleValue>(*v);
  262. if (p_tup.Elements().size() != v_tup.Elements().size()) {
  263. FATAL_PROGRAM_ERROR(line_num)
  264. << "arity mismatch in tuple pattern match:\n pattern: "
  265. << p_tup << "\n value: " << v_tup;
  266. }
  267. Env values;
  268. for (size_t i = 0; i < p_tup.Elements().size(); ++i) {
  269. if (p_tup.Elements()[i].name != v_tup.Elements()[i].name) {
  270. FATAL_PROGRAM_ERROR(line_num)
  271. << "Tuple field name '" << v_tup.Elements()[i].name
  272. << "' does not match pattern field name '"
  273. << p_tup.Elements()[i].name << "'";
  274. }
  275. std::optional<Env> matches = PatternMatch(
  276. p_tup.Elements()[i].value, v_tup.Elements()[i].value, line_num);
  277. if (!matches) {
  278. return std::nullopt;
  279. }
  280. for (const auto& [name, value] : *matches) {
  281. values.Set(name, value);
  282. }
  283. } // for
  284. return values;
  285. }
  286. default:
  287. FATAL() << "expected a tuple value in pattern, not " << *v;
  288. }
  289. case Value::Kind::AlternativeValue:
  290. switch (v->Tag()) {
  291. case Value::Kind::AlternativeValue: {
  292. const auto& p_alt = cast<AlternativeValue>(*p);
  293. const auto& v_alt = cast<AlternativeValue>(*v);
  294. if (p_alt.ChoiceName() != v_alt.ChoiceName() ||
  295. p_alt.AltName() != v_alt.AltName()) {
  296. return std::nullopt;
  297. }
  298. return PatternMatch(p_alt.Argument(), v_alt.Argument(), line_num);
  299. }
  300. default:
  301. FATAL() << "expected a choice alternative in pattern, not " << *v;
  302. }
  303. case Value::Kind::FunctionType:
  304. switch (v->Tag()) {
  305. case Value::Kind::FunctionType: {
  306. const auto& p_fn = cast<FunctionType>(*p);
  307. const auto& v_fn = cast<FunctionType>(*v);
  308. std::optional<Env> param_matches =
  309. PatternMatch(p_fn.Param(), v_fn.Param(), line_num);
  310. if (!param_matches) {
  311. return std::nullopt;
  312. }
  313. std::optional<Env> ret_matches =
  314. PatternMatch(p_fn.Ret(), v_fn.Ret(), line_num);
  315. if (!ret_matches) {
  316. return std::nullopt;
  317. }
  318. Env values = *param_matches;
  319. for (const auto& [name, value] : *ret_matches) {
  320. values.Set(name, value);
  321. }
  322. return values;
  323. }
  324. default:
  325. return std::nullopt;
  326. }
  327. case Value::Kind::AutoType:
  328. // `auto` matches any type, without binding any new names. We rely
  329. // on the typechecker to ensure that `v` is a type.
  330. return Env();
  331. default:
  332. if (ValueEqual(p, v, line_num)) {
  333. return Env();
  334. } else {
  335. return std::nullopt;
  336. }
  337. }
  338. }
  339. void PatternAssignment(const Value* pat, const Value* val, int line_num) {
  340. switch (pat->Tag()) {
  341. case Value::Kind::PointerValue:
  342. state->heap.Write(cast<PointerValue>(*pat).Val(), CopyVal(val, line_num),
  343. line_num);
  344. break;
  345. case Value::Kind::TupleValue: {
  346. switch (val->Tag()) {
  347. case Value::Kind::TupleValue: {
  348. const auto& pat_tup = cast<TupleValue>(*pat);
  349. const auto& val_tup = cast<TupleValue>(*val);
  350. if (pat_tup.Elements().size() != val_tup.Elements().size()) {
  351. FATAL_RUNTIME_ERROR(line_num)
  352. << "arity mismatch in tuple pattern assignment:\n pattern: "
  353. << pat_tup << "\n value: " << val_tup;
  354. }
  355. for (const TupleElement& pattern_element : pat_tup.Elements()) {
  356. const Value* value_field = val_tup.FindField(pattern_element.name);
  357. if (value_field == nullptr) {
  358. FATAL_RUNTIME_ERROR(line_num)
  359. << "field " << pattern_element.name << "not in " << *val;
  360. }
  361. PatternAssignment(pattern_element.value, value_field, line_num);
  362. }
  363. break;
  364. }
  365. default:
  366. FATAL() << "expected a tuple value on right-hand-side, not " << *val;
  367. }
  368. break;
  369. }
  370. case Value::Kind::AlternativeValue: {
  371. switch (val->Tag()) {
  372. case Value::Kind::AlternativeValue: {
  373. const auto& pat_alt = cast<AlternativeValue>(*pat);
  374. const auto& val_alt = cast<AlternativeValue>(*val);
  375. CHECK(val_alt.ChoiceName() == pat_alt.ChoiceName() &&
  376. val_alt.AltName() == pat_alt.AltName())
  377. << "internal error in pattern assignment";
  378. PatternAssignment(pat_alt.Argument(), val_alt.Argument(), line_num);
  379. break;
  380. }
  381. default:
  382. FATAL() << "expected an alternative in left-hand-side, not " << *val;
  383. }
  384. break;
  385. }
  386. default:
  387. CHECK(ValueEqual(pat, val, line_num))
  388. << "internal error in pattern assignment";
  389. }
  390. }
  391. // State transitions for lvalues.
  392. void StepLvalue() {
  393. Ptr<Frame> frame = state->stack.Top();
  394. Ptr<Action> act = frame->todo.Top();
  395. const Expression* exp = cast<LValAction>(*act).Exp();
  396. if (tracing_output) {
  397. llvm::outs() << "--- step lvalue " << *exp << " --->\n";
  398. }
  399. switch (exp->Tag()) {
  400. case Expression::Kind::IdentifierExpression: {
  401. // { {x :: C, E, F} :: S, H}
  402. // -> { {E(x) :: C, E, F} :: S, H}
  403. Address pointer = GetFromEnv(exp->LineNumber(),
  404. cast<IdentifierExpression>(*exp).Name());
  405. const Value* v = global_arena->RawNew<PointerValue>(pointer);
  406. frame->todo.Pop();
  407. frame->todo.Push(global_arena->New<ValAction>(v));
  408. break;
  409. }
  410. case Expression::Kind::FieldAccessExpression: {
  411. if (act->Pos() == 0) {
  412. // { {e.f :: C, E, F} :: S, H}
  413. // -> { e :: [].f :: C, E, F} :: S, H}
  414. frame->todo.Push(global_arena->New<LValAction>(
  415. cast<FieldAccessExpression>(*exp).Aggregate()));
  416. act->IncrementPos();
  417. } else {
  418. // { v :: [].f :: C, E, F} :: S, H}
  419. // -> { { &v.f :: C, E, F} :: S, H }
  420. Address aggregate = cast<PointerValue>(*act->Results()[0]).Val();
  421. Address field = aggregate.SubobjectAddress(
  422. cast<FieldAccessExpression>(*exp).Field());
  423. frame->todo.Pop(1);
  424. frame->todo.Push(global_arena->New<ValAction>(
  425. global_arena->RawNew<PointerValue>(field)));
  426. }
  427. break;
  428. }
  429. case Expression::Kind::IndexExpression: {
  430. if (act->Pos() == 0) {
  431. // { {e[i] :: C, E, F} :: S, H}
  432. // -> { e :: [][i] :: C, E, F} :: S, H}
  433. frame->todo.Push(global_arena->New<LValAction>(
  434. cast<IndexExpression>(*exp).Aggregate()));
  435. act->IncrementPos();
  436. } else if (act->Pos() == 1) {
  437. frame->todo.Push(global_arena->New<ExpressionAction>(
  438. cast<IndexExpression>(*exp).Offset()));
  439. act->IncrementPos();
  440. } else if (act->Pos() == 2) {
  441. // { v :: [][i] :: C, E, F} :: S, H}
  442. // -> { { &v[i] :: C, E, F} :: S, H }
  443. Address aggregate = cast<PointerValue>(*act->Results()[0]).Val();
  444. std::string f =
  445. std::to_string(cast<IntValue>(*act->Results()[1]).Val());
  446. Address field = aggregate.SubobjectAddress(f);
  447. frame->todo.Pop(1);
  448. frame->todo.Push(global_arena->New<ValAction>(
  449. global_arena->RawNew<PointerValue>(field)));
  450. }
  451. break;
  452. }
  453. case Expression::Kind::TupleLiteral: {
  454. if (act->Pos() == 0) {
  455. // { {(f1=e1,...) :: C, E, F} :: S, H}
  456. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  457. const Expression* e1 = cast<TupleLiteral>(*exp).Fields()[0].expression;
  458. frame->todo.Push(global_arena->New<LValAction>(e1));
  459. act->IncrementPos();
  460. } else if (act->Pos() !=
  461. static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
  462. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  463. // H}
  464. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  465. // H}
  466. const Expression* elt =
  467. cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
  468. frame->todo.Push(global_arena->New<LValAction>(elt));
  469. act->IncrementPos();
  470. } else {
  471. CreateTuple(frame, act, exp);
  472. }
  473. break;
  474. }
  475. case Expression::Kind::IntLiteral:
  476. case Expression::Kind::BoolLiteral:
  477. case Expression::Kind::CallExpression:
  478. case Expression::Kind::PrimitiveOperatorExpression:
  479. case Expression::Kind::IntTypeLiteral:
  480. case Expression::Kind::BoolTypeLiteral:
  481. case Expression::Kind::TypeTypeLiteral:
  482. case Expression::Kind::FunctionTypeLiteral:
  483. case Expression::Kind::ContinuationTypeLiteral:
  484. case Expression::Kind::StringLiteral:
  485. case Expression::Kind::StringTypeLiteral:
  486. case Expression::Kind::IntrinsicExpression:
  487. FATAL_RUNTIME_ERROR_NO_LINE()
  488. << "Can't treat expression as lvalue: " << *exp;
  489. }
  490. }
  491. // State transitions for expressions.
  492. void StepExp() {
  493. Ptr<Frame> frame = state->stack.Top();
  494. Ptr<Action> act = frame->todo.Top();
  495. const Expression* exp = cast<ExpressionAction>(*act).Exp();
  496. if (tracing_output) {
  497. llvm::outs() << "--- step exp " << *exp << " --->\n";
  498. }
  499. switch (exp->Tag()) {
  500. case Expression::Kind::IndexExpression: {
  501. if (act->Pos() == 0) {
  502. // { { e[i] :: C, E, F} :: S, H}
  503. // -> { { e :: [][i] :: C, E, F} :: S, H}
  504. frame->todo.Push(global_arena->New<ExpressionAction>(
  505. cast<IndexExpression>(*exp).Aggregate()));
  506. act->IncrementPos();
  507. } else if (act->Pos() == 1) {
  508. frame->todo.Push(global_arena->New<ExpressionAction>(
  509. cast<IndexExpression>(*exp).Offset()));
  510. act->IncrementPos();
  511. } else if (act->Pos() == 2) {
  512. auto tuple = act->Results()[0];
  513. switch (tuple->Tag()) {
  514. case Value::Kind::TupleValue: {
  515. // { { v :: [][i] :: C, E, F} :: S, H}
  516. // -> { { v_i :: C, E, F} : S, H}
  517. std::string f =
  518. std::to_string(cast<IntValue>(*act->Results()[1]).Val());
  519. const Value* field = cast<TupleValue>(*tuple).FindField(f);
  520. if (field == nullptr) {
  521. FATAL_RUNTIME_ERROR_NO_LINE()
  522. << "field " << f << " not in " << *tuple;
  523. }
  524. frame->todo.Pop(1);
  525. frame->todo.Push(global_arena->New<ValAction>(field));
  526. break;
  527. }
  528. default:
  529. FATAL_RUNTIME_ERROR_NO_LINE()
  530. << "expected a tuple in field access, not " << *tuple;
  531. }
  532. }
  533. break;
  534. }
  535. case Expression::Kind::TupleLiteral: {
  536. if (act->Pos() == 0) {
  537. if (cast<TupleLiteral>(*exp).Fields().size() > 0) {
  538. // { {(f1=e1,...) :: C, E, F} :: S, H}
  539. // -> { {e1 :: (f1=[],...) :: C, E, F} :: S, H}
  540. const Expression* e1 =
  541. cast<TupleLiteral>(*exp).Fields()[0].expression;
  542. frame->todo.Push(global_arena->New<ExpressionAction>(e1));
  543. act->IncrementPos();
  544. } else {
  545. CreateTuple(frame, act, exp);
  546. }
  547. } else if (act->Pos() !=
  548. static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
  549. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  550. // H}
  551. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  552. // H}
  553. const Expression* elt =
  554. cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
  555. frame->todo.Push(global_arena->New<ExpressionAction>(elt));
  556. act->IncrementPos();
  557. } else {
  558. CreateTuple(frame, act, exp);
  559. }
  560. break;
  561. }
  562. case Expression::Kind::FieldAccessExpression: {
  563. const auto& access = cast<FieldAccessExpression>(*exp);
  564. if (act->Pos() == 0) {
  565. // { { e.f :: C, E, F} :: S, H}
  566. // -> { { e :: [].f :: C, E, F} :: S, H}
  567. frame->todo.Push(
  568. global_arena->New<ExpressionAction>(access.Aggregate()));
  569. act->IncrementPos();
  570. } else {
  571. // { { v :: [].f :: C, E, F} :: S, H}
  572. // -> { { v_f :: C, E, F} : S, H}
  573. const Value* element = act->Results()[0]->GetField(
  574. FieldPath(access.Field()), exp->LineNumber());
  575. frame->todo.Pop(1);
  576. frame->todo.Push(global_arena->New<ValAction>(element));
  577. }
  578. break;
  579. }
  580. case Expression::Kind::IdentifierExpression: {
  581. CHECK(act->Pos() == 0);
  582. const auto& ident = cast<IdentifierExpression>(*exp);
  583. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  584. Address pointer = GetFromEnv(exp->LineNumber(), ident.Name());
  585. const Value* pointee = state->heap.Read(pointer, exp->LineNumber());
  586. frame->todo.Pop(1);
  587. frame->todo.Push(global_arena->New<ValAction>(pointee));
  588. break;
  589. }
  590. case Expression::Kind::IntLiteral:
  591. CHECK(act->Pos() == 0);
  592. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  593. frame->todo.Pop(1);
  594. frame->todo.Push(global_arena->New<ValAction>(
  595. global_arena->RawNew<IntValue>(cast<IntLiteral>(*exp).Val())));
  596. break;
  597. case Expression::Kind::BoolLiteral:
  598. CHECK(act->Pos() == 0);
  599. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  600. frame->todo.Pop(1);
  601. frame->todo.Push(global_arena->New<ValAction>(
  602. global_arena->RawNew<BoolValue>(cast<BoolLiteral>(*exp).Val())));
  603. break;
  604. case Expression::Kind::PrimitiveOperatorExpression: {
  605. const auto& op = cast<PrimitiveOperatorExpression>(*exp);
  606. if (act->Pos() != static_cast<int>(op.Arguments().size())) {
  607. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  608. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  609. const Expression* arg = op.Arguments()[act->Pos()];
  610. frame->todo.Push(global_arena->New<ExpressionAction>(arg));
  611. act->IncrementPos();
  612. } else {
  613. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  614. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  615. const Value* v = EvalPrim(op.Op(), act->Results(), exp->LineNumber());
  616. frame->todo.Pop(1);
  617. frame->todo.Push(global_arena->New<ValAction>(v));
  618. }
  619. break;
  620. }
  621. case Expression::Kind::CallExpression:
  622. if (act->Pos() == 0) {
  623. // { {e1(e2) :: C, E, F} :: S, H}
  624. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  625. frame->todo.Push(global_arena->New<ExpressionAction>(
  626. cast<CallExpression>(*exp).Function()));
  627. act->IncrementPos();
  628. } else if (act->Pos() == 1) {
  629. // { { v :: [](e) :: C, E, F} :: S, H}
  630. // -> { { e :: v([]) :: C, E, F} :: S, H}
  631. frame->todo.Push(global_arena->New<ExpressionAction>(
  632. cast<CallExpression>(*exp).Argument()));
  633. act->IncrementPos();
  634. } else if (act->Pos() == 2) {
  635. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  636. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  637. frame->todo.Pop(1);
  638. CallFunction(exp->LineNumber(), act->Results(), state);
  639. } else {
  640. FATAL() << "in handle_value with Call pos " << act->Pos();
  641. }
  642. break;
  643. case Expression::Kind::IntrinsicExpression:
  644. CHECK(act->Pos() == 0);
  645. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  646. frame->todo.Pop(1);
  647. switch (cast<IntrinsicExpression>(*exp).Intrinsic()) {
  648. case IntrinsicExpression::IntrinsicKind::Print:
  649. Address pointer = GetFromEnv(exp->LineNumber(), "format_str");
  650. const Value* pointee = state->heap.Read(pointer, exp->LineNumber());
  651. CHECK(pointee->Tag() == Value::Kind::StringValue);
  652. // TODO: This could eventually use something like llvm::formatv.
  653. llvm::outs() << cast<StringValue>(*pointee).Val();
  654. frame->todo.Push(global_arena->New<ValAction>(&TupleValue::Empty()));
  655. break;
  656. }
  657. break;
  658. case Expression::Kind::IntTypeLiteral: {
  659. CHECK(act->Pos() == 0);
  660. const Value* v = global_arena->RawNew<IntType>();
  661. frame->todo.Pop(1);
  662. frame->todo.Push(global_arena->New<ValAction>(v));
  663. break;
  664. }
  665. case Expression::Kind::BoolTypeLiteral: {
  666. CHECK(act->Pos() == 0);
  667. const Value* v = global_arena->RawNew<BoolType>();
  668. frame->todo.Pop(1);
  669. frame->todo.Push(global_arena->New<ValAction>(v));
  670. break;
  671. }
  672. case Expression::Kind::TypeTypeLiteral: {
  673. CHECK(act->Pos() == 0);
  674. const Value* v = global_arena->RawNew<TypeType>();
  675. frame->todo.Pop(1);
  676. frame->todo.Push(global_arena->New<ValAction>(v));
  677. break;
  678. }
  679. case Expression::Kind::FunctionTypeLiteral: {
  680. if (act->Pos() == 0) {
  681. frame->todo.Push(global_arena->New<ExpressionAction>(
  682. cast<FunctionTypeLiteral>(*exp).Parameter()));
  683. act->IncrementPos();
  684. } else if (act->Pos() == 1) {
  685. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  686. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  687. frame->todo.Push(global_arena->New<ExpressionAction>(
  688. cast<FunctionTypeLiteral>(*exp).ReturnType()));
  689. act->IncrementPos();
  690. } else if (act->Pos() == 2) {
  691. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  692. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  693. const Value* v = global_arena->RawNew<FunctionType>(
  694. std::vector<GenericBinding>(), act->Results()[0],
  695. act->Results()[1]);
  696. frame->todo.Pop(1);
  697. frame->todo.Push(global_arena->New<ValAction>(v));
  698. }
  699. break;
  700. }
  701. case Expression::Kind::ContinuationTypeLiteral: {
  702. CHECK(act->Pos() == 0);
  703. const Value* v = global_arena->RawNew<ContinuationType>();
  704. frame->todo.Pop(1);
  705. frame->todo.Push(global_arena->New<ValAction>(v));
  706. break;
  707. }
  708. case Expression::Kind::StringLiteral:
  709. CHECK(act->Pos() == 0);
  710. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  711. frame->todo.Pop(1);
  712. frame->todo.Push(global_arena->New<ValAction>(
  713. global_arena->RawNew<StringValue>(cast<StringLiteral>(*exp).Val())));
  714. break;
  715. case Expression::Kind::StringTypeLiteral: {
  716. CHECK(act->Pos() == 0);
  717. const Value* v = global_arena->RawNew<StringType>();
  718. frame->todo.Pop(1);
  719. frame->todo.Push(global_arena->New<ValAction>(v));
  720. break;
  721. }
  722. } // switch (exp->Tag)
  723. }
  724. void StepPattern() {
  725. Ptr<Frame> frame = state->stack.Top();
  726. Ptr<Action> act = frame->todo.Top();
  727. const Pattern* pattern = cast<PatternAction>(*act).Pat();
  728. if (tracing_output) {
  729. llvm::outs() << "--- step pattern " << *pattern << " --->\n";
  730. }
  731. switch (pattern->Tag()) {
  732. case Pattern::Kind::AutoPattern: {
  733. CHECK(act->Pos() == 0);
  734. const Value* v = global_arena->RawNew<AutoType>();
  735. frame->todo.Pop(1);
  736. frame->todo.Push(global_arena->New<ValAction>(v));
  737. break;
  738. }
  739. case Pattern::Kind::BindingPattern: {
  740. const auto& binding = cast<BindingPattern>(*pattern);
  741. if (act->Pos() == 0) {
  742. frame->todo.Push(global_arena->New<PatternAction>(binding.Type()));
  743. act->IncrementPos();
  744. } else {
  745. auto v = global_arena->RawNew<BindingPlaceholderValue>(
  746. binding.Name(), act->Results()[0]);
  747. frame->todo.Pop(1);
  748. frame->todo.Push(global_arena->New<ValAction>(v));
  749. }
  750. break;
  751. }
  752. case Pattern::Kind::TuplePattern: {
  753. const auto& tuple = cast<TuplePattern>(*pattern);
  754. if (act->Pos() == 0) {
  755. if (tuple.Fields().empty()) {
  756. frame->todo.Pop(1);
  757. frame->todo.Push(global_arena->New<ValAction>(&TupleValue::Empty()));
  758. } else {
  759. const Pattern* p1 = tuple.Fields()[0].pattern;
  760. frame->todo.Push(global_arena->New<PatternAction>(p1));
  761. act->IncrementPos();
  762. }
  763. } else if (act->Pos() != static_cast<int>(tuple.Fields().size())) {
  764. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  765. // H}
  766. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  767. // H}
  768. const Pattern* elt = tuple.Fields()[act->Pos()].pattern;
  769. frame->todo.Push(global_arena->New<PatternAction>(elt));
  770. act->IncrementPos();
  771. } else {
  772. std::vector<TupleElement> elements;
  773. for (size_t i = 0; i < tuple.Fields().size(); ++i) {
  774. elements.push_back(
  775. {.name = tuple.Fields()[i].name, .value = act->Results()[i]});
  776. }
  777. const Value* tuple_value =
  778. global_arena->RawNew<TupleValue>(std::move(elements));
  779. frame->todo.Pop(1);
  780. frame->todo.Push(global_arena->New<ValAction>(tuple_value));
  781. }
  782. break;
  783. }
  784. case Pattern::Kind::AlternativePattern: {
  785. const auto& alternative = cast<AlternativePattern>(*pattern);
  786. if (act->Pos() == 0) {
  787. frame->todo.Push(
  788. global_arena->New<ExpressionAction>(alternative.ChoiceType()));
  789. act->IncrementPos();
  790. } else if (act->Pos() == 1) {
  791. frame->todo.Push(
  792. global_arena->New<PatternAction>(alternative.Arguments()));
  793. act->IncrementPos();
  794. } else {
  795. CHECK(act->Pos() == 2);
  796. const auto& choice_type = cast<ChoiceType>(*act->Results()[0]);
  797. frame->todo.Pop(1);
  798. frame->todo.Push(
  799. global_arena->New<ValAction>(global_arena->RawNew<AlternativeValue>(
  800. alternative.AlternativeName(), choice_type.Name(),
  801. act->Results()[1])));
  802. }
  803. break;
  804. }
  805. case Pattern::Kind::ExpressionPattern:
  806. frame->todo.Pop(1);
  807. frame->todo.Push(global_arena->New<ExpressionAction>(
  808. cast<ExpressionPattern>(pattern)->Expression()));
  809. break;
  810. }
  811. }
  812. auto IsWhileAct(Ptr<Action> act) -> bool {
  813. switch (act->Tag()) {
  814. case Action::Kind::StatementAction:
  815. switch (cast<StatementAction>(*act).Stmt()->Tag()) {
  816. case Statement::Kind::While:
  817. return true;
  818. default:
  819. return false;
  820. }
  821. default:
  822. return false;
  823. }
  824. }
  825. auto IsBlockAct(Ptr<Action> act) -> bool {
  826. switch (act->Tag()) {
  827. case Action::Kind::StatementAction:
  828. switch (cast<StatementAction>(*act).Stmt()->Tag()) {
  829. case Statement::Kind::Block:
  830. return true;
  831. default:
  832. return false;
  833. }
  834. default:
  835. return false;
  836. }
  837. }
  838. // State transitions for statements.
  839. void StepStmt() {
  840. Ptr<Frame> frame = state->stack.Top();
  841. Ptr<Action> act = frame->todo.Top();
  842. const Statement* stmt = cast<StatementAction>(*act).Stmt();
  843. CHECK(stmt != nullptr) << "null statement!";
  844. if (tracing_output) {
  845. llvm::outs() << "--- step stmt ";
  846. stmt->PrintDepth(1, llvm::outs());
  847. llvm::outs() << " --->\n";
  848. }
  849. switch (stmt->Tag()) {
  850. case Statement::Kind::Match:
  851. if (act->Pos() == 0) {
  852. // { { (match (e) ...) :: C, E, F} :: S, H}
  853. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  854. frame->todo.Push(
  855. global_arena->New<ExpressionAction>(cast<Match>(*stmt).Exp()));
  856. act->IncrementPos();
  857. } else {
  858. // Regarding act->Pos():
  859. // * odd: start interpreting the pattern of a clause
  860. // * even: finished interpreting the pattern, now try to match
  861. //
  862. // Regarding act->Results():
  863. // * 0: the value that we're matching
  864. // * 1: the pattern for clause 0
  865. // * 2: the pattern for clause 1
  866. // * ...
  867. auto clause_num = (act->Pos() - 1) / 2;
  868. if (clause_num >=
  869. static_cast<int>(cast<Match>(*stmt).Clauses()->size())) {
  870. frame->todo.Pop(1);
  871. break;
  872. }
  873. auto c = cast<Match>(*stmt).Clauses()->begin();
  874. std::advance(c, clause_num);
  875. if (act->Pos() % 2 == 1) {
  876. // start interpreting the pattern of the clause
  877. // { {v :: (match ([]) ...) :: C, E, F} :: S, H}
  878. // -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
  879. frame->todo.Push(global_arena->New<PatternAction>(c->first));
  880. act->IncrementPos();
  881. } else { // try to match
  882. auto v = act->Results()[0];
  883. auto pat = act->Results()[clause_num + 1];
  884. std::optional<Env> matches = PatternMatch(pat, v, stmt->LineNumber());
  885. if (matches) { // we have a match, start the body
  886. Env values = CurrentEnv(state);
  887. std::list<std::string> vars;
  888. for (const auto& [name, value] : *matches) {
  889. values.Set(name, value);
  890. vars.push_back(name);
  891. }
  892. frame->scopes.Push(global_arena->New<Scope>(values, vars));
  893. const Statement* body_block =
  894. global_arena->RawNew<Block>(stmt->LineNumber(), c->second);
  895. auto body_act = global_arena->New<StatementAction>(body_block);
  896. body_act->IncrementPos();
  897. frame->todo.Pop(1);
  898. frame->todo.Push(body_act);
  899. frame->todo.Push(global_arena->New<StatementAction>(c->second));
  900. } else {
  901. // this case did not match, moving on
  902. act->IncrementPos();
  903. clause_num = (act->Pos() - 1) / 2;
  904. if (clause_num ==
  905. static_cast<int>(cast<Match>(*stmt).Clauses()->size())) {
  906. frame->todo.Pop(1);
  907. }
  908. }
  909. }
  910. }
  911. break;
  912. case Statement::Kind::While:
  913. if (act->Pos() == 0) {
  914. // { { (while (e) s) :: C, E, F} :: S, H}
  915. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  916. frame->todo.Push(
  917. global_arena->New<ExpressionAction>(cast<While>(*stmt).Cond()));
  918. act->IncrementPos();
  919. } else if (cast<BoolValue>(*act->Results()[0]).Val()) {
  920. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  921. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  922. frame->todo.Top()->Clear();
  923. frame->todo.Push(
  924. global_arena->New<StatementAction>(cast<While>(*stmt).Body()));
  925. } else {
  926. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  927. // -> { { C, E, F } :: S, H}
  928. frame->todo.Top()->Clear();
  929. frame->todo.Pop(1);
  930. }
  931. break;
  932. case Statement::Kind::Break:
  933. CHECK(act->Pos() == 0);
  934. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  935. // -> { { C, E', F} :: S, H}
  936. frame->todo.Pop(1);
  937. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  938. if (IsBlockAct(frame->todo.Top())) {
  939. DeallocateScope(stmt->LineNumber(), frame->scopes.Top());
  940. frame->scopes.Pop(1);
  941. }
  942. frame->todo.Pop(1);
  943. }
  944. frame->todo.Pop(1);
  945. break;
  946. case Statement::Kind::Continue:
  947. CHECK(act->Pos() == 0);
  948. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  949. // -> { { (while (e) s) :: C, E', F} :: S, H}
  950. frame->todo.Pop(1);
  951. while (!frame->todo.IsEmpty() && !IsWhileAct(frame->todo.Top())) {
  952. if (IsBlockAct(frame->todo.Top())) {
  953. DeallocateScope(stmt->LineNumber(), frame->scopes.Top());
  954. frame->scopes.Pop(1);
  955. }
  956. frame->todo.Pop(1);
  957. }
  958. break;
  959. case Statement::Kind::Block: {
  960. if (act->Pos() == 0) {
  961. if (cast<Block>(*stmt).Stmt()) {
  962. frame->scopes.Push(global_arena->New<Scope>(CurrentEnv(state)));
  963. frame->todo.Push(
  964. global_arena->New<StatementAction>(cast<Block>(*stmt).Stmt()));
  965. act->IncrementPos();
  966. act->IncrementPos();
  967. } else {
  968. frame->todo.Pop();
  969. }
  970. } else {
  971. Ptr<Scope> scope = frame->scopes.Top();
  972. DeallocateScope(stmt->LineNumber(), scope);
  973. frame->scopes.Pop(1);
  974. frame->todo.Pop(1);
  975. }
  976. break;
  977. }
  978. case Statement::Kind::VariableDefinition:
  979. if (act->Pos() == 0) {
  980. // { {(var x = e) :: C, E, F} :: S, H}
  981. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  982. frame->todo.Push(global_arena->New<ExpressionAction>(
  983. cast<VariableDefinition>(*stmt).Init()));
  984. act->IncrementPos();
  985. } else if (act->Pos() == 1) {
  986. frame->todo.Push(global_arena->New<PatternAction>(
  987. cast<VariableDefinition>(*stmt).Pat()));
  988. act->IncrementPos();
  989. } else if (act->Pos() == 2) {
  990. // { { v :: (x = []) :: C, E, F} :: S, H}
  991. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  992. const Value* v = act->Results()[0];
  993. const Value* p = act->Results()[1];
  994. std::optional<Env> matches = PatternMatch(p, v, stmt->LineNumber());
  995. CHECK(matches)
  996. << stmt->LineNumber()
  997. << ": internal error in variable definition, match failed";
  998. for (const auto& [name, value] : *matches) {
  999. frame->scopes.Top()->values.Set(name, value);
  1000. frame->scopes.Top()->locals.push_back(name);
  1001. }
  1002. frame->todo.Pop(1);
  1003. }
  1004. break;
  1005. case Statement::Kind::ExpressionStatement:
  1006. if (act->Pos() == 0) {
  1007. // { {e :: C, E, F} :: S, H}
  1008. // -> { {e :: C, E, F} :: S, H}
  1009. frame->todo.Push(global_arena->New<ExpressionAction>(
  1010. cast<ExpressionStatement>(*stmt).Exp()));
  1011. act->IncrementPos();
  1012. } else {
  1013. frame->todo.Pop(1);
  1014. }
  1015. break;
  1016. case Statement::Kind::Assign:
  1017. if (act->Pos() == 0) {
  1018. // { {(lv = e) :: C, E, F} :: S, H}
  1019. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1020. frame->todo.Push(
  1021. global_arena->New<LValAction>(cast<Assign>(*stmt).Lhs()));
  1022. act->IncrementPos();
  1023. } else if (act->Pos() == 1) {
  1024. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1025. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1026. frame->todo.Push(
  1027. global_arena->New<ExpressionAction>(cast<Assign>(*stmt).Rhs()));
  1028. act->IncrementPos();
  1029. } else if (act->Pos() == 2) {
  1030. // { { v :: (a = []) :: C, E, F} :: S, H}
  1031. // -> { { C, E, F} :: S, H(a := v)}
  1032. auto pat = act->Results()[0];
  1033. auto val = act->Results()[1];
  1034. PatternAssignment(pat, val, stmt->LineNumber());
  1035. frame->todo.Pop(1);
  1036. }
  1037. break;
  1038. case Statement::Kind::If:
  1039. if (act->Pos() == 0) {
  1040. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1041. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1042. frame->todo.Push(
  1043. global_arena->New<ExpressionAction>(cast<If>(*stmt).Cond()));
  1044. act->IncrementPos();
  1045. } else if (cast<BoolValue>(*act->Results()[0]).Val()) {
  1046. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1047. // S, H}
  1048. // -> { { then_stmt :: C, E, F } :: S, H}
  1049. frame->todo.Pop(1);
  1050. frame->todo.Push(
  1051. global_arena->New<StatementAction>(cast<If>(*stmt).ThenStmt()));
  1052. } else if (cast<If>(*stmt).ElseStmt()) {
  1053. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1054. // S, H}
  1055. // -> { { else_stmt :: C, E, F } :: S, H}
  1056. frame->todo.Pop(1);
  1057. frame->todo.Push(
  1058. global_arena->New<StatementAction>(cast<If>(*stmt).ElseStmt()));
  1059. } else {
  1060. frame->todo.Pop(1);
  1061. }
  1062. break;
  1063. case Statement::Kind::Return:
  1064. if (act->Pos() == 0) {
  1065. // { {return e :: C, E, F} :: S, H}
  1066. // -> { {e :: return [] :: C, E, F} :: S, H}
  1067. frame->todo.Push(
  1068. global_arena->New<ExpressionAction>(cast<Return>(*stmt).Exp()));
  1069. act->IncrementPos();
  1070. } else {
  1071. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1072. // -> { {v :: C', E', F'} :: S, H}
  1073. const Value* ret_val = CopyVal(act->Results()[0], stmt->LineNumber());
  1074. DeallocateLocals(stmt->LineNumber(), frame);
  1075. state->stack.Pop(1);
  1076. frame = state->stack.Top();
  1077. frame->todo.Push(global_arena->New<ValAction>(ret_val));
  1078. }
  1079. break;
  1080. case Statement::Kind::Sequence:
  1081. CHECK(act->Pos() == 0);
  1082. // { { (s1,s2) :: C, E, F} :: S, H}
  1083. // -> { { s1 :: s2 :: C, E, F} :: S, H}
  1084. frame->todo.Pop(1);
  1085. if (cast<Sequence>(*stmt).Next()) {
  1086. frame->todo.Push(
  1087. global_arena->New<StatementAction>(cast<Sequence>(*stmt).Next()));
  1088. }
  1089. frame->todo.Push(
  1090. global_arena->New<StatementAction>(cast<Sequence>(*stmt).Stmt()));
  1091. break;
  1092. case Statement::Kind::Continuation: {
  1093. CHECK(act->Pos() == 0);
  1094. // Create a continuation object by creating a frame similar the
  1095. // way one is created in a function call.
  1096. auto scopes =
  1097. Stack<Ptr<Scope>>(global_arena->New<Scope>(CurrentEnv(state)));
  1098. Stack<Ptr<Action>> todo;
  1099. todo.Push(global_arena->New<StatementAction>(
  1100. global_arena->RawNew<Return>(stmt->LineNumber(), nullptr,
  1101. /*is_omitted_exp=*/true)));
  1102. todo.Push(
  1103. global_arena->New<StatementAction>(cast<Continuation>(*stmt).Body()));
  1104. auto continuation_frame =
  1105. global_arena->New<Frame>("__continuation", scopes, todo);
  1106. Address continuation_address =
  1107. state->heap.AllocateValue(global_arena->RawNew<ContinuationValue>(
  1108. std::vector<Ptr<Frame>>({continuation_frame})));
  1109. // Store the continuation's address in the frame.
  1110. continuation_frame->continuation = continuation_address;
  1111. // Bind the continuation object to the continuation variable
  1112. frame->scopes.Top()->values.Set(
  1113. cast<Continuation>(*stmt).ContinuationVariable(),
  1114. continuation_address);
  1115. // Pop the continuation statement.
  1116. frame->todo.Pop();
  1117. break;
  1118. }
  1119. case Statement::Kind::Run:
  1120. if (act->Pos() == 0) {
  1121. // Evaluate the argument of the run statement.
  1122. frame->todo.Push(
  1123. global_arena->New<ExpressionAction>(cast<Run>(*stmt).Argument()));
  1124. act->IncrementPos();
  1125. } else {
  1126. frame->todo.Pop(1);
  1127. // Push an expression statement action to ignore the result
  1128. // value from the continuation.
  1129. auto ignore_result = global_arena->New<StatementAction>(
  1130. global_arena->RawNew<ExpressionStatement>(
  1131. stmt->LineNumber(),
  1132. global_arena->RawNew<TupleLiteral>(stmt->LineNumber())));
  1133. frame->todo.Push(ignore_result);
  1134. // Push the continuation onto the current stack.
  1135. const std::vector<Ptr<Frame>>& continuation_vector =
  1136. cast<ContinuationValue>(*act->Results()[0]).Stack();
  1137. for (auto frame_iter = continuation_vector.rbegin();
  1138. frame_iter != continuation_vector.rend(); ++frame_iter) {
  1139. state->stack.Push(*frame_iter);
  1140. }
  1141. }
  1142. break;
  1143. case Statement::Kind::Await:
  1144. CHECK(act->Pos() == 0);
  1145. // Pause the current continuation
  1146. frame->todo.Pop();
  1147. std::vector<Ptr<Frame>> paused;
  1148. do {
  1149. paused.push_back(state->stack.Pop());
  1150. } while (paused.back()->continuation == std::nullopt);
  1151. // Update the continuation with the paused stack.
  1152. state->heap.Write(*paused.back()->continuation,
  1153. global_arena->RawNew<ContinuationValue>(paused),
  1154. stmt->LineNumber());
  1155. break;
  1156. }
  1157. }
  1158. // State transition.
  1159. void Step() {
  1160. Ptr<Frame> frame = state->stack.Top();
  1161. if (frame->todo.IsEmpty()) {
  1162. FATAL_RUNTIME_ERROR_NO_LINE()
  1163. << "fell off end of function " << frame->name << " without `return`";
  1164. }
  1165. Ptr<Action> act = frame->todo.Top();
  1166. switch (act->Tag()) {
  1167. case Action::Kind::ValAction: {
  1168. const ValAction& val_act = cast<ValAction>(*frame->todo.Pop());
  1169. Ptr<Action> act = frame->todo.Top();
  1170. act->AddResult(val_act.Val());
  1171. break;
  1172. }
  1173. case Action::Kind::LValAction:
  1174. StepLvalue();
  1175. break;
  1176. case Action::Kind::ExpressionAction:
  1177. StepExp();
  1178. break;
  1179. case Action::Kind::PatternAction:
  1180. StepPattern();
  1181. break;
  1182. case Action::Kind::StatementAction:
  1183. StepStmt();
  1184. break;
  1185. } // switch
  1186. }
  1187. // Interpret the whole porogram.
  1188. auto InterpProgram(const std::list<Ptr<const Declaration>>& fs) -> int {
  1189. state = global_arena->RawNew<State>(); // Runtime state.
  1190. if (tracing_output) {
  1191. llvm::outs() << "********** initializing globals **********\n";
  1192. }
  1193. InitGlobals(fs);
  1194. const Expression* arg = global_arena->RawNew<TupleLiteral>(0);
  1195. const Expression* call_main = global_arena->RawNew<CallExpression>(
  1196. 0, global_arena->RawNew<IdentifierExpression>(0, "main"), arg);
  1197. auto todo =
  1198. Stack<Ptr<Action>>(global_arena->New<ExpressionAction>(call_main));
  1199. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(globals));
  1200. state->stack =
  1201. Stack<Ptr<Frame>>(global_arena->New<Frame>("top", scopes, todo));
  1202. if (tracing_output) {
  1203. llvm::outs() << "********** calling main function **********\n";
  1204. PrintState(llvm::outs());
  1205. }
  1206. while (state->stack.Count() > 1 || state->stack.Top()->todo.Count() > 1 ||
  1207. state->stack.Top()->todo.Top()->Tag() != Action::Kind::ValAction) {
  1208. Step();
  1209. if (tracing_output) {
  1210. PrintState(llvm::outs());
  1211. }
  1212. }
  1213. const Value* v = cast<ValAction>(*state->stack.Top()->todo.Top()).Val();
  1214. return cast<IntValue>(*v).Val();
  1215. }
  1216. // Interpret an expression at compile-time.
  1217. auto InterpExp(Env values, const Expression* e) -> const Value* {
  1218. auto todo = Stack<Ptr<Action>>(global_arena->New<ExpressionAction>(e));
  1219. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values));
  1220. state->stack =
  1221. Stack<Ptr<Frame>>(global_arena->New<Frame>("InterpExp", scopes, todo));
  1222. while (state->stack.Count() > 1 || state->stack.Top()->todo.Count() > 1 ||
  1223. state->stack.Top()->todo.Top()->Tag() != Action::Kind::ValAction) {
  1224. Step();
  1225. }
  1226. return cast<ValAction>(*state->stack.Top()->todo.Top()).Val();
  1227. }
  1228. // Interpret a pattern at compile-time.
  1229. auto InterpPattern(Env values, const Pattern* p) -> const Value* {
  1230. auto todo = Stack<Ptr<Action>>(global_arena->New<PatternAction>(p));
  1231. auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(values));
  1232. state->stack = Stack<Ptr<Frame>>(
  1233. global_arena->New<Frame>("InterpPattern", scopes, todo));
  1234. while (state->stack.Count() > 1 || state->stack.Top()->todo.Count() > 1 ||
  1235. state->stack.Top()->todo.Top()->Tag() != Action::Kind::ValAction) {
  1236. Step();
  1237. }
  1238. return cast<ValAction>(*state->stack.Top()->todo.Top()).Val();
  1239. }
  1240. } // namespace Carbon