interpreter.cpp 47 KB

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