interpreter.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "executable_semantics/interpreter/interpreter.h"
  5. #include <iterator>
  6. #include <map>
  7. #include <optional>
  8. #include <utility>
  9. #include <variant>
  10. #include <vector>
  11. #include "common/check.h"
  12. #include "executable_semantics/ast/declaration.h"
  13. #include "executable_semantics/ast/expression.h"
  14. #include "executable_semantics/common/arena.h"
  15. #include "executable_semantics/common/error.h"
  16. #include "executable_semantics/interpreter/action.h"
  17. #include "executable_semantics/interpreter/action_stack.h"
  18. #include "executable_semantics/interpreter/stack.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/Support/Casting.h"
  21. #include "llvm/Support/Error.h"
  22. using llvm::cast;
  23. using llvm::dyn_cast;
  24. using llvm::isa;
  25. namespace Carbon {
  26. // Constructs an ActionStack suitable for the specified phase.
  27. static auto MakeTodo(Phase phase, Nonnull<Heap*> heap) -> ActionStack {
  28. switch (phase) {
  29. case Phase::CompileTime:
  30. return ActionStack();
  31. case Phase::RunTime:
  32. return ActionStack(heap);
  33. }
  34. }
  35. // An Interpreter represents an instance of the Carbon abstract machine. It
  36. // manages the state of the abstract machine, and executes the steps of Actions
  37. // passed to it.
  38. class Interpreter {
  39. public:
  40. // Constructs an Interpreter which allocates values on `arena`, and prints
  41. // traces if `trace` is true. `phase` indicates whether it executes at
  42. // compile time or run time.
  43. Interpreter(Phase phase, Nonnull<Arena*> arena, bool trace)
  44. : arena_(arena),
  45. heap_(arena),
  46. todo_(MakeTodo(phase, &heap_)),
  47. trace_(trace),
  48. phase_(phase) {}
  49. ~Interpreter();
  50. // Runs all the steps of `action`.
  51. // It's not safe to call `RunAllSteps()` or `result()` after an error.
  52. auto RunAllSteps(std::unique_ptr<Action> action) -> ErrorOr<Success>;
  53. // The result produced by the `action` argument of the most recent
  54. // RunAllSteps call. Cannot be called if `action` was an action that doesn't
  55. // produce results.
  56. auto result() const -> Nonnull<const Value*> { return todo_.result(); }
  57. private:
  58. auto Step() -> ErrorOr<Success>;
  59. // State transitions for expressions.
  60. auto StepExp() -> ErrorOr<Success>;
  61. // State transitions for lvalues.
  62. auto StepLvalue() -> ErrorOr<Success>;
  63. // State transitions for patterns.
  64. auto StepPattern() -> ErrorOr<Success>;
  65. // State transition for statements.
  66. auto StepStmt() -> ErrorOr<Success>;
  67. // State transition for declarations.
  68. auto StepDeclaration() -> ErrorOr<Success>;
  69. auto CreateStruct(const std::vector<FieldInitializer>& fields,
  70. const std::vector<Nonnull<const Value*>>& values)
  71. -> Nonnull<const Value*>;
  72. auto EvalPrim(Operator op, const std::vector<Nonnull<const Value*>>& args,
  73. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  74. // Returns the result of converting `value` to type `destination_type`.
  75. auto Convert(Nonnull<const Value*> value,
  76. Nonnull<const Value*> destination_type,
  77. SourceLocation source_loc) const
  78. -> ErrorOr<Nonnull<const Value*>>;
  79. // Instantiate a type by replacing all type variables that occur inside the
  80. // type by the current values of those variables.
  81. //
  82. // For example, suppose T=i32 and U=Bool. Then
  83. // __Fn (Point(T)) -> Point(U)
  84. // becomes
  85. // __Fn (Point(i32)) -> Point(Bool)
  86. auto InstantiateType(Nonnull<const Value*> type,
  87. SourceLocation source_loc) const
  88. -> ErrorOr<Nonnull<const Value*>>;
  89. void PrintState(llvm::raw_ostream& out);
  90. Phase phase() const { return phase_; }
  91. Nonnull<Arena*> arena_;
  92. Heap heap_;
  93. ActionStack todo_;
  94. // The underlying states of continuation values. All StackFragments created
  95. // during execution are tracked here, in order to safely deallocate the
  96. // contents of any non-completed continuations at the end of execution.
  97. std::vector<Nonnull<ContinuationValue::StackFragment*>> stack_fragments_;
  98. bool trace_;
  99. Phase phase_;
  100. };
  101. Interpreter::~Interpreter() {
  102. // Clean up any remaining suspended continuations.
  103. for (Nonnull<ContinuationValue::StackFragment*> fragment : stack_fragments_) {
  104. fragment->Clear();
  105. }
  106. }
  107. //
  108. // State Operations
  109. //
  110. void Interpreter::PrintState(llvm::raw_ostream& out) {
  111. out << "{\nstack: " << todo_;
  112. out << "\nheap: " << heap_;
  113. if (!todo_.IsEmpty()) {
  114. out << "\nvalues: ";
  115. todo_.PrintScopes(out);
  116. }
  117. out << "\n}\n";
  118. }
  119. auto Interpreter::EvalPrim(Operator op,
  120. const std::vector<Nonnull<const Value*>>& args,
  121. SourceLocation source_loc)
  122. -> ErrorOr<Nonnull<const Value*>> {
  123. switch (op) {
  124. case Operator::Neg:
  125. return arena_->New<IntValue>(-cast<IntValue>(*args[0]).value());
  126. case Operator::Add:
  127. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() +
  128. cast<IntValue>(*args[1]).value());
  129. case Operator::Sub:
  130. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() -
  131. cast<IntValue>(*args[1]).value());
  132. case Operator::Mul:
  133. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() *
  134. cast<IntValue>(*args[1]).value());
  135. case Operator::Not:
  136. return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
  137. case Operator::And:
  138. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
  139. cast<BoolValue>(*args[1]).value());
  140. case Operator::Or:
  141. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
  142. cast<BoolValue>(*args[1]).value());
  143. case Operator::Eq:
  144. return arena_->New<BoolValue>(ValueEqual(args[0], args[1]));
  145. case Operator::Ptr:
  146. return arena_->New<PointerType>(args[0]);
  147. case Operator::Deref:
  148. return heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc);
  149. case Operator::AddressOf:
  150. return arena_->New<PointerValue>(cast<LValue>(*args[0]).address());
  151. }
  152. }
  153. auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
  154. const std::vector<Nonnull<const Value*>>& values)
  155. -> Nonnull<const Value*> {
  156. CHECK(fields.size() == values.size());
  157. std::vector<NamedValue> elements;
  158. for (size_t i = 0; i < fields.size(); ++i) {
  159. elements.push_back({.name = fields[i].name(), .value = values[i]});
  160. }
  161. return arena_->New<StructValue>(std::move(elements));
  162. }
  163. auto PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
  164. SourceLocation source_loc,
  165. std::optional<Nonnull<RuntimeScope*>> bindings,
  166. BindingMap& generic_args) -> bool {
  167. switch (p->kind()) {
  168. case Value::Kind::BindingPlaceholderValue: {
  169. CHECK(bindings.has_value());
  170. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  171. if (placeholder.value_node().has_value()) {
  172. (*bindings)->Initialize(*placeholder.value_node(), v);
  173. }
  174. return true;
  175. }
  176. case Value::Kind::VariableType: {
  177. const auto& var_type = cast<VariableType>(*p);
  178. generic_args[&var_type.binding()] = v;
  179. return true;
  180. }
  181. case Value::Kind::TupleValue:
  182. switch (v->kind()) {
  183. case Value::Kind::TupleValue: {
  184. const auto& p_tup = cast<TupleValue>(*p);
  185. const auto& v_tup = cast<TupleValue>(*v);
  186. CHECK(p_tup.elements().size() == v_tup.elements().size());
  187. for (size_t i = 0; i < p_tup.elements().size(); ++i) {
  188. if (!PatternMatch(p_tup.elements()[i], v_tup.elements()[i],
  189. source_loc, bindings, generic_args)) {
  190. return false;
  191. }
  192. } // for
  193. return true;
  194. }
  195. default:
  196. FATAL() << "expected a tuple value in pattern, not " << *v;
  197. }
  198. case Value::Kind::StructValue: {
  199. const auto& p_struct = cast<StructValue>(*p);
  200. const auto& v_struct = cast<StructValue>(*v);
  201. CHECK(p_struct.elements().size() == v_struct.elements().size());
  202. for (size_t i = 0; i < p_struct.elements().size(); ++i) {
  203. CHECK(p_struct.elements()[i].name == v_struct.elements()[i].name);
  204. if (!PatternMatch(p_struct.elements()[i].value,
  205. v_struct.elements()[i].value, source_loc, bindings,
  206. generic_args)) {
  207. return false;
  208. }
  209. }
  210. return true;
  211. }
  212. case Value::Kind::AlternativeValue:
  213. switch (v->kind()) {
  214. case Value::Kind::AlternativeValue: {
  215. const auto& p_alt = cast<AlternativeValue>(*p);
  216. const auto& v_alt = cast<AlternativeValue>(*v);
  217. if (p_alt.choice_name() != v_alt.choice_name() ||
  218. p_alt.alt_name() != v_alt.alt_name()) {
  219. return false;
  220. }
  221. return PatternMatch(&p_alt.argument(), &v_alt.argument(), source_loc,
  222. bindings, generic_args);
  223. }
  224. default:
  225. FATAL() << "expected a choice alternative in pattern, not " << *v;
  226. }
  227. case Value::Kind::FunctionType:
  228. switch (v->kind()) {
  229. case Value::Kind::FunctionType: {
  230. const auto& p_fn = cast<FunctionType>(*p);
  231. const auto& v_fn = cast<FunctionType>(*v);
  232. if (!PatternMatch(&p_fn.parameters(), &v_fn.parameters(), source_loc,
  233. bindings, generic_args)) {
  234. return false;
  235. }
  236. if (!PatternMatch(&p_fn.return_type(), &v_fn.return_type(),
  237. source_loc, bindings, generic_args)) {
  238. return false;
  239. }
  240. return true;
  241. }
  242. default:
  243. return false;
  244. }
  245. case Value::Kind::AutoType:
  246. // `auto` matches any type, without binding any new names. We rely
  247. // on the typechecker to ensure that `v` is a type.
  248. return true;
  249. default:
  250. return ValueEqual(p, v);
  251. }
  252. }
  253. auto Interpreter::StepLvalue() -> ErrorOr<Success> {
  254. Action& act = todo_.CurrentAction();
  255. const Expression& exp = cast<LValAction>(act).expression();
  256. if (trace_) {
  257. llvm::outs() << "--- step lvalue " << exp << " (" << exp.source_loc()
  258. << ") --->\n";
  259. }
  260. switch (exp.kind()) {
  261. case ExpressionKind::IdentifierExpression: {
  262. // { {x :: C, E, F} :: S, H}
  263. // -> { {E(x) :: C, E, F} :: S, H}
  264. ASSIGN_OR_RETURN(
  265. Nonnull<const Value*> value,
  266. todo_.ValueOfNode(cast<IdentifierExpression>(exp).value_node(),
  267. exp.source_loc()));
  268. CHECK(isa<LValue>(value)) << *value;
  269. return todo_.FinishAction(value);
  270. }
  271. case ExpressionKind::FieldAccessExpression: {
  272. if (act.pos() == 0) {
  273. // { {e.f :: C, E, F} :: S, H}
  274. // -> { e :: [].f :: C, E, F} :: S, H}
  275. return todo_.Spawn(std::make_unique<LValAction>(
  276. &cast<FieldAccessExpression>(exp).aggregate()));
  277. } else {
  278. // { v :: [].f :: C, E, F} :: S, H}
  279. // -> { { &v.f :: C, E, F} :: S, H }
  280. Address aggregate = cast<LValue>(*act.results()[0]).address();
  281. Address field = aggregate.SubobjectAddress(
  282. cast<FieldAccessExpression>(exp).field());
  283. return todo_.FinishAction(arena_->New<LValue>(field));
  284. }
  285. }
  286. case ExpressionKind::IndexExpression: {
  287. if (act.pos() == 0) {
  288. // { {e[i] :: C, E, F} :: S, H}
  289. // -> { e :: [][i] :: C, E, F} :: S, H}
  290. return todo_.Spawn(std::make_unique<LValAction>(
  291. &cast<IndexExpression>(exp).aggregate()));
  292. } else if (act.pos() == 1) {
  293. return todo_.Spawn(std::make_unique<ExpressionAction>(
  294. &cast<IndexExpression>(exp).offset()));
  295. } else {
  296. // { v :: [][i] :: C, E, F} :: S, H}
  297. // -> { { &v[i] :: C, E, F} :: S, H }
  298. Address aggregate = cast<LValue>(*act.results()[0]).address();
  299. std::string f =
  300. std::to_string(cast<IntValue>(*act.results()[1]).value());
  301. Address field = aggregate.SubobjectAddress(f);
  302. return todo_.FinishAction(arena_->New<LValue>(field));
  303. }
  304. }
  305. case ExpressionKind::PrimitiveOperatorExpression: {
  306. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  307. if (op.op() != Operator::Deref) {
  308. FATAL() << "Can't treat primitive operator expression as lvalue: "
  309. << exp;
  310. }
  311. if (act.pos() == 0) {
  312. return todo_.Spawn(
  313. std::make_unique<ExpressionAction>(op.arguments()[0]));
  314. } else {
  315. const auto& res = cast<PointerValue>(*act.results()[0]);
  316. return todo_.FinishAction(arena_->New<LValue>(res.address()));
  317. }
  318. break;
  319. }
  320. case ExpressionKind::TupleLiteral:
  321. case ExpressionKind::StructLiteral:
  322. case ExpressionKind::StructTypeLiteral:
  323. case ExpressionKind::IntLiteral:
  324. case ExpressionKind::BoolLiteral:
  325. case ExpressionKind::CallExpression:
  326. case ExpressionKind::IntTypeLiteral:
  327. case ExpressionKind::BoolTypeLiteral:
  328. case ExpressionKind::TypeTypeLiteral:
  329. case ExpressionKind::FunctionTypeLiteral:
  330. case ExpressionKind::ContinuationTypeLiteral:
  331. case ExpressionKind::StringLiteral:
  332. case ExpressionKind::StringTypeLiteral:
  333. case ExpressionKind::IntrinsicExpression:
  334. case ExpressionKind::IfExpression:
  335. FATAL() << "Can't treat expression as lvalue: " << exp;
  336. case ExpressionKind::UnimplementedExpression:
  337. FATAL() << "Unimplemented: " << exp;
  338. }
  339. }
  340. auto Interpreter::InstantiateType(Nonnull<const Value*> type,
  341. SourceLocation source_loc) const
  342. -> ErrorOr<Nonnull<const Value*>> {
  343. if (trace_) {
  344. llvm::outs() << "instantiating: " << *type << "\n";
  345. }
  346. switch (type->kind()) {
  347. case Value::Kind::VariableType: {
  348. if (trace_) {
  349. llvm::outs() << "case VariableType\n";
  350. }
  351. ASSIGN_OR_RETURN(
  352. Nonnull<const Value*> value,
  353. todo_.ValueOfNode(&cast<VariableType>(*type).binding(), source_loc));
  354. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  355. ASSIGN_OR_RETURN(value, heap_.Read(lvalue->address(), source_loc));
  356. }
  357. return value;
  358. }
  359. case Value::Kind::NominalClassType: {
  360. if (trace_) {
  361. llvm::outs() << "case NominalClassType\n";
  362. }
  363. const auto& class_type = cast<NominalClassType>(*type);
  364. BindingMap inst_type_args;
  365. for (const auto& [ty_var, ty_arg] : class_type.type_args()) {
  366. ASSIGN_OR_RETURN(inst_type_args[ty_var],
  367. InstantiateType(ty_arg, source_loc));
  368. }
  369. if (trace_) {
  370. llvm::outs() << "finished instantiating ty_arg\n";
  371. }
  372. std::map<Nonnull<const ImplBinding*>, Nonnull<const Witness*>> witnesses;
  373. for (const auto& [bind, impl] : class_type.impls()) {
  374. ASSIGN_OR_RETURN(Nonnull<const Value*> witness_addr,
  375. todo_.ValueOfNode(impl, source_loc));
  376. if (trace_) {
  377. llvm::outs() << "witness_addr: " << *witness_addr << "\n";
  378. }
  379. // If the witness came directly from an `impl` declaration (via
  380. // `constant_value`), then it is a `Witness`. If the witness
  381. // came from the runtime scope, then the `Witness` got wrapped
  382. // in an `LValue` because that's what
  383. // `RuntimeScope::Initialize` does.
  384. Nonnull<const Witness*> witness;
  385. if (llvm::isa<Witness>(witness_addr)) {
  386. witness = cast<Witness>(witness_addr);
  387. } else if (llvm::isa<LValue>(witness_addr)) {
  388. ASSIGN_OR_RETURN(
  389. Nonnull<const Value*> witness_value,
  390. heap_.Read(llvm::cast<LValue>(witness_addr)->address(),
  391. source_loc));
  392. witness = cast<Witness>(witness_value);
  393. } else {
  394. FATAL() << "expected a witness or LValue of a witness";
  395. }
  396. witnesses[bind] = witness;
  397. }
  398. if (trace_) {
  399. llvm::outs() << "finished finding witnesses\n";
  400. }
  401. return arena_->New<NominalClassType>(&class_type.declaration(),
  402. inst_type_args, witnesses);
  403. }
  404. default:
  405. return type;
  406. }
  407. }
  408. auto Interpreter::Convert(Nonnull<const Value*> value,
  409. Nonnull<const Value*> destination_type,
  410. SourceLocation source_loc) const
  411. -> ErrorOr<Nonnull<const Value*>> {
  412. switch (value->kind()) {
  413. case Value::Kind::IntValue:
  414. case Value::Kind::FunctionValue:
  415. case Value::Kind::BoundMethodValue:
  416. case Value::Kind::PointerValue:
  417. case Value::Kind::LValue:
  418. case Value::Kind::BoolValue:
  419. case Value::Kind::NominalClassValue:
  420. case Value::Kind::AlternativeValue:
  421. case Value::Kind::IntType:
  422. case Value::Kind::BoolType:
  423. case Value::Kind::TypeType:
  424. case Value::Kind::FunctionType:
  425. case Value::Kind::PointerType:
  426. case Value::Kind::AutoType:
  427. case Value::Kind::StructType:
  428. case Value::Kind::NominalClassType:
  429. case Value::Kind::InterfaceType:
  430. case Value::Kind::Witness:
  431. case Value::Kind::ChoiceType:
  432. case Value::Kind::ContinuationType:
  433. case Value::Kind::VariableType:
  434. case Value::Kind::BindingPlaceholderValue:
  435. case Value::Kind::AlternativeConstructorValue:
  436. case Value::Kind::ContinuationValue:
  437. case Value::Kind::StringType:
  438. case Value::Kind::StringValue:
  439. case Value::Kind::TypeOfClassType:
  440. case Value::Kind::TypeOfInterfaceType:
  441. case Value::Kind::TypeOfChoiceType:
  442. // TODO: add `CHECK(TypeEqual(type, value->dynamic_type()))`, once we
  443. // have Value::dynamic_type.
  444. return value;
  445. case Value::Kind::StructValue: {
  446. const auto& struct_val = cast<StructValue>(*value);
  447. switch (destination_type->kind()) {
  448. case Value::Kind::StructType: {
  449. const auto& destination_struct_type =
  450. cast<StructType>(*destination_type);
  451. std::vector<NamedValue> new_elements;
  452. for (const auto& [field_name, field_type] :
  453. destination_struct_type.fields()) {
  454. std::optional<Nonnull<const Value*>> old_value =
  455. struct_val.FindField(field_name);
  456. ASSIGN_OR_RETURN(Nonnull<const Value*> val,
  457. Convert(*old_value, field_type, source_loc));
  458. new_elements.push_back({.name = field_name, .value = val});
  459. }
  460. return arena_->New<StructValue>(std::move(new_elements));
  461. }
  462. case Value::Kind::NominalClassType: {
  463. // Instantiate the `destintation_type` to obtain the runtime
  464. // type of the object.
  465. ASSIGN_OR_RETURN(Nonnull<const Value*> inst_dest,
  466. InstantiateType(destination_type, source_loc));
  467. return arena_->New<NominalClassValue>(inst_dest, value);
  468. }
  469. default:
  470. FATAL() << "Can't convert value " << *value << " to type "
  471. << *destination_type;
  472. }
  473. }
  474. case Value::Kind::TupleValue: {
  475. const auto& tuple = cast<TupleValue>(value);
  476. const auto& destination_tuple_type = cast<TupleValue>(destination_type);
  477. CHECK(tuple->elements().size() ==
  478. destination_tuple_type->elements().size());
  479. std::vector<Nonnull<const Value*>> new_elements;
  480. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  481. ASSIGN_OR_RETURN(
  482. Nonnull<const Value*> val,
  483. Convert(tuple->elements()[i], destination_tuple_type->elements()[i],
  484. source_loc));
  485. new_elements.push_back(val);
  486. }
  487. return arena_->New<TupleValue>(std::move(new_elements));
  488. }
  489. }
  490. }
  491. auto Interpreter::StepExp() -> ErrorOr<Success> {
  492. Action& act = todo_.CurrentAction();
  493. const Expression& exp = cast<ExpressionAction>(act).expression();
  494. if (trace_) {
  495. llvm::outs() << "--- step exp " << exp << " (" << exp.source_loc()
  496. << ") --->\n";
  497. }
  498. switch (exp.kind()) {
  499. case ExpressionKind::IndexExpression: {
  500. if (act.pos() == 0) {
  501. // { { e[i] :: C, E, F} :: S, H}
  502. // -> { { e :: [][i] :: C, E, F} :: S, H}
  503. return todo_.Spawn(std::make_unique<ExpressionAction>(
  504. &cast<IndexExpression>(exp).aggregate()));
  505. } else if (act.pos() == 1) {
  506. return todo_.Spawn(std::make_unique<ExpressionAction>(
  507. &cast<IndexExpression>(exp).offset()));
  508. } else {
  509. // { { v :: [][i] :: C, E, F} :: S, H}
  510. // -> { { v_i :: C, E, F} : S, H}
  511. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  512. int i = cast<IntValue>(*act.results()[1]).value();
  513. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  514. return FATAL_RUNTIME_ERROR_NO_LINE()
  515. << "index " << i << " out of range in " << tuple;
  516. }
  517. return todo_.FinishAction(tuple.elements()[i]);
  518. }
  519. }
  520. case ExpressionKind::TupleLiteral: {
  521. if (act.pos() <
  522. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  523. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  524. // H}
  525. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  526. // H}
  527. return todo_.Spawn(std::make_unique<ExpressionAction>(
  528. cast<TupleLiteral>(exp).fields()[act.pos()]));
  529. } else {
  530. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  531. }
  532. }
  533. case ExpressionKind::StructLiteral: {
  534. const auto& literal = cast<StructLiteral>(exp);
  535. if (act.pos() < static_cast<int>(literal.fields().size())) {
  536. return todo_.Spawn(std::make_unique<ExpressionAction>(
  537. &literal.fields()[act.pos()].expression()));
  538. } else {
  539. return todo_.FinishAction(
  540. CreateStruct(literal.fields(), act.results()));
  541. }
  542. }
  543. case ExpressionKind::StructTypeLiteral: {
  544. const auto& struct_type = cast<StructTypeLiteral>(exp);
  545. if (act.pos() < static_cast<int>(struct_type.fields().size())) {
  546. return todo_.Spawn(std::make_unique<ExpressionAction>(
  547. &struct_type.fields()[act.pos()].expression()));
  548. } else {
  549. std::vector<NamedValue> fields;
  550. for (size_t i = 0; i < struct_type.fields().size(); ++i) {
  551. fields.push_back({struct_type.fields()[i].name(), act.results()[i]});
  552. }
  553. return todo_.FinishAction(arena_->New<StructType>(std::move(fields)));
  554. }
  555. }
  556. case ExpressionKind::FieldAccessExpression: {
  557. const auto& access = cast<FieldAccessExpression>(exp);
  558. if (act.pos() == 0) {
  559. // { { e.f :: C, E, F} :: S, H}
  560. // -> { { e :: [].f :: C, E, F} :: S, H}
  561. return todo_.Spawn(
  562. std::make_unique<ExpressionAction>(&access.aggregate()));
  563. } else {
  564. // { { v :: [].f :: C, E, F} :: S, H}
  565. // -> { { v_f :: C, E, F} : S, H}
  566. std::optional<Nonnull<const Witness*>> witness = std::nullopt;
  567. if (access.impl().has_value()) {
  568. ASSIGN_OR_RETURN(
  569. auto witness_addr,
  570. todo_.ValueOfNode(*access.impl(), access.source_loc()));
  571. ASSIGN_OR_RETURN(
  572. Nonnull<const Value*> witness_value,
  573. heap_.Read(llvm::cast<LValue>(witness_addr)->address(),
  574. access.source_loc()));
  575. witness = cast<Witness>(witness_value);
  576. }
  577. FieldPath::Component field(access.field(), witness);
  578. ASSIGN_OR_RETURN(Nonnull<const Value*> member,
  579. act.results()[0]->GetField(arena_, FieldPath(field),
  580. exp.source_loc()));
  581. return todo_.FinishAction(member);
  582. }
  583. }
  584. case ExpressionKind::IdentifierExpression: {
  585. CHECK(act.pos() == 0);
  586. const auto& ident = cast<IdentifierExpression>(exp);
  587. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  588. ASSIGN_OR_RETURN(
  589. Nonnull<const Value*> value,
  590. todo_.ValueOfNode(ident.value_node(), ident.source_loc()));
  591. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  592. ASSIGN_OR_RETURN(value,
  593. heap_.Read(lvalue->address(), exp.source_loc()));
  594. }
  595. return todo_.FinishAction(value);
  596. }
  597. case ExpressionKind::IntLiteral:
  598. CHECK(act.pos() == 0);
  599. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  600. return todo_.FinishAction(
  601. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  602. case ExpressionKind::BoolLiteral:
  603. CHECK(act.pos() == 0);
  604. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  605. return todo_.FinishAction(
  606. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  607. case ExpressionKind::PrimitiveOperatorExpression: {
  608. const auto& op = cast<PrimitiveOperatorExpression>(exp);
  609. if (act.pos() != static_cast<int>(op.arguments().size())) {
  610. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  611. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  612. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  613. if (op.op() == Operator::AddressOf) {
  614. return todo_.Spawn(std::make_unique<LValAction>(arg));
  615. } else {
  616. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  617. }
  618. } else {
  619. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  620. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  621. ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  622. EvalPrim(op.op(), act.results(), exp.source_loc()));
  623. return todo_.FinishAction(value);
  624. }
  625. }
  626. case ExpressionKind::CallExpression:
  627. if (act.pos() == 0) {
  628. // { {e1(e2) :: C, E, F} :: S, H}
  629. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  630. return todo_.Spawn(std::make_unique<ExpressionAction>(
  631. &cast<CallExpression>(exp).function()));
  632. } else if (act.pos() == 1) {
  633. // { { v :: [](e) :: C, E, F} :: S, H}
  634. // -> { { e :: v([]) :: C, E, F} :: S, H}
  635. return todo_.Spawn(std::make_unique<ExpressionAction>(
  636. &cast<CallExpression>(exp).argument()));
  637. } else if (act.pos() == 2) {
  638. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  639. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  640. switch (act.results()[0]->kind()) {
  641. case Value::Kind::AlternativeConstructorValue: {
  642. const auto& alt =
  643. cast<AlternativeConstructorValue>(*act.results()[0]);
  644. return todo_.FinishAction(arena_->New<AlternativeValue>(
  645. alt.alt_name(), alt.choice_name(), act.results()[1]));
  646. }
  647. case Value::Kind::FunctionValue: {
  648. const FunctionValue& fun_val =
  649. cast<FunctionValue>(*act.results()[0]);
  650. const FunctionDeclaration& function = fun_val.declaration();
  651. if (trace_) {
  652. llvm::outs() << "*** call function " << function.name() << "\n";
  653. }
  654. ASSIGN_OR_RETURN(Nonnull<const Value*> converted_args,
  655. Convert(act.results()[1],
  656. &function.param_pattern().static_type(),
  657. exp.source_loc()));
  658. RuntimeScope function_scope(&heap_);
  659. // Bring the class type arguments into scope.
  660. for (const auto& [bind, val] : fun_val.type_args()) {
  661. function_scope.Initialize(bind, val);
  662. }
  663. // Bring the deduced type arguments into scope.
  664. for (const auto& [bind, val] :
  665. cast<CallExpression>(exp).deduced_args()) {
  666. function_scope.Initialize(bind, val);
  667. }
  668. // Bring the impl witness tables into scope.
  669. for (const auto& [impl_bind, impl_node] :
  670. cast<CallExpression>(exp).impls()) {
  671. ASSIGN_OR_RETURN(Nonnull<const Value*> witness,
  672. todo_.ValueOfNode(impl_node, exp.source_loc()));
  673. if (witness->kind() == Value::Kind::LValue) {
  674. const auto& lval = cast<LValue>(*witness);
  675. ASSIGN_OR_RETURN(witness,
  676. heap_.Read(lval.address(), exp.source_loc()));
  677. }
  678. function_scope.Initialize(impl_bind, witness);
  679. }
  680. for (const auto& [impl_bind, witness] : fun_val.witnesses()) {
  681. function_scope.Initialize(impl_bind, witness);
  682. }
  683. BindingMap generic_args;
  684. CHECK(PatternMatch(&function.param_pattern().value(),
  685. converted_args, exp.source_loc(),
  686. &function_scope, generic_args));
  687. CHECK(function.body().has_value())
  688. << "Calling a function that's missing a body";
  689. return todo_.Spawn(
  690. std::make_unique<StatementAction>(*function.body()),
  691. std::move(function_scope));
  692. }
  693. case Value::Kind::BoundMethodValue: {
  694. const auto& m = cast<BoundMethodValue>(*act.results()[0]);
  695. const FunctionDeclaration& method = m.declaration();
  696. CHECK(method.is_method());
  697. ASSIGN_OR_RETURN(
  698. Nonnull<const Value*> converted_args,
  699. Convert(act.results()[1], &method.param_pattern().static_type(),
  700. exp.source_loc()));
  701. RuntimeScope method_scope(&heap_);
  702. BindingMap generic_args;
  703. CHECK(PatternMatch(&method.me_pattern().value(), m.receiver(),
  704. exp.source_loc(), &method_scope, generic_args));
  705. CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  706. exp.source_loc(), &method_scope, generic_args));
  707. // Bring the class type arguments into scope.
  708. for (const auto& [bind, val] : m.type_args()) {
  709. method_scope.Initialize(bind, val);
  710. }
  711. // Bring the impl witness tables into scope.
  712. for (const auto& [impl_bind, witness] : m.witnesses()) {
  713. method_scope.Initialize(impl_bind, witness);
  714. }
  715. CHECK(method.body().has_value())
  716. << "Calling a method that's missing a body";
  717. return todo_.Spawn(
  718. std::make_unique<StatementAction>(*method.body()),
  719. std::move(method_scope));
  720. }
  721. case Value::Kind::NominalClassType: {
  722. const NominalClassType& class_type =
  723. cast<NominalClassType>(*act.results()[0]);
  724. const ClassDeclaration& class_decl = class_type.declaration();
  725. RuntimeScope type_params_scope(&heap_);
  726. BindingMap generic_args;
  727. if (class_decl.type_params().has_value()) {
  728. CHECK(PatternMatch(&(*class_decl.type_params())->value(),
  729. act.results()[1], exp.source_loc(),
  730. &type_params_scope, generic_args));
  731. switch (phase()) {
  732. case Phase::RunTime: {
  733. std::map<Nonnull<const ImplBinding*>, const Witness*>
  734. witnesses;
  735. for (const auto& [impl_bind, impl_node] :
  736. cast<CallExpression>(exp).impls()) {
  737. ASSIGN_OR_RETURN(
  738. Nonnull<const Value*> witness,
  739. todo_.ValueOfNode(impl_node, exp.source_loc()));
  740. if (witness->kind() == Value::Kind::LValue) {
  741. const LValue& lval = cast<LValue>(*witness);
  742. ASSIGN_OR_RETURN(witness, heap_.Read(lval.address(),
  743. exp.source_loc()));
  744. }
  745. witnesses[impl_bind] = &cast<Witness>(*witness);
  746. }
  747. Nonnull<NominalClassType*> inst_class =
  748. arena_->New<NominalClassType>(&class_type.declaration(),
  749. generic_args, witnesses);
  750. return todo_.FinishAction(inst_class);
  751. }
  752. case Phase::CompileTime: {
  753. Nonnull<NominalClassType*> inst_class =
  754. arena_->New<NominalClassType>(
  755. &class_type.declaration(), generic_args,
  756. cast<CallExpression>(exp).impls());
  757. return todo_.FinishAction(inst_class);
  758. }
  759. }
  760. } else {
  761. FATAL() << "instantiation of non-generic class " << class_type;
  762. }
  763. }
  764. default:
  765. return FATAL_RUNTIME_ERROR(exp.source_loc())
  766. << "in call, expected a function, not " << *act.results()[0];
  767. }
  768. } else if (act.pos() == 3) {
  769. if (act.results().size() < 3) {
  770. // Control fell through without explicit return.
  771. return todo_.FinishAction(TupleValue::Empty());
  772. } else {
  773. return todo_.FinishAction(act.results()[2]);
  774. }
  775. } else {
  776. FATAL() << "in handle_value with Call pos " << act.pos();
  777. }
  778. case ExpressionKind::IntrinsicExpression: {
  779. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  780. if (act.pos() == 0) {
  781. return todo_.Spawn(
  782. std::make_unique<ExpressionAction>(&intrinsic.args()));
  783. }
  784. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  785. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  786. case IntrinsicExpression::Intrinsic::Print: {
  787. const auto& args = cast<TupleValue>(*act.results()[0]);
  788. // TODO: This could eventually use something like llvm::formatv.
  789. llvm::outs() << cast<StringValue>(*args.elements()[0]).value();
  790. return todo_.FinishAction(TupleValue::Empty());
  791. }
  792. }
  793. }
  794. case ExpressionKind::IntTypeLiteral: {
  795. CHECK(act.pos() == 0);
  796. return todo_.FinishAction(arena_->New<IntType>());
  797. }
  798. case ExpressionKind::BoolTypeLiteral: {
  799. CHECK(act.pos() == 0);
  800. return todo_.FinishAction(arena_->New<BoolType>());
  801. }
  802. case ExpressionKind::TypeTypeLiteral: {
  803. CHECK(act.pos() == 0);
  804. return todo_.FinishAction(arena_->New<TypeType>());
  805. }
  806. case ExpressionKind::FunctionTypeLiteral: {
  807. if (act.pos() == 0) {
  808. return todo_.Spawn(std::make_unique<ExpressionAction>(
  809. &cast<FunctionTypeLiteral>(exp).parameter()));
  810. } else if (act.pos() == 1) {
  811. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  812. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  813. return todo_.Spawn(std::make_unique<ExpressionAction>(
  814. &cast<FunctionTypeLiteral>(exp).return_type()));
  815. } else {
  816. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  817. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  818. return todo_.FinishAction(arena_->New<FunctionType>(
  819. std::vector<Nonnull<const GenericBinding*>>(), act.results()[0],
  820. act.results()[1], std::vector<Nonnull<const ImplBinding*>>()));
  821. }
  822. }
  823. case ExpressionKind::ContinuationTypeLiteral: {
  824. CHECK(act.pos() == 0);
  825. return todo_.FinishAction(arena_->New<ContinuationType>());
  826. }
  827. case ExpressionKind::StringLiteral:
  828. CHECK(act.pos() == 0);
  829. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  830. return todo_.FinishAction(
  831. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  832. case ExpressionKind::StringTypeLiteral: {
  833. CHECK(act.pos() == 0);
  834. return todo_.FinishAction(arena_->New<StringType>());
  835. }
  836. case ExpressionKind::IfExpression: {
  837. const auto& if_expr = cast<IfExpression>(exp);
  838. if (act.pos() == 0) {
  839. return todo_.Spawn(
  840. std::make_unique<ExpressionAction>(if_expr.condition()));
  841. } else if (act.pos() == 1) {
  842. const auto& condition = cast<BoolValue>(*act.results()[0]);
  843. return todo_.Spawn(std::make_unique<ExpressionAction>(
  844. condition.value() ? if_expr.then_expression()
  845. : if_expr.else_expression()));
  846. } else {
  847. return todo_.FinishAction(act.results()[1]);
  848. }
  849. break;
  850. }
  851. case ExpressionKind::UnimplementedExpression:
  852. FATAL() << "Unimplemented: " << exp;
  853. } // switch (exp->kind)
  854. }
  855. auto Interpreter::StepPattern() -> ErrorOr<Success> {
  856. Action& act = todo_.CurrentAction();
  857. const Pattern& pattern = cast<PatternAction>(act).pattern();
  858. if (trace_) {
  859. llvm::outs() << "--- step pattern " << pattern << " ("
  860. << pattern.source_loc() << ") --->\n";
  861. }
  862. switch (pattern.kind()) {
  863. case PatternKind::AutoPattern: {
  864. CHECK(act.pos() == 0);
  865. return todo_.FinishAction(arena_->New<AutoType>());
  866. }
  867. case PatternKind::BindingPattern: {
  868. const auto& binding = cast<BindingPattern>(pattern);
  869. if (binding.name() != AnonymousName) {
  870. return todo_.FinishAction(
  871. arena_->New<BindingPlaceholderValue>(&binding));
  872. } else {
  873. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  874. }
  875. }
  876. case PatternKind::GenericBinding: {
  877. const auto& binding = cast<GenericBinding>(pattern);
  878. return todo_.FinishAction(arena_->New<VariableType>(&binding));
  879. }
  880. case PatternKind::TuplePattern: {
  881. const auto& tuple = cast<TuplePattern>(pattern);
  882. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  883. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  884. // H}
  885. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  886. // H}
  887. return todo_.Spawn(
  888. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  889. } else {
  890. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  891. }
  892. }
  893. case PatternKind::AlternativePattern: {
  894. const auto& alternative = cast<AlternativePattern>(pattern);
  895. if (act.pos() == 0) {
  896. return todo_.Spawn(
  897. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  898. } else if (act.pos() == 1) {
  899. return todo_.Spawn(
  900. std::make_unique<PatternAction>(&alternative.arguments()));
  901. } else {
  902. CHECK(act.pos() == 2);
  903. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  904. return todo_.FinishAction(arena_->New<AlternativeValue>(
  905. alternative.alternative_name(), choice_type.name(),
  906. act.results()[1]));
  907. }
  908. }
  909. case PatternKind::ExpressionPattern:
  910. if (act.pos() == 0) {
  911. return todo_.Spawn(std::make_unique<ExpressionAction>(
  912. &cast<ExpressionPattern>(pattern).expression()));
  913. } else {
  914. return todo_.FinishAction(act.results()[0]);
  915. }
  916. case PatternKind::VarPattern:
  917. if (act.pos() == 0) {
  918. return todo_.Spawn(std::make_unique<PatternAction>(
  919. &cast<VarPattern>(pattern).pattern()));
  920. } else {
  921. return todo_.FinishAction(act.results()[0]);
  922. }
  923. }
  924. }
  925. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  926. Action& act = todo_.CurrentAction();
  927. const Statement& stmt = cast<StatementAction>(act).statement();
  928. if (trace_) {
  929. llvm::outs() << "--- step stmt ";
  930. stmt.PrintDepth(1, llvm::outs());
  931. llvm::outs() << " (" << stmt.source_loc() << ") --->\n";
  932. }
  933. switch (stmt.kind()) {
  934. case StatementKind::Match: {
  935. const auto& match_stmt = cast<Match>(stmt);
  936. if (act.pos() == 0) {
  937. // { { (match (e) ...) :: C, E, F} :: S, H}
  938. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  939. act.StartScope(RuntimeScope(&heap_));
  940. return todo_.Spawn(
  941. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  942. } else {
  943. int clause_num = act.pos() - 1;
  944. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  945. return todo_.FinishAction();
  946. }
  947. auto c = match_stmt.clauses()[clause_num];
  948. RuntimeScope matches(&heap_);
  949. BindingMap generic_args;
  950. ASSIGN_OR_RETURN(Nonnull<const Value*> val,
  951. Convert(act.results()[0], &c.pattern().static_type(),
  952. stmt.source_loc()));
  953. if (PatternMatch(&c.pattern().value(), val, stmt.source_loc(), &matches,
  954. generic_args)) {
  955. // Ensure we don't process any more clauses.
  956. act.set_pos(match_stmt.clauses().size() + 1);
  957. todo_.MergeScope(std::move(matches));
  958. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  959. } else {
  960. return todo_.RunAgain();
  961. }
  962. }
  963. }
  964. case StatementKind::While:
  965. if (act.pos() % 2 == 0) {
  966. // { { (while (e) s) :: C, E, F} :: S, H}
  967. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  968. act.Clear();
  969. return todo_.Spawn(
  970. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  971. } else {
  972. ASSIGN_OR_RETURN(Nonnull<const Value*> condition,
  973. Convert(act.results().back(), arena_->New<BoolType>(),
  974. stmt.source_loc()));
  975. if (cast<BoolValue>(*condition).value()) {
  976. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  977. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  978. return todo_.Spawn(
  979. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  980. } else {
  981. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  982. // -> { { C, E, F } :: S, H}
  983. return todo_.FinishAction();
  984. }
  985. }
  986. case StatementKind::Break: {
  987. CHECK(act.pos() == 0);
  988. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  989. // -> { { C, E', F} :: S, H}
  990. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  991. }
  992. case StatementKind::Continue: {
  993. CHECK(act.pos() == 0);
  994. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  995. // -> { { (while (e) s) :: C, E', F} :: S, H}
  996. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  997. }
  998. case StatementKind::Block: {
  999. const auto& block = cast<Block>(stmt);
  1000. if (act.pos() >= static_cast<int>(block.statements().size())) {
  1001. // If the position is past the end of the block, end processing. Note
  1002. // that empty blocks immediately end.
  1003. return todo_.FinishAction();
  1004. }
  1005. // Initialize a scope when starting a block.
  1006. if (act.pos() == 0) {
  1007. act.StartScope(RuntimeScope(&heap_));
  1008. }
  1009. // Process the next statement in the block. The position will be
  1010. // incremented as part of Spawn.
  1011. return todo_.Spawn(
  1012. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  1013. }
  1014. case StatementKind::VariableDefinition: {
  1015. const auto& definition = cast<VariableDefinition>(stmt);
  1016. if (act.pos() == 0) {
  1017. // { {(var x = e) :: C, E, F} :: S, H}
  1018. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  1019. return todo_.Spawn(
  1020. std::make_unique<ExpressionAction>(&definition.init()));
  1021. } else {
  1022. // { { v :: (x = []) :: C, E, F} :: S, H}
  1023. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1024. ASSIGN_OR_RETURN(
  1025. Nonnull<const Value*> v,
  1026. Convert(act.results()[0], &definition.pattern().static_type(),
  1027. stmt.source_loc()));
  1028. Nonnull<const Value*> p =
  1029. &cast<VariableDefinition>(stmt).pattern().value();
  1030. RuntimeScope matches(&heap_);
  1031. BindingMap generic_args;
  1032. CHECK(PatternMatch(p, v, stmt.source_loc(), &matches, generic_args))
  1033. << stmt.source_loc()
  1034. << ": internal error in variable definition, match failed";
  1035. todo_.MergeScope(std::move(matches));
  1036. return todo_.FinishAction();
  1037. }
  1038. }
  1039. case StatementKind::ExpressionStatement:
  1040. if (act.pos() == 0) {
  1041. // { {e :: C, E, F} :: S, H}
  1042. // -> { {e :: C, E, F} :: S, H}
  1043. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1044. &cast<ExpressionStatement>(stmt).expression()));
  1045. } else {
  1046. return todo_.FinishAction();
  1047. }
  1048. case StatementKind::Assign: {
  1049. const auto& assign = cast<Assign>(stmt);
  1050. if (act.pos() == 0) {
  1051. // { {(lv = e) :: C, E, F} :: S, H}
  1052. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1053. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  1054. } else if (act.pos() == 1) {
  1055. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1056. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1057. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  1058. } else {
  1059. // { { v :: (a = []) :: C, E, F} :: S, H}
  1060. // -> { { C, E, F} :: S, H(a := v)}
  1061. const auto& lval = cast<LValue>(*act.results()[0]);
  1062. ASSIGN_OR_RETURN(Nonnull<const Value*> rval,
  1063. Convert(act.results()[1], &assign.lhs().static_type(),
  1064. stmt.source_loc()));
  1065. RETURN_IF_ERROR(heap_.Write(lval.address(), rval, stmt.source_loc()));
  1066. return todo_.FinishAction();
  1067. }
  1068. }
  1069. case StatementKind::If:
  1070. if (act.pos() == 0) {
  1071. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1072. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1073. return todo_.Spawn(
  1074. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  1075. } else if (act.pos() == 1) {
  1076. ASSIGN_OR_RETURN(Nonnull<const Value*> condition,
  1077. Convert(act.results()[0], arena_->New<BoolType>(),
  1078. stmt.source_loc()));
  1079. if (cast<BoolValue>(*condition).value()) {
  1080. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1081. // S, H}
  1082. // -> { { then_stmt :: C, E, F } :: S, H}
  1083. return todo_.Spawn(
  1084. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  1085. } else if (cast<If>(stmt).else_block()) {
  1086. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1087. // S, H}
  1088. // -> { { else_stmt :: C, E, F } :: S, H}
  1089. return todo_.Spawn(
  1090. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  1091. } else {
  1092. return todo_.FinishAction();
  1093. }
  1094. } else {
  1095. return todo_.FinishAction();
  1096. }
  1097. case StatementKind::Return:
  1098. if (act.pos() == 0) {
  1099. // { {return e :: C, E, F} :: S, H}
  1100. // -> { {e :: return [] :: C, E, F} :: S, H}
  1101. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1102. &cast<Return>(stmt).expression()));
  1103. } else {
  1104. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1105. // -> { {v :: C', E', F'} :: S, H}
  1106. const FunctionDeclaration& function = cast<Return>(stmt).function();
  1107. ASSIGN_OR_RETURN(
  1108. Nonnull<const Value*> return_value,
  1109. Convert(act.results()[0], &function.return_term().static_type(),
  1110. stmt.source_loc()));
  1111. return todo_.UnwindPast(*function.body(), return_value);
  1112. }
  1113. case StatementKind::Continuation: {
  1114. CHECK(act.pos() == 0);
  1115. const auto& continuation = cast<Continuation>(stmt);
  1116. // Create a continuation object by creating a frame similar the
  1117. // way one is created in a function call.
  1118. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  1119. stack_fragments_.push_back(fragment);
  1120. todo_.InitializeFragment(*fragment, &continuation.body());
  1121. // Bind the continuation object to the continuation variable
  1122. todo_.Initialize(&cast<Continuation>(stmt),
  1123. arena_->New<ContinuationValue>(fragment));
  1124. return todo_.FinishAction();
  1125. }
  1126. case StatementKind::Run: {
  1127. auto& run = cast<Run>(stmt);
  1128. if (act.pos() == 0) {
  1129. // Evaluate the argument of the run statement.
  1130. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  1131. } else if (act.pos() == 1) {
  1132. // Push the continuation onto the current stack.
  1133. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  1134. } else {
  1135. return todo_.FinishAction();
  1136. }
  1137. }
  1138. case StatementKind::Await:
  1139. CHECK(act.pos() == 0);
  1140. return todo_.Suspend();
  1141. }
  1142. }
  1143. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  1144. Action& act = todo_.CurrentAction();
  1145. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  1146. if (trace_) {
  1147. llvm::outs() << "--- step declaration (" << decl.source_loc() << ") --->\n";
  1148. }
  1149. switch (decl.kind()) {
  1150. case DeclarationKind::VariableDeclaration: {
  1151. const auto& var_decl = cast<VariableDeclaration>(decl);
  1152. if (var_decl.has_initializer()) {
  1153. if (act.pos() == 0) {
  1154. return todo_.Spawn(
  1155. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  1156. } else {
  1157. todo_.Initialize(&var_decl.binding(), act.results()[0]);
  1158. return todo_.FinishAction();
  1159. }
  1160. } else {
  1161. return todo_.FinishAction();
  1162. }
  1163. }
  1164. case DeclarationKind::FunctionDeclaration:
  1165. case DeclarationKind::ClassDeclaration:
  1166. case DeclarationKind::ChoiceDeclaration:
  1167. case DeclarationKind::InterfaceDeclaration:
  1168. case DeclarationKind::ImplDeclaration:
  1169. // These declarations have no run-time effects.
  1170. return todo_.FinishAction();
  1171. }
  1172. }
  1173. // State transition.
  1174. auto Interpreter::Step() -> ErrorOr<Success> {
  1175. Action& act = todo_.CurrentAction();
  1176. switch (act.kind()) {
  1177. case Action::Kind::LValAction:
  1178. RETURN_IF_ERROR(StepLvalue());
  1179. break;
  1180. case Action::Kind::ExpressionAction:
  1181. RETURN_IF_ERROR(StepExp());
  1182. break;
  1183. case Action::Kind::PatternAction:
  1184. RETURN_IF_ERROR(StepPattern());
  1185. break;
  1186. case Action::Kind::StatementAction:
  1187. RETURN_IF_ERROR(StepStmt());
  1188. break;
  1189. case Action::Kind::DeclarationAction:
  1190. RETURN_IF_ERROR(StepDeclaration());
  1191. break;
  1192. case Action::Kind::ScopeAction:
  1193. FATAL() << "ScopeAction escaped ActionStack";
  1194. } // switch
  1195. return Success();
  1196. }
  1197. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  1198. -> ErrorOr<Success> {
  1199. if (trace_) {
  1200. PrintState(llvm::outs());
  1201. }
  1202. todo_.Start(std::move(action));
  1203. while (!todo_.IsEmpty()) {
  1204. RETURN_IF_ERROR(Step());
  1205. if (trace_) {
  1206. PrintState(llvm::outs());
  1207. }
  1208. }
  1209. return Success();
  1210. }
  1211. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena, bool trace)
  1212. -> ErrorOr<int> {
  1213. Interpreter interpreter(Phase::RunTime, arena, trace);
  1214. if (trace) {
  1215. llvm::outs() << "********** initializing globals **********\n";
  1216. }
  1217. for (Nonnull<Declaration*> declaration : ast.declarations) {
  1218. RETURN_IF_ERROR(interpreter.RunAllSteps(
  1219. std::make_unique<DeclarationAction>(declaration)));
  1220. }
  1221. if (trace) {
  1222. llvm::outs() << "********** calling main function **********\n";
  1223. }
  1224. RETURN_IF_ERROR(interpreter.RunAllSteps(
  1225. std::make_unique<ExpressionAction>(*ast.main_call)));
  1226. return cast<IntValue>(*interpreter.result()).value();
  1227. }
  1228. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena, bool trace)
  1229. -> ErrorOr<Nonnull<const Value*>> {
  1230. Interpreter interpreter(Phase::CompileTime, arena, trace);
  1231. RETURN_IF_ERROR(
  1232. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e)));
  1233. return interpreter.result();
  1234. }
  1235. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena, bool trace)
  1236. -> ErrorOr<Nonnull<const Value*>> {
  1237. Interpreter interpreter(Phase::CompileTime, arena, trace);
  1238. RETURN_IF_ERROR(interpreter.RunAllSteps(std::make_unique<PatternAction>(p)));
  1239. return interpreter.result();
  1240. }
  1241. } // namespace Carbon