interpreter.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  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 "explorer/interpreter/interpreter.h"
  5. #include <iterator>
  6. #include <map>
  7. #include <optional>
  8. #include <random>
  9. #include <utility>
  10. #include <variant>
  11. #include <vector>
  12. #include "common/check.h"
  13. #include "explorer/ast/declaration.h"
  14. #include "explorer/ast/expression.h"
  15. #include "explorer/common/arena.h"
  16. #include "explorer/common/error_builders.h"
  17. #include "explorer/interpreter/action.h"
  18. #include "explorer/interpreter/action_stack.h"
  19. #include "explorer/interpreter/stack.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/Support/Casting.h"
  22. #include "llvm/Support/Error.h"
  23. #include "llvm/Support/FormatVariadic.h"
  24. using llvm::cast;
  25. using llvm::dyn_cast;
  26. using llvm::isa;
  27. namespace Carbon {
  28. static std::mt19937 generator(12);
  29. // Constructs an ActionStack suitable for the specified phase.
  30. static auto MakeTodo(Phase phase, Nonnull<Heap*> heap) -> ActionStack {
  31. switch (phase) {
  32. case Phase::CompileTime:
  33. return ActionStack();
  34. case Phase::RunTime:
  35. return ActionStack(heap);
  36. }
  37. }
  38. // An Interpreter represents an instance of the Carbon abstract machine. It
  39. // manages the state of the abstract machine, and executes the steps of Actions
  40. // passed to it.
  41. class Interpreter {
  42. public:
  43. // Constructs an Interpreter which allocates values on `arena`, and prints
  44. // traces if `trace` is true. `phase` indicates whether it executes at
  45. // compile time or run time.
  46. Interpreter(Phase phase, Nonnull<Arena*> arena,
  47. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  48. : arena_(arena),
  49. heap_(arena),
  50. todo_(MakeTodo(phase, &heap_)),
  51. trace_stream_(trace_stream),
  52. phase_(phase) {}
  53. ~Interpreter();
  54. // Runs all the steps of `action`.
  55. // It's not safe to call `RunAllSteps()` or `result()` after an error.
  56. auto RunAllSteps(std::unique_ptr<Action> action) -> ErrorOr<Success>;
  57. // The result produced by the `action` argument of the most recent
  58. // RunAllSteps call. Cannot be called if `action` was an action that doesn't
  59. // produce results.
  60. auto result() const -> Nonnull<const Value*> { return todo_.result(); }
  61. private:
  62. auto Step() -> ErrorOr<Success>;
  63. // State transitions for expressions.
  64. auto StepExp() -> ErrorOr<Success>;
  65. // State transitions for lvalues.
  66. auto StepLvalue() -> ErrorOr<Success>;
  67. // State transitions for patterns.
  68. auto StepPattern() -> ErrorOr<Success>;
  69. // State transition for statements.
  70. auto StepStmt() -> ErrorOr<Success>;
  71. // State transition for declarations.
  72. auto StepDeclaration() -> ErrorOr<Success>;
  73. auto CreateStruct(const std::vector<FieldInitializer>& fields,
  74. const std::vector<Nonnull<const Value*>>& values)
  75. -> Nonnull<const Value*>;
  76. auto EvalPrim(Operator op, Nonnull<const Value*> static_type,
  77. const std::vector<Nonnull<const Value*>>& args,
  78. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  79. // Returns the result of converting `value` to type `destination_type`.
  80. auto Convert(Nonnull<const Value*> value,
  81. Nonnull<const Value*> destination_type,
  82. SourceLocation source_loc) -> ErrorOr<Nonnull<const Value*>>;
  83. // Evaluate an expression immediately, recursively.
  84. //
  85. // TODO: Stop using this.
  86. auto EvalExpRecursively(Nonnull<const Expression*> exp)
  87. -> ErrorOr<Nonnull<const Value*>>;
  88. // Evaluate an associated constant by evaluating its witness and looking
  89. // inside the impl for the corresponding value.
  90. //
  91. // TODO: This approach doesn't provide values that are known because they
  92. // appear in constraints:
  93. //
  94. // interface Iface { let N:! i32; }
  95. // fn PickType(N: i32) -> Type { return i32; }
  96. // fn F[T:! Iface where .N == 5](x: T) {
  97. // var x: PickType(T.N) = 0;
  98. // }
  99. //
  100. // ... will fail because we can't resolve T.N to 5 at compile time.
  101. auto EvalAssociatedConstant(Nonnull<const AssociatedConstant*> assoc,
  102. SourceLocation source_loc)
  103. -> ErrorOr<Nonnull<const Value*>>;
  104. // Instantiate a type by replacing all type variables that occur inside the
  105. // type by the current values of those variables.
  106. //
  107. // For example, suppose T=i32 and U=bool. Then
  108. // __Fn (Point(T)) -> Point(U)
  109. // becomes
  110. // __Fn (Point(i32)) -> Point(bool)
  111. auto InstantiateType(Nonnull<const Value*> type, SourceLocation source_loc)
  112. -> ErrorOr<Nonnull<const Value*>>;
  113. // Instantiate a set of bindings by replacing all type variables that occur
  114. // within it by the current values of those variables.
  115. auto InstantiateBindings(Nonnull<const Bindings*> bindings,
  116. SourceLocation source_loc)
  117. -> ErrorOr<Nonnull<const Bindings*>>;
  118. // Call the function `fun` with the given `arg` and the `witnesses`
  119. // for the function's impl bindings.
  120. auto CallFunction(const CallExpression& call, Nonnull<const Value*> fun,
  121. Nonnull<const Value*> arg, ImplWitnessMap&& witnesses)
  122. -> ErrorOr<Success>;
  123. void PrintState(llvm::raw_ostream& out);
  124. Phase phase() const { return phase_; }
  125. Nonnull<Arena*> arena_;
  126. Heap heap_;
  127. ActionStack todo_;
  128. // The underlying states of continuation values. All StackFragments created
  129. // during execution are tracked here, in order to safely deallocate the
  130. // contents of any non-completed continuations at the end of execution.
  131. std::vector<Nonnull<ContinuationValue::StackFragment*>> stack_fragments_;
  132. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream_;
  133. Phase phase_;
  134. };
  135. Interpreter::~Interpreter() {
  136. // Clean up any remaining suspended continuations.
  137. for (Nonnull<ContinuationValue::StackFragment*> fragment : stack_fragments_) {
  138. fragment->Clear();
  139. }
  140. }
  141. //
  142. // State Operations
  143. //
  144. void Interpreter::PrintState(llvm::raw_ostream& out) {
  145. out << "{\nstack: " << todo_;
  146. out << "\nmemory: " << heap_;
  147. out << "\n}\n";
  148. }
  149. auto Interpreter::EvalPrim(Operator op, Nonnull<const Value*> static_type,
  150. const std::vector<Nonnull<const Value*>>& args,
  151. SourceLocation source_loc)
  152. -> ErrorOr<Nonnull<const Value*>> {
  153. switch (op) {
  154. case Operator::Neg:
  155. return arena_->New<IntValue>(-cast<IntValue>(*args[0]).value());
  156. case Operator::Add:
  157. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() +
  158. cast<IntValue>(*args[1]).value());
  159. case Operator::Sub:
  160. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() -
  161. cast<IntValue>(*args[1]).value());
  162. case Operator::Mul:
  163. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() *
  164. cast<IntValue>(*args[1]).value());
  165. case Operator::Mod:
  166. return arena_->New<IntValue>(cast<IntValue>(*args[0]).value() %
  167. cast<IntValue>(*args[1]).value());
  168. case Operator::Not:
  169. return arena_->New<BoolValue>(!cast<BoolValue>(*args[0]).value());
  170. case Operator::And:
  171. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() &&
  172. cast<BoolValue>(*args[1]).value());
  173. case Operator::Or:
  174. return arena_->New<BoolValue>(cast<BoolValue>(*args[0]).value() ||
  175. cast<BoolValue>(*args[1]).value());
  176. case Operator::Ptr:
  177. return arena_->New<PointerType>(args[0]);
  178. case Operator::Deref:
  179. return heap_.Read(cast<PointerValue>(*args[0]).address(), source_loc);
  180. case Operator::AddressOf:
  181. return arena_->New<PointerValue>(cast<LValue>(*args[0]).address());
  182. case Operator::BitwiseAnd:
  183. // If & wasn't rewritten, it's being used to form a constraint.
  184. return &cast<TypeOfConstraintType>(static_type)->constraint_type();
  185. case Operator::As:
  186. case Operator::Eq:
  187. case Operator::BitwiseOr:
  188. case Operator::BitwiseXor:
  189. case Operator::BitShiftLeft:
  190. case Operator::BitShiftRight:
  191. case Operator::Complement:
  192. CARBON_FATAL() << "operator " << ToString(op)
  193. << " should always be rewritten";
  194. }
  195. }
  196. auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
  197. const std::vector<Nonnull<const Value*>>& values)
  198. -> Nonnull<const Value*> {
  199. CARBON_CHECK(fields.size() == values.size());
  200. std::vector<NamedValue> elements;
  201. for (size_t i = 0; i < fields.size(); ++i) {
  202. elements.push_back({.name = fields[i].name(), .value = values[i]});
  203. }
  204. return arena_->New<StructValue>(std::move(elements));
  205. }
  206. auto PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
  207. SourceLocation source_loc,
  208. std::optional<Nonnull<RuntimeScope*>> bindings,
  209. BindingMap& generic_args,
  210. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream,
  211. Nonnull<Arena*> arena) -> bool {
  212. if (trace_stream) {
  213. **trace_stream << "match pattern " << *p << "\nwith value " << *v << "\n";
  214. }
  215. switch (p->kind()) {
  216. case Value::Kind::BindingPlaceholderValue: {
  217. CARBON_CHECK(bindings.has_value());
  218. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  219. if (placeholder.value_node().has_value()) {
  220. (*bindings)->Initialize(*placeholder.value_node(), v);
  221. }
  222. return true;
  223. }
  224. case Value::Kind::AddrValue: {
  225. const auto& addr = cast<AddrValue>(*p);
  226. CARBON_CHECK(v->kind() == Value::Kind::LValue);
  227. const auto& lvalue = cast<LValue>(*v);
  228. return PatternMatch(
  229. &addr.pattern(), arena->New<PointerValue>(lvalue.address()),
  230. source_loc, bindings, generic_args, trace_stream, arena);
  231. }
  232. case Value::Kind::VariableType: {
  233. const auto& var_type = cast<VariableType>(*p);
  234. generic_args[&var_type.binding()] = v;
  235. return true;
  236. }
  237. case Value::Kind::TupleValue:
  238. switch (v->kind()) {
  239. case Value::Kind::TupleValue: {
  240. const auto& p_tup = cast<TupleValue>(*p);
  241. const auto& v_tup = cast<TupleValue>(*v);
  242. CARBON_CHECK(p_tup.elements().size() == v_tup.elements().size());
  243. for (size_t i = 0; i < p_tup.elements().size(); ++i) {
  244. if (!PatternMatch(p_tup.elements()[i], v_tup.elements()[i],
  245. source_loc, bindings, generic_args, trace_stream,
  246. arena)) {
  247. return false;
  248. }
  249. } // for
  250. return true;
  251. }
  252. case Value::Kind::UninitializedValue: {
  253. const auto& p_tup = cast<TupleValue>(*p);
  254. for (auto& ele : p_tup.elements()) {
  255. if (!PatternMatch(ele, arena->New<UninitializedValue>(ele),
  256. source_loc, bindings, generic_args, trace_stream,
  257. arena)) {
  258. return false;
  259. }
  260. }
  261. return true;
  262. }
  263. default:
  264. CARBON_FATAL() << "expected a tuple value in pattern, not " << *v;
  265. }
  266. case Value::Kind::StructValue: {
  267. const auto& p_struct = cast<StructValue>(*p);
  268. const auto& v_struct = cast<StructValue>(*v);
  269. CARBON_CHECK(p_struct.elements().size() == v_struct.elements().size());
  270. for (size_t i = 0; i < p_struct.elements().size(); ++i) {
  271. CARBON_CHECK(p_struct.elements()[i].name ==
  272. v_struct.elements()[i].name);
  273. if (!PatternMatch(p_struct.elements()[i].value,
  274. v_struct.elements()[i].value, source_loc, bindings,
  275. generic_args, trace_stream, arena)) {
  276. return false;
  277. }
  278. }
  279. return true;
  280. }
  281. case Value::Kind::AlternativeValue:
  282. switch (v->kind()) {
  283. case Value::Kind::AlternativeValue: {
  284. const auto& p_alt = cast<AlternativeValue>(*p);
  285. const auto& v_alt = cast<AlternativeValue>(*v);
  286. if (p_alt.choice_name() != v_alt.choice_name() ||
  287. p_alt.alt_name() != v_alt.alt_name()) {
  288. return false;
  289. }
  290. return PatternMatch(&p_alt.argument(), &v_alt.argument(), source_loc,
  291. bindings, generic_args, trace_stream, arena);
  292. }
  293. default:
  294. CARBON_FATAL() << "expected a choice alternative in pattern, not "
  295. << *v;
  296. }
  297. case Value::Kind::UninitializedValue:
  298. CARBON_FATAL() << "uninitialized value is not allowed in pattern " << *v;
  299. case Value::Kind::FunctionType:
  300. switch (v->kind()) {
  301. case Value::Kind::FunctionType: {
  302. const auto& p_fn = cast<FunctionType>(*p);
  303. const auto& v_fn = cast<FunctionType>(*v);
  304. if (!PatternMatch(&p_fn.parameters(), &v_fn.parameters(), source_loc,
  305. bindings, generic_args, trace_stream, arena)) {
  306. return false;
  307. }
  308. if (!PatternMatch(&p_fn.return_type(), &v_fn.return_type(),
  309. source_loc, bindings, generic_args, trace_stream,
  310. arena)) {
  311. return false;
  312. }
  313. return true;
  314. }
  315. default:
  316. return false;
  317. }
  318. case Value::Kind::AutoType:
  319. // `auto` matches any type, without binding any new names. We rely
  320. // on the typechecker to ensure that `v` is a type.
  321. return true;
  322. default:
  323. return ValueEqual(p, v, std::nullopt);
  324. }
  325. }
  326. auto Interpreter::StepLvalue() -> ErrorOr<Success> {
  327. Action& act = todo_.CurrentAction();
  328. const Expression& exp = cast<LValAction>(act).expression();
  329. if (trace_stream_) {
  330. **trace_stream_ << "--- step lvalue " << exp << " ." << act.pos() << "."
  331. << " (" << exp.source_loc() << ") --->\n";
  332. }
  333. switch (exp.kind()) {
  334. case ExpressionKind::IdentifierExpression: {
  335. // { {x :: C, E, F} :: S, H}
  336. // -> { {E(x) :: C, E, F} :: S, H}
  337. CARBON_ASSIGN_OR_RETURN(
  338. Nonnull<const Value*> value,
  339. todo_.ValueOfNode(cast<IdentifierExpression>(exp).value_node(),
  340. exp.source_loc()));
  341. CARBON_CHECK(isa<LValue>(value)) << *value;
  342. return todo_.FinishAction(value);
  343. }
  344. case ExpressionKind::SimpleMemberAccessExpression: {
  345. if (act.pos() == 0) {
  346. // { {e.f :: C, E, F} :: S, H}
  347. // -> { e :: [].f :: C, E, F} :: S, H}
  348. return todo_.Spawn(std::make_unique<LValAction>(
  349. &cast<SimpleMemberAccessExpression>(exp).object()));
  350. } else {
  351. // { v :: [].f :: C, E, F} :: S, H}
  352. // -> { { &v.f :: C, E, F} :: S, H }
  353. Address object = cast<LValue>(*act.results()[0]).address();
  354. Address member = object.SubobjectAddress(
  355. cast<SimpleMemberAccessExpression>(exp).member());
  356. return todo_.FinishAction(arena_->New<LValue>(member));
  357. }
  358. }
  359. case ExpressionKind::CompoundMemberAccessExpression: {
  360. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  361. if (act.pos() == 0) {
  362. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  363. } else {
  364. CARBON_CHECK(!access.member().interface().has_value())
  365. << "unexpected lvalue interface member";
  366. CARBON_ASSIGN_OR_RETURN(
  367. Nonnull<const Value*> val,
  368. Convert(act.results()[0], *access.member().base_type(),
  369. exp.source_loc()));
  370. Address object = cast<LValue>(*val).address();
  371. Address field = object.SubobjectAddress(access.member().member());
  372. return todo_.FinishAction(arena_->New<LValue>(field));
  373. }
  374. }
  375. case ExpressionKind::IndexExpression: {
  376. if (act.pos() == 0) {
  377. // { {e[i] :: C, E, F} :: S, H}
  378. // -> { e :: [][i] :: C, E, F} :: S, H}
  379. return todo_.Spawn(
  380. std::make_unique<LValAction>(&cast<IndexExpression>(exp).object()));
  381. } else if (act.pos() == 1) {
  382. return todo_.Spawn(std::make_unique<ExpressionAction>(
  383. &cast<IndexExpression>(exp).offset()));
  384. } else {
  385. // { v :: [][i] :: C, E, F} :: S, H}
  386. // -> { { &v[i] :: C, E, F} :: S, H }
  387. Address object = cast<LValue>(*act.results()[0]).address();
  388. // TODO: Add support to `Member` for naming tuple fields rather than
  389. // pretending we have struct fields with numerical names.
  390. std::string f =
  391. std::to_string(cast<IntValue>(*act.results()[1]).value());
  392. auto* tuple_field_as_struct_field =
  393. arena_->New<NamedValue>(NamedValue{f, &exp.static_type()});
  394. Address field =
  395. object.SubobjectAddress(Member(tuple_field_as_struct_field));
  396. return todo_.FinishAction(arena_->New<LValue>(field));
  397. }
  398. }
  399. case ExpressionKind::OperatorExpression: {
  400. const auto& op = cast<OperatorExpression>(exp);
  401. if (auto rewrite = op.rewritten_form()) {
  402. return todo_.ReplaceWith(std::make_unique<LValAction>(*rewrite));
  403. }
  404. if (op.op() != Operator::Deref) {
  405. CARBON_FATAL()
  406. << "Can't treat primitive operator expression as lvalue: " << exp;
  407. }
  408. if (act.pos() == 0) {
  409. return todo_.Spawn(
  410. std::make_unique<ExpressionAction>(op.arguments()[0]));
  411. } else {
  412. const auto& res = cast<PointerValue>(*act.results()[0]);
  413. return todo_.FinishAction(arena_->New<LValue>(res.address()));
  414. }
  415. break;
  416. }
  417. case ExpressionKind::TupleLiteral:
  418. case ExpressionKind::StructLiteral:
  419. case ExpressionKind::StructTypeLiteral:
  420. case ExpressionKind::IntLiteral:
  421. case ExpressionKind::BoolLiteral:
  422. case ExpressionKind::CallExpression:
  423. case ExpressionKind::IntTypeLiteral:
  424. case ExpressionKind::BoolTypeLiteral:
  425. case ExpressionKind::TypeTypeLiteral:
  426. case ExpressionKind::FunctionTypeLiteral:
  427. case ExpressionKind::ContinuationTypeLiteral:
  428. case ExpressionKind::StringLiteral:
  429. case ExpressionKind::StringTypeLiteral:
  430. case ExpressionKind::ValueLiteral:
  431. case ExpressionKind::IntrinsicExpression:
  432. case ExpressionKind::IfExpression:
  433. case ExpressionKind::WhereExpression:
  434. case ExpressionKind::DotSelfExpression:
  435. case ExpressionKind::ArrayTypeLiteral:
  436. case ExpressionKind::InstantiateImpl:
  437. CARBON_FATAL() << "Can't treat expression as lvalue: " << exp;
  438. case ExpressionKind::UnimplementedExpression:
  439. CARBON_FATAL() << "Unimplemented: " << exp;
  440. }
  441. }
  442. auto Interpreter::EvalExpRecursively(Nonnull<const Expression*> exp)
  443. -> ErrorOr<Nonnull<const Value*>> {
  444. if (trace_stream_) {
  445. **trace_stream_ << "--- recursive eval of " << *exp << "\n";
  446. PrintState(**trace_stream_);
  447. }
  448. todo_.BeginRecursiveAction();
  449. CARBON_RETURN_IF_ERROR(todo_.Spawn(std::make_unique<ExpressionAction>(exp)));
  450. // Note that the only `RecursiveAction` we can encounter here is our own --
  451. // if a nested action begins a recursive action, it will run until that
  452. // action is finished and popped off the queue before returning to us.
  453. while (!isa<RecursiveAction>(todo_.CurrentAction())) {
  454. CARBON_RETURN_IF_ERROR(Step());
  455. if (trace_stream_) {
  456. PrintState(**trace_stream_);
  457. }
  458. }
  459. if (trace_stream_) {
  460. **trace_stream_ << "--- recursive eval done\n";
  461. }
  462. Nonnull<const Value*> result =
  463. cast<RecursiveAction>(todo_.CurrentAction()).results()[0];
  464. CARBON_RETURN_IF_ERROR(todo_.FinishAction());
  465. return result;
  466. }
  467. auto Interpreter::EvalAssociatedConstant(
  468. Nonnull<const AssociatedConstant*> assoc, SourceLocation source_loc)
  469. -> ErrorOr<Nonnull<const Value*>> {
  470. // Find the witness.
  471. Nonnull<const Value*> witness = &assoc->witness();
  472. if (auto* sym = dyn_cast<SymbolicWitness>(witness)) {
  473. CARBON_ASSIGN_OR_RETURN(witness,
  474. EvalExpRecursively(&sym->impl_expression()));
  475. }
  476. if (!isa<ImplWitness>(witness)) {
  477. CARBON_CHECK(phase() == Phase::CompileTime)
  478. << "symbolic witnesses should only be formed at compile time";
  479. return CompilationError(source_loc)
  480. << "value of associated constant " << *assoc << " is not known";
  481. }
  482. auto& impl_witness = cast<ImplWitness>(*witness);
  483. Nonnull<const ConstraintType*> constraint =
  484. impl_witness.declaration().constraint_type();
  485. Nonnull<const Value*> expected = arena_->New<AssociatedConstant>(
  486. &constraint->self_binding()->value(), &assoc->interface(),
  487. &assoc->constant(), &impl_witness);
  488. std::optional<Nonnull<const Value*>> result;
  489. constraint->VisitEqualValues(expected,
  490. [&](Nonnull<const Value*> equal_value) {
  491. // TODO: The value might depend on the
  492. // parameters of the impl. We need to
  493. // substitute impl_witness.type_args() into the
  494. // value.
  495. if (isa<AssociatedConstant>(equal_value)) {
  496. return true;
  497. }
  498. // TODO: This makes an arbitrary choice if
  499. // there's more than one equal value. It's not
  500. // clear how to handle that case.
  501. result = equal_value;
  502. return false;
  503. });
  504. if (!result) {
  505. CARBON_FATAL() << impl_witness.declaration()
  506. << " is missing value for associated constant " << *assoc;
  507. }
  508. return *result;
  509. }
  510. auto Interpreter::InstantiateType(Nonnull<const Value*> type,
  511. SourceLocation source_loc)
  512. -> ErrorOr<Nonnull<const Value*>> {
  513. switch (type->kind()) {
  514. case Value::Kind::VariableType: {
  515. CARBON_ASSIGN_OR_RETURN(
  516. Nonnull<const Value*> value,
  517. todo_.ValueOfNode(&cast<VariableType>(*type).binding(), source_loc));
  518. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  519. CARBON_ASSIGN_OR_RETURN(value,
  520. heap_.Read(lvalue->address(), source_loc));
  521. }
  522. return value;
  523. }
  524. case Value::Kind::NominalClassType: {
  525. const auto& class_type = cast<NominalClassType>(*type);
  526. CARBON_ASSIGN_OR_RETURN(
  527. Nonnull<const Bindings*> bindings,
  528. InstantiateBindings(&class_type.bindings(), source_loc));
  529. return arena_->New<NominalClassType>(&class_type.declaration(), bindings);
  530. }
  531. case Value::Kind::AssociatedConstant: {
  532. CARBON_ASSIGN_OR_RETURN(
  533. Nonnull<const Value*> type_value,
  534. EvalAssociatedConstant(cast<AssociatedConstant>(type), source_loc));
  535. return InstantiateType(type_value, source_loc);
  536. }
  537. default:
  538. return type;
  539. }
  540. }
  541. auto Interpreter::InstantiateBindings(Nonnull<const Bindings*> bindings,
  542. SourceLocation source_loc)
  543. -> ErrorOr<Nonnull<const Bindings*>> {
  544. BindingMap args = bindings->args();
  545. for (auto& [var, arg] : args) {
  546. CARBON_ASSIGN_OR_RETURN(arg, InstantiateType(arg, source_loc));
  547. }
  548. ImplWitnessMap witnesses = bindings->witnesses();
  549. for (auto& [bind, witness] : witnesses) {
  550. if (auto* sym = dyn_cast<SymbolicWitness>(witness)) {
  551. CARBON_ASSIGN_OR_RETURN(witness,
  552. EvalExpRecursively(&sym->impl_expression()));
  553. }
  554. }
  555. if (args == bindings->args() && witnesses == bindings->witnesses()) {
  556. return bindings;
  557. }
  558. return arena_->New<Bindings>(std::move(args), std::move(witnesses));
  559. }
  560. auto Interpreter::Convert(Nonnull<const Value*> value,
  561. Nonnull<const Value*> destination_type,
  562. SourceLocation source_loc)
  563. -> ErrorOr<Nonnull<const Value*>> {
  564. switch (value->kind()) {
  565. case Value::Kind::IntValue:
  566. case Value::Kind::FunctionValue:
  567. case Value::Kind::BoundMethodValue:
  568. case Value::Kind::PointerValue:
  569. case Value::Kind::LValue:
  570. case Value::Kind::BoolValue:
  571. case Value::Kind::NominalClassValue:
  572. case Value::Kind::AlternativeValue:
  573. case Value::Kind::UninitializedValue:
  574. case Value::Kind::IntType:
  575. case Value::Kind::BoolType:
  576. case Value::Kind::TypeType:
  577. case Value::Kind::FunctionType:
  578. case Value::Kind::PointerType:
  579. case Value::Kind::AutoType:
  580. case Value::Kind::NominalClassType:
  581. case Value::Kind::InterfaceType:
  582. case Value::Kind::ConstraintType:
  583. case Value::Kind::ImplWitness:
  584. case Value::Kind::SymbolicWitness:
  585. case Value::Kind::ParameterizedEntityName:
  586. case Value::Kind::ChoiceType:
  587. case Value::Kind::ContinuationType:
  588. case Value::Kind::VariableType:
  589. case Value::Kind::BindingPlaceholderValue:
  590. case Value::Kind::AddrValue:
  591. case Value::Kind::AlternativeConstructorValue:
  592. case Value::Kind::ContinuationValue:
  593. case Value::Kind::StringType:
  594. case Value::Kind::StringValue:
  595. case Value::Kind::TypeOfClassType:
  596. case Value::Kind::TypeOfInterfaceType:
  597. case Value::Kind::TypeOfConstraintType:
  598. case Value::Kind::TypeOfChoiceType:
  599. case Value::Kind::TypeOfParameterizedEntityName:
  600. case Value::Kind::TypeOfMemberName:
  601. case Value::Kind::StaticArrayType:
  602. case Value::Kind::MemberName:
  603. // TODO: add `CARBON_CHECK(TypeEqual(type, value->dynamic_type()))`, once
  604. // we have Value::dynamic_type.
  605. return value;
  606. case Value::Kind::StructValue: {
  607. const auto& struct_val = cast<StructValue>(*value);
  608. switch (destination_type->kind()) {
  609. case Value::Kind::StructType: {
  610. const auto& destination_struct_type =
  611. cast<StructType>(*destination_type);
  612. std::vector<NamedValue> new_elements;
  613. for (const auto& [field_name, field_type] :
  614. destination_struct_type.fields()) {
  615. std::optional<Nonnull<const Value*>> old_value =
  616. struct_val.FindField(field_name);
  617. CARBON_ASSIGN_OR_RETURN(
  618. Nonnull<const Value*> val,
  619. Convert(*old_value, field_type, source_loc));
  620. new_elements.push_back({.name = field_name, .value = val});
  621. }
  622. return arena_->New<StructValue>(std::move(new_elements));
  623. }
  624. case Value::Kind::NominalClassType: {
  625. // Instantiate the `destination_type` to obtain the runtime
  626. // type of the object.
  627. CARBON_ASSIGN_OR_RETURN(
  628. Nonnull<const Value*> inst_dest,
  629. InstantiateType(destination_type, source_loc));
  630. return arena_->New<NominalClassValue>(inst_dest, value);
  631. }
  632. default:
  633. CARBON_FATAL() << "Can't convert value " << *value << " to type "
  634. << *destination_type;
  635. }
  636. }
  637. case Value::Kind::StructType: {
  638. // The value `{}` has kind `StructType` not `StructValue`. This value can
  639. // be converted to an empty class type.
  640. if (auto* destination_class_type =
  641. dyn_cast<NominalClassType>(destination_type)) {
  642. CARBON_CHECK(cast<StructType>(*value).fields().empty())
  643. << "only an empty struct type value converts to class type";
  644. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> inst_dest,
  645. InstantiateType(destination_type, source_loc));
  646. return arena_->New<NominalClassValue>(inst_dest, value);
  647. }
  648. return value;
  649. }
  650. case Value::Kind::TupleValue: {
  651. const auto& tuple = cast<TupleValue>(value);
  652. std::vector<Nonnull<const Value*>> destination_element_types;
  653. switch (destination_type->kind()) {
  654. case Value::Kind::TupleValue:
  655. destination_element_types =
  656. cast<TupleValue>(destination_type)->elements();
  657. break;
  658. case Value::Kind::StaticArrayType: {
  659. const auto& array_type = cast<StaticArrayType>(*destination_type);
  660. destination_element_types.resize(array_type.size(),
  661. &array_type.element_type());
  662. break;
  663. }
  664. default:
  665. CARBON_FATAL() << "Can't convert value " << *value << " to type "
  666. << *destination_type;
  667. }
  668. CARBON_CHECK(tuple->elements().size() ==
  669. destination_element_types.size());
  670. std::vector<Nonnull<const Value*>> new_elements;
  671. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  672. CARBON_ASSIGN_OR_RETURN(
  673. Nonnull<const Value*> val,
  674. Convert(tuple->elements()[i], destination_element_types[i],
  675. source_loc));
  676. new_elements.push_back(val);
  677. }
  678. return arena_->New<TupleValue>(std::move(new_elements));
  679. }
  680. case Value::Kind::AssociatedConstant: {
  681. CARBON_ASSIGN_OR_RETURN(
  682. Nonnull<const Value*> value,
  683. EvalAssociatedConstant(cast<AssociatedConstant>(value), source_loc));
  684. return Convert(value, destination_type, source_loc);
  685. }
  686. }
  687. }
  688. auto Interpreter::CallFunction(const CallExpression& call,
  689. Nonnull<const Value*> fun,
  690. Nonnull<const Value*> arg,
  691. ImplWitnessMap&& witnesses) -> ErrorOr<Success> {
  692. if (trace_stream_) {
  693. **trace_stream_ << "calling function: " << *fun << "\n";
  694. }
  695. switch (fun->kind()) {
  696. case Value::Kind::AlternativeConstructorValue: {
  697. const auto& alt = cast<AlternativeConstructorValue>(*fun);
  698. return todo_.FinishAction(arena_->New<AlternativeValue>(
  699. alt.alt_name(), alt.choice_name(), arg));
  700. }
  701. case Value::Kind::FunctionValue: {
  702. const FunctionValue& fun_val = cast<FunctionValue>(*fun);
  703. const FunctionDeclaration& function = fun_val.declaration();
  704. RuntimeScope binding_scope(&heap_);
  705. // Bring the class type arguments into scope.
  706. for (const auto& [bind, val] : fun_val.type_args()) {
  707. binding_scope.Initialize(bind, val);
  708. }
  709. // Bring the deduced type arguments into scope.
  710. for (const auto& [bind, val] : call.deduced_args()) {
  711. binding_scope.Initialize(bind, val);
  712. }
  713. // Bring the impl witness tables into scope.
  714. for (const auto& [impl_bind, witness] : witnesses) {
  715. binding_scope.Initialize(impl_bind, witness);
  716. }
  717. for (const auto& [impl_bind, witness] : fun_val.witnesses()) {
  718. binding_scope.Initialize(impl_bind, witness);
  719. }
  720. // Enter the binding scope to make any deduced arguments visible before
  721. // we resolve the parameter type.
  722. todo_.CurrentAction().StartScope(std::move(binding_scope));
  723. CARBON_ASSIGN_OR_RETURN(
  724. Nonnull<const Value*> converted_args,
  725. Convert(arg, &function.param_pattern().static_type(),
  726. call.source_loc()));
  727. RuntimeScope function_scope(&heap_);
  728. BindingMap generic_args;
  729. CARBON_CHECK(PatternMatch(
  730. &function.param_pattern().value(), converted_args, call.source_loc(),
  731. &function_scope, generic_args, trace_stream_, this->arena_));
  732. CARBON_CHECK(function.body().has_value())
  733. << "Calling a function that's missing a body";
  734. return todo_.Spawn(std::make_unique<StatementAction>(*function.body()),
  735. std::move(function_scope));
  736. }
  737. case Value::Kind::BoundMethodValue: {
  738. const auto& m = cast<BoundMethodValue>(*fun);
  739. const FunctionDeclaration& method = m.declaration();
  740. CARBON_CHECK(method.is_method());
  741. CARBON_ASSIGN_OR_RETURN(
  742. Nonnull<const Value*> converted_args,
  743. Convert(arg, &method.param_pattern().static_type(),
  744. call.source_loc()));
  745. RuntimeScope method_scope(&heap_);
  746. BindingMap generic_args;
  747. // Bind the receiver to the `me` parameter.
  748. CARBON_CHECK(PatternMatch(&method.me_pattern().value(), m.receiver(),
  749. call.source_loc(), &method_scope, generic_args,
  750. trace_stream_, this->arena_));
  751. // Bind the arguments to the parameters.
  752. CARBON_CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  753. call.source_loc(), &method_scope, generic_args,
  754. trace_stream_, this->arena_));
  755. // Bring the class type arguments into scope.
  756. for (const auto& [bind, val] : m.type_args()) {
  757. method_scope.Initialize(bind->original(), val);
  758. }
  759. // Bring the deduced type arguments into scope.
  760. for (const auto& [bind, val] : call.deduced_args()) {
  761. method_scope.Initialize(bind->original(), val);
  762. }
  763. // Bring the impl witness tables into scope.
  764. for (const auto& [impl_bind, witness] : witnesses) {
  765. method_scope.Initialize(impl_bind->original(), witness);
  766. }
  767. for (const auto& [impl_bind, witness] : m.witnesses()) {
  768. method_scope.Initialize(impl_bind->original(), witness);
  769. }
  770. CARBON_CHECK(method.body().has_value())
  771. << "Calling a method that's missing a body";
  772. return todo_.Spawn(std::make_unique<StatementAction>(*method.body()),
  773. std::move(method_scope));
  774. }
  775. case Value::Kind::ParameterizedEntityName: {
  776. const auto& name = cast<ParameterizedEntityName>(*fun);
  777. const Declaration& decl = name.declaration();
  778. RuntimeScope params_scope(&heap_);
  779. BindingMap generic_args;
  780. CARBON_CHECK(PatternMatch(&name.params().value(), arg, call.source_loc(),
  781. &params_scope, generic_args, trace_stream_,
  782. this->arena_));
  783. Nonnull<const Bindings*> bindings =
  784. arena_->New<Bindings>(std::move(generic_args), std::move(witnesses));
  785. switch (decl.kind()) {
  786. case DeclarationKind::ClassDeclaration:
  787. return todo_.FinishAction(arena_->New<NominalClassType>(
  788. &cast<ClassDeclaration>(decl), bindings));
  789. case DeclarationKind::InterfaceDeclaration:
  790. return todo_.FinishAction(arena_->New<InterfaceType>(
  791. &cast<InterfaceDeclaration>(decl), bindings));
  792. default:
  793. CARBON_FATAL() << "unknown kind of ParameterizedEntityName " << decl;
  794. }
  795. }
  796. default:
  797. return RuntimeError(call.source_loc())
  798. << "in call, expected a function, not " << *fun;
  799. }
  800. }
  801. auto Interpreter::StepExp() -> ErrorOr<Success> {
  802. Action& act = todo_.CurrentAction();
  803. const Expression& exp = cast<ExpressionAction>(act).expression();
  804. if (trace_stream_) {
  805. **trace_stream_ << "--- step exp " << exp << " ." << act.pos() << "."
  806. << " (" << exp.source_loc() << ") --->\n";
  807. }
  808. switch (exp.kind()) {
  809. case ExpressionKind::InstantiateImpl: {
  810. const InstantiateImpl& inst_impl = cast<InstantiateImpl>(exp);
  811. if (act.pos() == 0) {
  812. return todo_.Spawn(
  813. std::make_unique<ExpressionAction>(inst_impl.generic_impl()));
  814. }
  815. if (act.pos() == 1 && isa<SymbolicWitness>(act.results()[0])) {
  816. return todo_.FinishAction(arena_->New<SymbolicWitness>(&exp));
  817. }
  818. if (act.pos() - 1 < int(inst_impl.impls().size())) {
  819. auto iter = inst_impl.impls().begin();
  820. std::advance(iter, act.pos() - 1);
  821. return todo_.Spawn(std::make_unique<ExpressionAction>(iter->second));
  822. } else {
  823. Nonnull<const ImplWitness*> generic_witness =
  824. cast<ImplWitness>(act.results()[0]);
  825. ImplWitnessMap witnesses;
  826. int i = 0;
  827. for (const auto& [impl_bind, impl_exp] : inst_impl.impls()) {
  828. witnesses[impl_bind] = cast<Witness>(act.results()[i + 1]);
  829. ++i;
  830. }
  831. return todo_.FinishAction(arena_->New<ImplWitness>(
  832. &generic_witness->declaration(),
  833. arena_->New<Bindings>(inst_impl.type_args(),
  834. std::move(witnesses))));
  835. }
  836. }
  837. case ExpressionKind::IndexExpression: {
  838. if (act.pos() == 0) {
  839. // { { e[i] :: C, E, F} :: S, H}
  840. // -> { { e :: [][i] :: C, E, F} :: S, H}
  841. return todo_.Spawn(std::make_unique<ExpressionAction>(
  842. &cast<IndexExpression>(exp).object()));
  843. } else if (act.pos() == 1) {
  844. if (isa<SymbolicWitness>(act.results()[0])) {
  845. return todo_.FinishAction(arena_->New<SymbolicWitness>(&exp));
  846. }
  847. return todo_.Spawn(std::make_unique<ExpressionAction>(
  848. &cast<IndexExpression>(exp).offset()));
  849. } else {
  850. // { { v :: [][i] :: C, E, F} :: S, H}
  851. // -> { { v_i :: C, E, F} : S, H}
  852. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  853. int i = cast<IntValue>(*act.results()[1]).value();
  854. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  855. return RuntimeError(exp.source_loc())
  856. << "index " << i << " out of range in " << tuple;
  857. }
  858. return todo_.FinishAction(tuple.elements()[i]);
  859. }
  860. }
  861. case ExpressionKind::TupleLiteral: {
  862. if (act.pos() <
  863. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  864. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  865. // H}
  866. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  867. // H}
  868. return todo_.Spawn(std::make_unique<ExpressionAction>(
  869. cast<TupleLiteral>(exp).fields()[act.pos()]));
  870. } else {
  871. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  872. }
  873. }
  874. case ExpressionKind::StructLiteral: {
  875. const auto& literal = cast<StructLiteral>(exp);
  876. if (act.pos() < static_cast<int>(literal.fields().size())) {
  877. return todo_.Spawn(std::make_unique<ExpressionAction>(
  878. &literal.fields()[act.pos()].expression()));
  879. } else {
  880. return todo_.FinishAction(
  881. CreateStruct(literal.fields(), act.results()));
  882. }
  883. }
  884. case ExpressionKind::StructTypeLiteral: {
  885. const auto& struct_type = cast<StructTypeLiteral>(exp);
  886. if (act.pos() < static_cast<int>(struct_type.fields().size())) {
  887. return todo_.Spawn(std::make_unique<ExpressionAction>(
  888. &struct_type.fields()[act.pos()].expression()));
  889. } else {
  890. std::vector<NamedValue> fields;
  891. for (size_t i = 0; i < struct_type.fields().size(); ++i) {
  892. fields.push_back({struct_type.fields()[i].name(), act.results()[i]});
  893. }
  894. return todo_.FinishAction(arena_->New<StructType>(std::move(fields)));
  895. }
  896. }
  897. case ExpressionKind::SimpleMemberAccessExpression: {
  898. const auto& access = cast<SimpleMemberAccessExpression>(exp);
  899. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  900. if (act.pos() == 0) {
  901. // First, evaluate the first operand.
  902. if (access.is_field_addr_me_method()) {
  903. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  904. } else {
  905. return todo_.Spawn(
  906. std::make_unique<ExpressionAction>(&access.object()));
  907. }
  908. } else if (act.pos() == 1 && access.impl().has_value() &&
  909. !forming_member_name) {
  910. // Next, if we're accessing an interface member, evaluate the `impl`
  911. // expression to find the corresponding witness.
  912. return todo_.Spawn(
  913. std::make_unique<ExpressionAction>(access.impl().value()));
  914. } else {
  915. // Finally, produce the result.
  916. std::optional<Nonnull<const InterfaceType*>> found_in_interface =
  917. access.found_in_interface();
  918. if (found_in_interface) {
  919. CARBON_ASSIGN_OR_RETURN(
  920. Nonnull<const Value*> instantiated,
  921. InstantiateType(*found_in_interface, exp.source_loc()));
  922. found_in_interface = cast<InterfaceType>(instantiated);
  923. }
  924. if (const auto* member_name_type =
  925. dyn_cast<TypeOfMemberName>(&access.static_type())) {
  926. // The result is a member name, such as in `Type.field_name`. Form a
  927. // suitable member name value.
  928. CARBON_CHECK(phase() == Phase::CompileTime)
  929. << "should not form MemberNames at runtime";
  930. std::optional<const Value*> type_result;
  931. if (!isa<InterfaceType, ConstraintType>(act.results()[0])) {
  932. type_result = act.results()[0];
  933. }
  934. MemberName* member_name = arena_->New<MemberName>(
  935. type_result, found_in_interface, member_name_type->member());
  936. return todo_.FinishAction(member_name);
  937. } else {
  938. // The result is the value of the named field, such as in
  939. // `value.field_name`. Extract the value within the given object.
  940. std::optional<Nonnull<const Witness*>> witness;
  941. if (access.impl().has_value()) {
  942. witness = cast<Witness>(act.results()[1]);
  943. }
  944. FieldPath::Component member(access.member(), found_in_interface,
  945. witness);
  946. const Value* aggregate;
  947. if (const auto* lvalue = dyn_cast<LValue>(act.results()[0])) {
  948. CARBON_ASSIGN_OR_RETURN(
  949. aggregate,
  950. this->heap_.Read(lvalue->address(), exp.source_loc()));
  951. } else {
  952. aggregate = act.results()[0];
  953. }
  954. CARBON_ASSIGN_OR_RETURN(
  955. Nonnull<const Value*> member_value,
  956. aggregate->GetMember(arena_, FieldPath(member), exp.source_loc(),
  957. act.results()[0]));
  958. return todo_.FinishAction(member_value);
  959. }
  960. }
  961. }
  962. case ExpressionKind::CompoundMemberAccessExpression: {
  963. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  964. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  965. if (act.pos() == 0) {
  966. // First, evaluate the first operand.
  967. return todo_.Spawn(
  968. std::make_unique<ExpressionAction>(&access.object()));
  969. } else if (act.pos() == 1 && access.impl().has_value() &&
  970. !forming_member_name) {
  971. // Next, if we're accessing an interface member, evaluate the `impl`
  972. // expression to find the corresponding witness.
  973. return todo_.Spawn(
  974. std::make_unique<ExpressionAction>(access.impl().value()));
  975. } else {
  976. // Finally, produce the result.
  977. std::optional<Nonnull<const InterfaceType*>> found_in_interface =
  978. access.member().interface();
  979. if (found_in_interface) {
  980. CARBON_ASSIGN_OR_RETURN(
  981. Nonnull<const Value*> instantiated,
  982. InstantiateType(*found_in_interface, exp.source_loc()));
  983. found_in_interface = cast<InterfaceType>(instantiated);
  984. }
  985. if (forming_member_name) {
  986. // If we're forming a member name, we must be in the outer evaluation
  987. // in `Type.(Interface.method)`. Produce the same method name with
  988. // its `type` field set.
  989. CARBON_CHECK(phase() == Phase::CompileTime)
  990. << "should not form MemberNames at runtime";
  991. CARBON_CHECK(!access.member().base_type().has_value())
  992. << "compound member access forming a member name should be "
  993. "performing impl lookup";
  994. auto* member_name = arena_->New<MemberName>(
  995. act.results()[0], found_in_interface, access.member().member());
  996. return todo_.FinishAction(member_name);
  997. } else {
  998. // Access the object to find the named member.
  999. Nonnull<const Value*> object = act.results()[0];
  1000. std::optional<Nonnull<const Witness*>> witness;
  1001. if (access.impl().has_value()) {
  1002. witness = cast<Witness>(act.results()[1]);
  1003. } else {
  1004. CARBON_CHECK(access.member().base_type().has_value())
  1005. << "compound access should have base type or impl";
  1006. CARBON_ASSIGN_OR_RETURN(
  1007. object, Convert(object, *access.member().base_type(),
  1008. exp.source_loc()));
  1009. }
  1010. FieldPath::Component field(access.member().member(),
  1011. found_in_interface, witness);
  1012. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> member,
  1013. object->GetMember(arena_, FieldPath(field),
  1014. exp.source_loc(), object));
  1015. return todo_.FinishAction(member);
  1016. }
  1017. }
  1018. }
  1019. case ExpressionKind::IdentifierExpression: {
  1020. CARBON_CHECK(act.pos() == 0);
  1021. const auto& ident = cast<IdentifierExpression>(exp);
  1022. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  1023. CARBON_ASSIGN_OR_RETURN(
  1024. Nonnull<const Value*> value,
  1025. todo_.ValueOfNode(ident.value_node(), ident.source_loc()));
  1026. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1027. CARBON_ASSIGN_OR_RETURN(
  1028. value, heap_.Read(lvalue->address(), exp.source_loc()));
  1029. }
  1030. return todo_.FinishAction(value);
  1031. }
  1032. case ExpressionKind::DotSelfExpression: {
  1033. // `.Self` always symbolically resolves to the self binding, even if it's
  1034. // not yet been type-checked.
  1035. CARBON_CHECK(act.pos() == 0);
  1036. const auto& dot_self = cast<DotSelfExpression>(exp);
  1037. return todo_.FinishAction(
  1038. arena_->New<VariableType>(&dot_self.self_binding()));
  1039. }
  1040. case ExpressionKind::IntLiteral:
  1041. CARBON_CHECK(act.pos() == 0);
  1042. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1043. return todo_.FinishAction(
  1044. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  1045. case ExpressionKind::BoolLiteral:
  1046. CARBON_CHECK(act.pos() == 0);
  1047. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1048. return todo_.FinishAction(
  1049. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  1050. case ExpressionKind::OperatorExpression: {
  1051. const auto& op = cast<OperatorExpression>(exp);
  1052. if (auto rewrite = op.rewritten_form()) {
  1053. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(*rewrite));
  1054. }
  1055. if (act.pos() != static_cast<int>(op.arguments().size())) {
  1056. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  1057. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  1058. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  1059. if (op.op() == Operator::AddressOf) {
  1060. return todo_.Spawn(std::make_unique<LValAction>(arg));
  1061. } else if ((op.op() == Operator::And || op.op() == Operator::Or) &&
  1062. act.pos() == 1) {
  1063. // Short-circuit evaluation for 'and' & 'or'
  1064. auto operand_value = cast<BoolValue>(act.results()[act.pos() - 1]);
  1065. if ((op.op() == Operator::Or && operand_value->value()) ||
  1066. (op.op() == Operator::And && !operand_value->value())) {
  1067. return todo_.FinishAction(operand_value);
  1068. }
  1069. // No short-circuit, fall through to evaluate 2nd operand.
  1070. }
  1071. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  1072. } else {
  1073. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  1074. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  1075. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1076. EvalPrim(op.op(), &op.static_type(),
  1077. act.results(), exp.source_loc()));
  1078. return todo_.FinishAction(value);
  1079. }
  1080. }
  1081. case ExpressionKind::CallExpression: {
  1082. const CallExpression& call = cast<CallExpression>(exp);
  1083. unsigned int num_impls = call.impls().size();
  1084. if (act.pos() == 0) {
  1085. // { {e1(e2) :: C, E, F} :: S, H}
  1086. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  1087. return todo_.Spawn(
  1088. std::make_unique<ExpressionAction>(&call.function()));
  1089. } else if (act.pos() == 1) {
  1090. // { { v :: [](e) :: C, E, F} :: S, H}
  1091. // -> { { e :: v([]) :: C, E, F} :: S, H}
  1092. return todo_.Spawn(
  1093. std::make_unique<ExpressionAction>(&call.argument()));
  1094. } else if (num_impls > 0 && act.pos() < 2 + int(num_impls)) {
  1095. auto iter = call.impls().begin();
  1096. std::advance(iter, act.pos() - 2);
  1097. return todo_.Spawn(std::make_unique<ExpressionAction>(iter->second));
  1098. } else if (act.pos() == 2 + int(num_impls)) {
  1099. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  1100. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  1101. ImplWitnessMap witnesses;
  1102. if (num_impls > 0) {
  1103. int i = 2;
  1104. for (const auto& [impl_bind, impl_exp] : call.impls()) {
  1105. witnesses[impl_bind] = act.results()[i];
  1106. ++i;
  1107. }
  1108. }
  1109. return CallFunction(call, act.results()[0], act.results()[1],
  1110. std::move(witnesses));
  1111. } else if (act.pos() == 3 + int(num_impls)) {
  1112. if (act.results().size() < 3 + num_impls) {
  1113. // Control fell through without explicit return.
  1114. return todo_.FinishAction(TupleValue::Empty());
  1115. } else {
  1116. return todo_.FinishAction(act.results()[2 + int(num_impls)]);
  1117. }
  1118. } else {
  1119. CARBON_FATAL() << "in StepExp with Call pos " << act.pos();
  1120. }
  1121. }
  1122. case ExpressionKind::IntrinsicExpression: {
  1123. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  1124. if (act.pos() == 0) {
  1125. return todo_.Spawn(
  1126. std::make_unique<ExpressionAction>(&intrinsic.args()));
  1127. }
  1128. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1129. const auto& args = cast<TupleValue>(*act.results()[0]).elements();
  1130. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  1131. case IntrinsicExpression::Intrinsic::Print: {
  1132. CARBON_ASSIGN_OR_RETURN(
  1133. Nonnull<const Value*> format_string_value,
  1134. Convert(args[0], arena_->New<StringType>(), exp.source_loc()));
  1135. const char* format_string =
  1136. cast<StringValue>(*format_string_value).value().c_str();
  1137. switch (args.size()) {
  1138. case 1:
  1139. llvm::outs() << llvm::formatv(format_string);
  1140. break;
  1141. case 2:
  1142. llvm::outs() << llvm::formatv(format_string,
  1143. cast<IntValue>(*args[1]).value());
  1144. break;
  1145. default:
  1146. CARBON_FATAL() << "Unexpected arg count: " << args.size();
  1147. }
  1148. // Implicit newline; currently no way to disable it.
  1149. llvm::outs() << "\n";
  1150. return todo_.FinishAction(TupleValue::Empty());
  1151. }
  1152. case IntrinsicExpression::Intrinsic::Alloc: {
  1153. CARBON_CHECK(args.size() == 1);
  1154. Address addr(heap_.AllocateValue(args[0]));
  1155. return todo_.FinishAction(arena_->New<PointerValue>(addr));
  1156. }
  1157. case IntrinsicExpression::Intrinsic::Dealloc: {
  1158. CARBON_CHECK(args.size() == 1);
  1159. heap_.Deallocate(cast<PointerValue>(args[0])->address());
  1160. return todo_.FinishAction(TupleValue::Empty());
  1161. }
  1162. case IntrinsicExpression::Intrinsic::Rand: {
  1163. CARBON_CHECK(args.size() == 2);
  1164. const auto& low = cast<IntValue>(*args[0]).value();
  1165. const auto& high = cast<IntValue>(*args[1]).value();
  1166. std::uniform_int_distribution<> distr(low, high);
  1167. int r = distr(generator);
  1168. return todo_.FinishAction(arena_->New<IntValue>(r));
  1169. }
  1170. case IntrinsicExpression::Intrinsic::IntEq: {
  1171. CARBON_CHECK(args.size() == 2);
  1172. auto lhs = cast<IntValue>(*args[0]).value();
  1173. auto rhs = cast<IntValue>(*args[1]).value();
  1174. auto result = arena_->New<BoolValue>(lhs == rhs);
  1175. return todo_.FinishAction(result);
  1176. }
  1177. case IntrinsicExpression::Intrinsic::StrEq: {
  1178. CARBON_CHECK(args.size() == 2);
  1179. auto& lhs = cast<StringValue>(*args[0]).value();
  1180. auto& rhs = cast<StringValue>(*args[1]).value();
  1181. auto result = arena_->New<BoolValue>(lhs == rhs);
  1182. return todo_.FinishAction(result);
  1183. }
  1184. case IntrinsicExpression::Intrinsic::IntBitComplement: {
  1185. CARBON_CHECK(args.size() == 1);
  1186. return todo_.FinishAction(
  1187. arena_->New<IntValue>(~cast<IntValue>(*args[0]).value()));
  1188. }
  1189. case IntrinsicExpression::Intrinsic::IntBitAnd: {
  1190. CARBON_CHECK(args.size() == 2);
  1191. return todo_.FinishAction(
  1192. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() &
  1193. cast<IntValue>(*args[1]).value()));
  1194. }
  1195. case IntrinsicExpression::Intrinsic::IntBitOr: {
  1196. CARBON_CHECK(args.size() == 2);
  1197. return todo_.FinishAction(
  1198. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() |
  1199. cast<IntValue>(*args[1]).value()));
  1200. }
  1201. case IntrinsicExpression::Intrinsic::IntBitXor: {
  1202. CARBON_CHECK(args.size() == 2);
  1203. return todo_.FinishAction(
  1204. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() ^
  1205. cast<IntValue>(*args[1]).value()));
  1206. }
  1207. case IntrinsicExpression::Intrinsic::IntLeftShift: {
  1208. CARBON_CHECK(args.size() == 2);
  1209. // TODO: Runtime error if RHS is too large.
  1210. return todo_.FinishAction(arena_->New<IntValue>(
  1211. static_cast<uint32_t>(cast<IntValue>(*args[0]).value())
  1212. << cast<IntValue>(*args[1]).value()));
  1213. }
  1214. case IntrinsicExpression::Intrinsic::IntRightShift: {
  1215. CARBON_CHECK(args.size() == 2);
  1216. // TODO: Runtime error if RHS is too large.
  1217. return todo_.FinishAction(
  1218. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() >>
  1219. cast<IntValue>(*args[1]).value()));
  1220. }
  1221. }
  1222. }
  1223. case ExpressionKind::IntTypeLiteral: {
  1224. CARBON_CHECK(act.pos() == 0);
  1225. return todo_.FinishAction(arena_->New<IntType>());
  1226. }
  1227. case ExpressionKind::BoolTypeLiteral: {
  1228. CARBON_CHECK(act.pos() == 0);
  1229. return todo_.FinishAction(arena_->New<BoolType>());
  1230. }
  1231. case ExpressionKind::TypeTypeLiteral: {
  1232. CARBON_CHECK(act.pos() == 0);
  1233. return todo_.FinishAction(arena_->New<TypeType>());
  1234. }
  1235. case ExpressionKind::FunctionTypeLiteral: {
  1236. if (act.pos() == 0) {
  1237. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1238. &cast<FunctionTypeLiteral>(exp).parameter()));
  1239. } else if (act.pos() == 1) {
  1240. // { { pt :: fn [] -> e :: C, E, F} :: S, H}
  1241. // -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
  1242. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1243. &cast<FunctionTypeLiteral>(exp).return_type()));
  1244. } else {
  1245. // { { rt :: fn pt -> [] :: C, E, F} :: S, H}
  1246. // -> { fn pt -> rt :: {C, E, F} :: S, H}
  1247. return todo_.FinishAction(arena_->New<FunctionType>(
  1248. act.results()[0], llvm::None, act.results()[1], llvm::None,
  1249. llvm::None));
  1250. }
  1251. }
  1252. case ExpressionKind::ContinuationTypeLiteral: {
  1253. CARBON_CHECK(act.pos() == 0);
  1254. return todo_.FinishAction(arena_->New<ContinuationType>());
  1255. }
  1256. case ExpressionKind::StringLiteral:
  1257. CARBON_CHECK(act.pos() == 0);
  1258. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1259. return todo_.FinishAction(
  1260. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  1261. case ExpressionKind::StringTypeLiteral: {
  1262. CARBON_CHECK(act.pos() == 0);
  1263. return todo_.FinishAction(arena_->New<StringType>());
  1264. }
  1265. case ExpressionKind::ValueLiteral: {
  1266. CARBON_CHECK(act.pos() == 0);
  1267. return todo_.FinishAction(&cast<ValueLiteral>(exp).value());
  1268. }
  1269. case ExpressionKind::IfExpression: {
  1270. const auto& if_expr = cast<IfExpression>(exp);
  1271. if (act.pos() == 0) {
  1272. return todo_.Spawn(
  1273. std::make_unique<ExpressionAction>(&if_expr.condition()));
  1274. } else if (act.pos() == 1) {
  1275. const auto& condition = cast<BoolValue>(*act.results()[0]);
  1276. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1277. condition.value() ? &if_expr.then_expression()
  1278. : &if_expr.else_expression()));
  1279. } else {
  1280. return todo_.FinishAction(act.results()[1]);
  1281. }
  1282. break;
  1283. }
  1284. case ExpressionKind::WhereExpression: {
  1285. return todo_.FinishAction(
  1286. &cast<TypeOfConstraintType>(exp.static_type()).constraint_type());
  1287. }
  1288. case ExpressionKind::UnimplementedExpression:
  1289. CARBON_FATAL() << "Unimplemented: " << exp;
  1290. case ExpressionKind::ArrayTypeLiteral: {
  1291. const auto& array_literal = cast<ArrayTypeLiteral>(exp);
  1292. if (act.pos() == 0) {
  1293. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1294. &array_literal.element_type_expression()));
  1295. } else if (act.pos() == 1) {
  1296. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1297. &array_literal.size_expression()));
  1298. } else {
  1299. return todo_.FinishAction(arena_->New<StaticArrayType>(
  1300. act.results()[0], cast<IntValue>(act.results()[1])->value()));
  1301. }
  1302. }
  1303. } // switch (exp->kind)
  1304. }
  1305. auto Interpreter::StepPattern() -> ErrorOr<Success> {
  1306. Action& act = todo_.CurrentAction();
  1307. const Pattern& pattern = cast<PatternAction>(act).pattern();
  1308. if (trace_stream_) {
  1309. **trace_stream_ << "--- step pattern " << pattern << " ." << act.pos()
  1310. << ". (" << pattern.source_loc() << ") --->\n";
  1311. }
  1312. switch (pattern.kind()) {
  1313. case PatternKind::AutoPattern: {
  1314. CARBON_CHECK(act.pos() == 0);
  1315. return todo_.FinishAction(arena_->New<AutoType>());
  1316. }
  1317. case PatternKind::BindingPattern: {
  1318. const auto& binding = cast<BindingPattern>(pattern);
  1319. if (binding.name() != AnonymousName) {
  1320. return todo_.FinishAction(
  1321. arena_->New<BindingPlaceholderValue>(&binding));
  1322. } else {
  1323. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  1324. }
  1325. }
  1326. case PatternKind::GenericBinding: {
  1327. const auto& binding = cast<GenericBinding>(pattern);
  1328. return todo_.FinishAction(arena_->New<VariableType>(&binding));
  1329. }
  1330. case PatternKind::TuplePattern: {
  1331. const auto& tuple = cast<TuplePattern>(pattern);
  1332. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  1333. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1334. // H}
  1335. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1336. // H}
  1337. return todo_.Spawn(
  1338. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  1339. } else {
  1340. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  1341. }
  1342. }
  1343. case PatternKind::AlternativePattern: {
  1344. const auto& alternative = cast<AlternativePattern>(pattern);
  1345. if (act.pos() == 0) {
  1346. return todo_.Spawn(
  1347. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  1348. } else if (act.pos() == 1) {
  1349. return todo_.Spawn(
  1350. std::make_unique<PatternAction>(&alternative.arguments()));
  1351. } else {
  1352. CARBON_CHECK(act.pos() == 2);
  1353. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  1354. return todo_.FinishAction(arena_->New<AlternativeValue>(
  1355. alternative.alternative_name(), choice_type.name(),
  1356. act.results()[1]));
  1357. }
  1358. }
  1359. case PatternKind::ExpressionPattern:
  1360. if (act.pos() == 0) {
  1361. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1362. &cast<ExpressionPattern>(pattern).expression()));
  1363. } else {
  1364. return todo_.FinishAction(act.results()[0]);
  1365. }
  1366. case PatternKind::VarPattern:
  1367. if (act.pos() == 0) {
  1368. return todo_.Spawn(std::make_unique<PatternAction>(
  1369. &cast<VarPattern>(pattern).pattern()));
  1370. } else {
  1371. return todo_.FinishAction(act.results()[0]);
  1372. }
  1373. case PatternKind::AddrPattern:
  1374. const auto& addr = cast<AddrPattern>(pattern);
  1375. if (act.pos() == 0) {
  1376. return todo_.Spawn(std::make_unique<PatternAction>(&addr.binding()));
  1377. } else {
  1378. return todo_.FinishAction(arena_->New<AddrValue>(act.results()[0]));
  1379. }
  1380. break;
  1381. }
  1382. }
  1383. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  1384. Action& act = todo_.CurrentAction();
  1385. const Statement& stmt = cast<StatementAction>(act).statement();
  1386. if (trace_stream_) {
  1387. **trace_stream_ << "--- step stmt ";
  1388. stmt.PrintDepth(1, **trace_stream_);
  1389. **trace_stream_ << " ." << act.pos() << ". "
  1390. << "(" << stmt.source_loc() << ") --->\n";
  1391. }
  1392. switch (stmt.kind()) {
  1393. case StatementKind::Match: {
  1394. const auto& match_stmt = cast<Match>(stmt);
  1395. if (act.pos() == 0) {
  1396. // { { (match (e) ...) :: C, E, F} :: S, H}
  1397. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  1398. act.StartScope(RuntimeScope(&heap_));
  1399. return todo_.Spawn(
  1400. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  1401. } else {
  1402. int clause_num = act.pos() - 1;
  1403. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  1404. return todo_.FinishAction();
  1405. }
  1406. auto c = match_stmt.clauses()[clause_num];
  1407. RuntimeScope matches(&heap_);
  1408. BindingMap generic_args;
  1409. CARBON_ASSIGN_OR_RETURN(
  1410. Nonnull<const Value*> val,
  1411. Convert(act.results()[0], &c.pattern().static_type(),
  1412. stmt.source_loc()));
  1413. if (PatternMatch(&c.pattern().value(), val, stmt.source_loc(), &matches,
  1414. generic_args, trace_stream_, this->arena_)) {
  1415. // Ensure we don't process any more clauses.
  1416. act.set_pos(match_stmt.clauses().size() + 1);
  1417. todo_.MergeScope(std::move(matches));
  1418. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  1419. } else {
  1420. return todo_.RunAgain();
  1421. }
  1422. }
  1423. }
  1424. case StatementKind::While:
  1425. if (act.pos() % 2 == 0) {
  1426. // { { (while (e) s) :: C, E, F} :: S, H}
  1427. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  1428. act.Clear();
  1429. return todo_.Spawn(
  1430. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  1431. } else {
  1432. CARBON_ASSIGN_OR_RETURN(
  1433. Nonnull<const Value*> condition,
  1434. Convert(act.results().back(), arena_->New<BoolType>(),
  1435. stmt.source_loc()));
  1436. if (cast<BoolValue>(*condition).value()) {
  1437. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1438. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1439. return todo_.Spawn(
  1440. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  1441. } else {
  1442. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1443. // -> { { C, E, F } :: S, H}
  1444. return todo_.FinishAction();
  1445. }
  1446. }
  1447. case StatementKind::Break: {
  1448. CARBON_CHECK(act.pos() == 0);
  1449. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1450. // -> { { C, E', F} :: S, H}
  1451. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  1452. }
  1453. case StatementKind::Continue: {
  1454. CARBON_CHECK(act.pos() == 0);
  1455. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1456. // -> { { (while (e) s) :: C, E', F} :: S, H}
  1457. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  1458. }
  1459. case StatementKind::Block: {
  1460. const auto& block = cast<Block>(stmt);
  1461. if (act.pos() >= static_cast<int>(block.statements().size())) {
  1462. // If the position is past the end of the block, end processing. Note
  1463. // that empty blocks immediately end.
  1464. return todo_.FinishAction();
  1465. }
  1466. // Initialize a scope when starting a block.
  1467. if (act.pos() == 0) {
  1468. act.StartScope(RuntimeScope(&heap_));
  1469. }
  1470. // Process the next statement in the block. The position will be
  1471. // incremented as part of Spawn.
  1472. return todo_.Spawn(
  1473. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  1474. }
  1475. case StatementKind::VariableDefinition: {
  1476. const auto& definition = cast<VariableDefinition>(stmt);
  1477. if (act.pos() == 0 && definition.has_init()) {
  1478. // { {(var x = e) :: C, E, F} :: S, H}
  1479. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  1480. return todo_.Spawn(
  1481. std::make_unique<ExpressionAction>(&definition.init()));
  1482. } else {
  1483. // { { v :: (x = []) :: C, E, F} :: S, H}
  1484. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1485. Nonnull<const Value*> p =
  1486. &cast<VariableDefinition>(stmt).pattern().value();
  1487. Nonnull<const Value*> v;
  1488. if (definition.has_init()) {
  1489. CARBON_ASSIGN_OR_RETURN(
  1490. v, Convert(act.results()[0], &definition.pattern().static_type(),
  1491. stmt.source_loc()));
  1492. } else {
  1493. v = arena_->New<UninitializedValue>(p);
  1494. }
  1495. RuntimeScope matches(&heap_);
  1496. BindingMap generic_args;
  1497. CARBON_CHECK(PatternMatch(p, v, stmt.source_loc(), &matches,
  1498. generic_args, trace_stream_, this->arena_))
  1499. << stmt.source_loc()
  1500. << ": internal error in variable definition, match failed";
  1501. todo_.MergeScope(std::move(matches));
  1502. return todo_.FinishAction();
  1503. }
  1504. }
  1505. case StatementKind::ExpressionStatement:
  1506. if (act.pos() == 0) {
  1507. // { {e :: C, E, F} :: S, H}
  1508. // -> { {e :: C, E, F} :: S, H}
  1509. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1510. &cast<ExpressionStatement>(stmt).expression()));
  1511. } else {
  1512. return todo_.FinishAction();
  1513. }
  1514. case StatementKind::Assign: {
  1515. const auto& assign = cast<Assign>(stmt);
  1516. if (act.pos() == 0) {
  1517. // { {(lv = e) :: C, E, F} :: S, H}
  1518. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1519. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  1520. } else if (act.pos() == 1) {
  1521. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1522. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1523. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  1524. } else {
  1525. // { { v :: (a = []) :: C, E, F} :: S, H}
  1526. // -> { { C, E, F} :: S, H(a := v)}
  1527. const auto& lval = cast<LValue>(*act.results()[0]);
  1528. CARBON_ASSIGN_OR_RETURN(
  1529. Nonnull<const Value*> rval,
  1530. Convert(act.results()[1], &assign.lhs().static_type(),
  1531. stmt.source_loc()));
  1532. CARBON_RETURN_IF_ERROR(
  1533. heap_.Write(lval.address(), rval, stmt.source_loc()));
  1534. return todo_.FinishAction();
  1535. }
  1536. }
  1537. case StatementKind::If:
  1538. if (act.pos() == 0) {
  1539. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1540. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1541. return todo_.Spawn(
  1542. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  1543. } else if (act.pos() == 1) {
  1544. CARBON_ASSIGN_OR_RETURN(
  1545. Nonnull<const Value*> condition,
  1546. Convert(act.results()[0], arena_->New<BoolType>(),
  1547. stmt.source_loc()));
  1548. if (cast<BoolValue>(*condition).value()) {
  1549. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1550. // S, H}
  1551. // -> { { then_stmt :: C, E, F } :: S, H}
  1552. return todo_.Spawn(
  1553. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  1554. } else if (cast<If>(stmt).else_block()) {
  1555. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1556. // S, H}
  1557. // -> { { else_stmt :: C, E, F } :: S, H}
  1558. return todo_.Spawn(
  1559. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  1560. } else {
  1561. return todo_.FinishAction();
  1562. }
  1563. } else {
  1564. return todo_.FinishAction();
  1565. }
  1566. case StatementKind::ReturnVar: {
  1567. const ValueNodeView& value_node = cast<ReturnVar>(stmt).value_node();
  1568. if (trace_stream_) {
  1569. **trace_stream_ << "--- step returned var "
  1570. << cast<BindingPattern>(value_node.base()).name()
  1571. << " ." << act.pos() << "."
  1572. << " (" << stmt.source_loc() << ") --->\n";
  1573. }
  1574. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1575. todo_.ValueOfNode(value_node, stmt.source_loc()));
  1576. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1577. CARBON_ASSIGN_OR_RETURN(
  1578. value,
  1579. heap_.Read(lvalue->address(), value_node.base().source_loc()));
  1580. }
  1581. const FunctionDeclaration& function = cast<Return>(stmt).function();
  1582. CARBON_ASSIGN_OR_RETURN(
  1583. Nonnull<const Value*> return_value,
  1584. Convert(value, &function.return_term().static_type(),
  1585. stmt.source_loc()));
  1586. return todo_.UnwindPast(*function.body(), return_value);
  1587. }
  1588. case StatementKind::ReturnExpression:
  1589. if (act.pos() == 0) {
  1590. // { {return e :: C, E, F} :: S, H}
  1591. // -> { {e :: return [] :: C, E, F} :: S, H}
  1592. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1593. &cast<ReturnExpression>(stmt).expression()));
  1594. } else {
  1595. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1596. // -> { {v :: C', E', F'} :: S, H}
  1597. const FunctionDeclaration& function = cast<Return>(stmt).function();
  1598. CARBON_ASSIGN_OR_RETURN(
  1599. Nonnull<const Value*> return_value,
  1600. Convert(act.results()[0], &function.return_term().static_type(),
  1601. stmt.source_loc()));
  1602. return todo_.UnwindPast(*function.body(), return_value);
  1603. }
  1604. case StatementKind::Continuation: {
  1605. CARBON_CHECK(act.pos() == 0);
  1606. const auto& continuation = cast<Continuation>(stmt);
  1607. // Create a continuation object by creating a frame similar the
  1608. // way one is created in a function call.
  1609. auto fragment = arena_->New<ContinuationValue::StackFragment>();
  1610. stack_fragments_.push_back(fragment);
  1611. todo_.InitializeFragment(*fragment, &continuation.body());
  1612. // Bind the continuation object to the continuation variable
  1613. todo_.Initialize(&cast<Continuation>(stmt),
  1614. arena_->New<ContinuationValue>(fragment));
  1615. return todo_.FinishAction();
  1616. }
  1617. case StatementKind::Run: {
  1618. auto& run = cast<Run>(stmt);
  1619. if (act.pos() == 0) {
  1620. // Evaluate the argument of the run statement.
  1621. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  1622. } else if (act.pos() == 1) {
  1623. // Push the continuation onto the current stack.
  1624. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  1625. } else {
  1626. return todo_.FinishAction();
  1627. }
  1628. }
  1629. case StatementKind::Await:
  1630. CARBON_CHECK(act.pos() == 0);
  1631. return todo_.Suspend();
  1632. }
  1633. }
  1634. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  1635. Action& act = todo_.CurrentAction();
  1636. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  1637. if (trace_stream_) {
  1638. **trace_stream_ << "--- step decl ";
  1639. decl.PrintID(**trace_stream_);
  1640. **trace_stream_ << " ." << act.pos() << ". "
  1641. << "(" << decl.source_loc() << ") --->\n";
  1642. }
  1643. switch (decl.kind()) {
  1644. case DeclarationKind::VariableDeclaration: {
  1645. const auto& var_decl = cast<VariableDeclaration>(decl);
  1646. if (var_decl.has_initializer()) {
  1647. if (act.pos() == 0) {
  1648. return todo_.Spawn(
  1649. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  1650. } else {
  1651. CARBON_ASSIGN_OR_RETURN(
  1652. Nonnull<const Value*> v,
  1653. Convert(act.results()[0], &var_decl.binding().static_type(),
  1654. var_decl.source_loc()));
  1655. todo_.Initialize(&var_decl.binding(), v);
  1656. return todo_.FinishAction();
  1657. }
  1658. } else {
  1659. Nonnull<const Value*> v =
  1660. arena_->New<UninitializedValue>(&var_decl.binding().value());
  1661. todo_.Initialize(&var_decl.binding(), v);
  1662. return todo_.FinishAction();
  1663. }
  1664. }
  1665. case DeclarationKind::FunctionDeclaration:
  1666. case DeclarationKind::ClassDeclaration:
  1667. case DeclarationKind::ChoiceDeclaration:
  1668. case DeclarationKind::InterfaceDeclaration:
  1669. case DeclarationKind::AssociatedConstantDeclaration:
  1670. case DeclarationKind::ImplDeclaration:
  1671. case DeclarationKind::SelfDeclaration:
  1672. case DeclarationKind::AliasDeclaration:
  1673. // These declarations have no run-time effects.
  1674. return todo_.FinishAction();
  1675. }
  1676. }
  1677. // State transition.
  1678. auto Interpreter::Step() -> ErrorOr<Success> {
  1679. Action& act = todo_.CurrentAction();
  1680. switch (act.kind()) {
  1681. case Action::Kind::LValAction:
  1682. CARBON_RETURN_IF_ERROR(StepLvalue());
  1683. break;
  1684. case Action::Kind::ExpressionAction:
  1685. CARBON_RETURN_IF_ERROR(StepExp());
  1686. break;
  1687. case Action::Kind::PatternAction:
  1688. CARBON_RETURN_IF_ERROR(StepPattern());
  1689. break;
  1690. case Action::Kind::StatementAction:
  1691. CARBON_RETURN_IF_ERROR(StepStmt());
  1692. break;
  1693. case Action::Kind::DeclarationAction:
  1694. CARBON_RETURN_IF_ERROR(StepDeclaration());
  1695. break;
  1696. case Action::Kind::ScopeAction:
  1697. CARBON_FATAL() << "ScopeAction escaped ActionStack";
  1698. case Action::Kind::RecursiveAction:
  1699. CARBON_FATAL() << "Tried to step a RecursiveAction";
  1700. } // switch
  1701. return Success();
  1702. }
  1703. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  1704. -> ErrorOr<Success> {
  1705. if (trace_stream_) {
  1706. PrintState(**trace_stream_);
  1707. }
  1708. todo_.Start(std::move(action));
  1709. while (!todo_.IsEmpty()) {
  1710. CARBON_RETURN_IF_ERROR(Step());
  1711. if (trace_stream_) {
  1712. PrintState(**trace_stream_);
  1713. }
  1714. }
  1715. return Success();
  1716. }
  1717. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena,
  1718. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1719. -> ErrorOr<int> {
  1720. Interpreter interpreter(Phase::RunTime, arena, trace_stream);
  1721. if (trace_stream) {
  1722. **trace_stream << "********** initializing globals **********\n";
  1723. }
  1724. for (Nonnull<Declaration*> declaration : ast.declarations) {
  1725. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  1726. std::make_unique<DeclarationAction>(declaration)));
  1727. }
  1728. if (trace_stream) {
  1729. **trace_stream << "********** calling main function **********\n";
  1730. }
  1731. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  1732. std::make_unique<ExpressionAction>(*ast.main_call)));
  1733. return cast<IntValue>(*interpreter.result()).value();
  1734. }
  1735. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena,
  1736. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1737. -> ErrorOr<Nonnull<const Value*>> {
  1738. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1739. CARBON_RETURN_IF_ERROR(
  1740. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e)));
  1741. return interpreter.result();
  1742. }
  1743. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena,
  1744. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  1745. -> ErrorOr<Nonnull<const Value*>> {
  1746. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  1747. CARBON_RETURN_IF_ERROR(
  1748. interpreter.RunAllSteps(std::make_unique<PatternAction>(p)));
  1749. return interpreter.result();
  1750. }
  1751. } // namespace Carbon