interpreter.cpp 52 KB

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