interpreter.cpp 87 KB

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