interpreter.cpp 48 KB

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