interpreter.cpp 89 KB

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