interpreter.cpp 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207
  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::NamedConstraintType: {
  563. const auto& constraint_type = cast<NamedConstraintType>(*type);
  564. CARBON_ASSIGN_OR_RETURN(
  565. Nonnull<const Bindings*> bindings,
  566. InstantiateBindings(&constraint_type.bindings(), source_loc));
  567. return arena_->New<NamedConstraintType>(&constraint_type.declaration(),
  568. bindings);
  569. }
  570. case Value::Kind::NominalClassType: {
  571. const auto& class_type = cast<NominalClassType>(*type);
  572. CARBON_ASSIGN_OR_RETURN(
  573. Nonnull<const Bindings*> bindings,
  574. InstantiateBindings(&class_type.bindings(), source_loc));
  575. return arena_->New<NominalClassType>(&class_type.declaration(), bindings);
  576. }
  577. case Value::Kind::ChoiceType: {
  578. const auto& choice_type = cast<ChoiceType>(*type);
  579. CARBON_ASSIGN_OR_RETURN(
  580. Nonnull<const Bindings*> bindings,
  581. InstantiateBindings(&choice_type.bindings(), source_loc));
  582. return arena_->New<ChoiceType>(&choice_type.declaration(), bindings);
  583. }
  584. case Value::Kind::AssociatedConstant: {
  585. CARBON_ASSIGN_OR_RETURN(
  586. Nonnull<const Value*> type_value,
  587. EvalAssociatedConstant(cast<AssociatedConstant>(type), source_loc));
  588. return type_value;
  589. }
  590. default:
  591. return type;
  592. }
  593. }
  594. auto Interpreter::InstantiateBindings(Nonnull<const Bindings*> bindings,
  595. SourceLocation source_loc)
  596. -> ErrorOr<Nonnull<const Bindings*>> {
  597. BindingMap args = bindings->args();
  598. for (auto& [var, arg] : args) {
  599. CARBON_ASSIGN_OR_RETURN(arg, InstantiateType(arg, source_loc));
  600. }
  601. ImplWitnessMap witnesses = bindings->witnesses();
  602. for (auto& [bind, witness] : witnesses) {
  603. CARBON_ASSIGN_OR_RETURN(witness,
  604. InstantiateWitness(cast<Witness>(witness)));
  605. }
  606. if (args == bindings->args() && witnesses == bindings->witnesses()) {
  607. return bindings;
  608. }
  609. return arena_->New<Bindings>(std::move(args), std::move(witnesses));
  610. }
  611. auto Interpreter::InstantiateWitness(Nonnull<const Witness*> witness)
  612. -> ErrorOr<Nonnull<const Witness*>> {
  613. CARBON_ASSIGN_OR_RETURN(
  614. Nonnull<const Value*> value,
  615. EvalRecursively(std::make_unique<WitnessAction>(witness)));
  616. return cast<Witness>(value);
  617. }
  618. auto Interpreter::Convert(Nonnull<const Value*> value,
  619. Nonnull<const Value*> destination_type,
  620. SourceLocation source_loc)
  621. -> ErrorOr<Nonnull<const Value*>> {
  622. switch (value->kind()) {
  623. case Value::Kind::IntValue:
  624. case Value::Kind::FunctionValue:
  625. case Value::Kind::DestructorValue:
  626. case Value::Kind::BoundMethodValue:
  627. case Value::Kind::PointerValue:
  628. case Value::Kind::LValue:
  629. case Value::Kind::BoolValue:
  630. case Value::Kind::NominalClassValue:
  631. case Value::Kind::AlternativeValue:
  632. case Value::Kind::UninitializedValue:
  633. case Value::Kind::IntType:
  634. case Value::Kind::BoolType:
  635. case Value::Kind::TypeType:
  636. case Value::Kind::FunctionType:
  637. case Value::Kind::PointerType:
  638. case Value::Kind::TupleType:
  639. case Value::Kind::StructType:
  640. case Value::Kind::AutoType:
  641. case Value::Kind::NominalClassType:
  642. case Value::Kind::MixinPseudoType:
  643. case Value::Kind::InterfaceType:
  644. case Value::Kind::NamedConstraintType:
  645. case Value::Kind::ConstraintType:
  646. case Value::Kind::ImplWitness:
  647. case Value::Kind::BindingWitness:
  648. case Value::Kind::ConstraintWitness:
  649. case Value::Kind::ConstraintImplWitness:
  650. case Value::Kind::ParameterizedEntityName:
  651. case Value::Kind::ChoiceType:
  652. case Value::Kind::ContinuationType:
  653. case Value::Kind::VariableType:
  654. case Value::Kind::BindingPlaceholderValue:
  655. case Value::Kind::AddrValue:
  656. case Value::Kind::AlternativeConstructorValue:
  657. case Value::Kind::ContinuationValue:
  658. case Value::Kind::StringType:
  659. case Value::Kind::StringValue:
  660. case Value::Kind::TypeOfMixinPseudoType:
  661. case Value::Kind::TypeOfParameterizedEntityName:
  662. case Value::Kind::TypeOfMemberName:
  663. case Value::Kind::StaticArrayType:
  664. case Value::Kind::MemberName:
  665. // TODO: add `CARBON_CHECK(TypeEqual(type, value->dynamic_type()))`, once
  666. // we have Value::dynamic_type.
  667. return value;
  668. case Value::Kind::StructValue: {
  669. const auto& struct_val = cast<StructValue>(*value);
  670. switch (destination_type->kind()) {
  671. case Value::Kind::StructType: {
  672. const auto& destination_struct_type =
  673. cast<StructType>(*destination_type);
  674. std::vector<NamedValue> new_elements;
  675. for (const auto& [field_name, field_type] :
  676. destination_struct_type.fields()) {
  677. std::optional<Nonnull<const Value*>> old_value =
  678. struct_val.FindField(field_name);
  679. CARBON_ASSIGN_OR_RETURN(
  680. Nonnull<const Value*> val,
  681. Convert(*old_value, field_type, source_loc));
  682. new_elements.push_back({.name = field_name, .value = val});
  683. }
  684. return arena_->New<StructValue>(std::move(new_elements));
  685. }
  686. case Value::Kind::NominalClassType: {
  687. // Instantiate the `destination_type` to obtain the runtime
  688. // type of the object.
  689. CARBON_ASSIGN_OR_RETURN(
  690. Nonnull<const Value*> inst_dest,
  691. InstantiateType(destination_type, source_loc));
  692. return arena_->New<NominalClassValue>(inst_dest, value);
  693. }
  694. case Value::Kind::TypeType:
  695. case Value::Kind::ConstraintType:
  696. case Value::Kind::NamedConstraintType:
  697. case Value::Kind::InterfaceType: {
  698. CARBON_CHECK(struct_val.elements().empty())
  699. << "only empty structs convert to Type";
  700. return arena_->New<StructType>();
  701. }
  702. default: {
  703. CARBON_CHECK(IsValueKindDependent(destination_type) ||
  704. isa<TypeType, ConstraintType>(destination_type))
  705. << "Can't convert value " << *value << " to type "
  706. << *destination_type;
  707. return value;
  708. }
  709. }
  710. }
  711. case Value::Kind::TupleValue: {
  712. const auto* tuple = cast<TupleValue>(value);
  713. std::vector<Nonnull<const Value*>> destination_element_types;
  714. switch (destination_type->kind()) {
  715. case Value::Kind::TupleType:
  716. destination_element_types =
  717. cast<TupleType>(destination_type)->elements();
  718. break;
  719. case Value::Kind::StaticArrayType: {
  720. const auto& array_type = cast<StaticArrayType>(*destination_type);
  721. destination_element_types.resize(array_type.size(),
  722. &array_type.element_type());
  723. break;
  724. }
  725. case Value::Kind::TypeType:
  726. case Value::Kind::ConstraintType:
  727. case Value::Kind::NamedConstraintType:
  728. case Value::Kind::InterfaceType: {
  729. std::vector<Nonnull<const Value*>> new_elements;
  730. Nonnull<const Value*> type_type = arena_->New<TypeType>();
  731. for (Nonnull<const Value*> value : tuple->elements()) {
  732. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value_as_type,
  733. Convert(value, type_type, source_loc));
  734. new_elements.push_back(value_as_type);
  735. }
  736. return arena_->New<TupleType>(std::move(new_elements));
  737. }
  738. default: {
  739. CARBON_CHECK(IsValueKindDependent(destination_type) ||
  740. isa<TypeType, ConstraintType>(destination_type))
  741. << "Can't convert value " << *value << " to type "
  742. << *destination_type;
  743. return value;
  744. }
  745. }
  746. CARBON_CHECK(tuple->elements().size() ==
  747. destination_element_types.size());
  748. std::vector<Nonnull<const Value*>> new_elements;
  749. for (size_t i = 0; i < tuple->elements().size(); ++i) {
  750. CARBON_ASSIGN_OR_RETURN(
  751. Nonnull<const Value*> val,
  752. Convert(tuple->elements()[i], destination_element_types[i],
  753. source_loc));
  754. new_elements.push_back(val);
  755. }
  756. return arena_->New<TupleValue>(std::move(new_elements));
  757. }
  758. case Value::Kind::AssociatedConstant: {
  759. CARBON_ASSIGN_OR_RETURN(
  760. Nonnull<const Value*> value,
  761. EvalAssociatedConstant(cast<AssociatedConstant>(value), source_loc));
  762. if (auto* new_const = dyn_cast<AssociatedConstant>(value)) {
  763. // TODO: Detect whether conversions are required in type-checking.
  764. if (isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  765. destination_type) &&
  766. isa<TypeType, ConstraintType, NamedConstraintType, InterfaceType>(
  767. new_const->constant().static_type())) {
  768. // No further conversions are required.
  769. return value;
  770. }
  771. // We need to convert this, and we don't know how because we don't have
  772. // the value yet.
  773. return ProgramError(source_loc)
  774. << "value of associated constant " << *value << " is not known";
  775. }
  776. return Convert(value, destination_type, source_loc);
  777. }
  778. }
  779. }
  780. auto Interpreter::CallDestructor(Nonnull<const DestructorDeclaration*> fun,
  781. Nonnull<const Value*> receiver)
  782. -> ErrorOr<Success> {
  783. const DestructorDeclaration& method = *fun;
  784. CARBON_CHECK(method.is_method());
  785. RuntimeScope method_scope(&heap_);
  786. BindingMap generic_args;
  787. // TODO: move this logic into PatternMatch, and call it here.
  788. auto p = &method.me_pattern().value();
  789. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  790. if (placeholder.value_node().has_value()) {
  791. method_scope.Bind(*placeholder.value_node(), receiver);
  792. }
  793. CARBON_CHECK(method.body().has_value())
  794. << "Calling a method that's missing a body";
  795. auto act = std::make_unique<StatementAction>(*method.body());
  796. return todo_.Spawn(std::unique_ptr<Action>(std::move(act)),
  797. std::move(method_scope));
  798. }
  799. auto Interpreter::CallFunction(const CallExpression& call,
  800. Nonnull<const Value*> fun,
  801. Nonnull<const Value*> arg,
  802. ImplWitnessMap&& witnesses) -> ErrorOr<Success> {
  803. if (trace_stream_) {
  804. **trace_stream_ << "calling function: " << *fun << "\n";
  805. }
  806. switch (fun->kind()) {
  807. case Value::Kind::AlternativeConstructorValue: {
  808. const auto& alt = cast<AlternativeConstructorValue>(*fun);
  809. return todo_.FinishAction(arena_->New<AlternativeValue>(
  810. alt.alt_name(), alt.choice_name(), arg));
  811. }
  812. case Value::Kind::FunctionValue: {
  813. const auto& fun_val = cast<FunctionValue>(*fun);
  814. const FunctionDeclaration& function = fun_val.declaration();
  815. if (!function.body().has_value()) {
  816. return ProgramError(call.source_loc())
  817. << "attempt to call function `" << function.name()
  818. << "` that has not been defined";
  819. }
  820. if (!function.is_type_checked()) {
  821. return ProgramError(call.source_loc())
  822. << "attempt to call function `" << function.name()
  823. << "` that has not been fully type-checked";
  824. }
  825. RuntimeScope binding_scope(&heap_);
  826. // Bring the class type arguments into scope.
  827. for (const auto& [bind, val] : fun_val.type_args()) {
  828. binding_scope.Initialize(bind, val);
  829. }
  830. // Bring the deduced type arguments into scope.
  831. for (const auto& [bind, val] : call.deduced_args()) {
  832. binding_scope.Initialize(bind, val);
  833. }
  834. // Bring the impl witness tables into scope.
  835. for (const auto& [impl_bind, witness] : witnesses) {
  836. binding_scope.Initialize(impl_bind, witness);
  837. }
  838. for (const auto& [impl_bind, witness] : fun_val.witnesses()) {
  839. binding_scope.Initialize(impl_bind, witness);
  840. }
  841. // Enter the binding scope to make any deduced arguments visible before
  842. // we resolve the parameter type.
  843. todo_.CurrentAction().StartScope(std::move(binding_scope));
  844. CARBON_ASSIGN_OR_RETURN(
  845. Nonnull<const Value*> converted_args,
  846. Convert(arg, &function.param_pattern().static_type(),
  847. call.source_loc()));
  848. RuntimeScope function_scope(&heap_);
  849. BindingMap generic_args;
  850. CARBON_CHECK(PatternMatch(
  851. &function.param_pattern().value(), converted_args, call.source_loc(),
  852. &function_scope, generic_args, trace_stream_, this->arena_));
  853. return todo_.Spawn(std::make_unique<StatementAction>(*function.body()),
  854. std::move(function_scope));
  855. }
  856. case Value::Kind::BoundMethodValue: {
  857. const auto& m = cast<BoundMethodValue>(*fun);
  858. const FunctionDeclaration& method = m.declaration();
  859. CARBON_CHECK(method.is_method());
  860. CARBON_ASSIGN_OR_RETURN(
  861. Nonnull<const Value*> converted_args,
  862. Convert(arg, &method.param_pattern().static_type(),
  863. call.source_loc()));
  864. RuntimeScope method_scope(&heap_);
  865. BindingMap generic_args;
  866. // Bind the receiver to the `me` parameter.
  867. auto p = &method.me_pattern().value();
  868. if (p->kind() == Value::Kind::BindingPlaceholderValue) {
  869. // TODO: move this logic into PatternMatch
  870. const auto& placeholder = cast<BindingPlaceholderValue>(*p);
  871. if (placeholder.value_node().has_value()) {
  872. method_scope.Bind(*placeholder.value_node(), m.receiver());
  873. }
  874. } else {
  875. CARBON_CHECK(PatternMatch(&method.me_pattern().value(), m.receiver(),
  876. call.source_loc(), &method_scope,
  877. generic_args, trace_stream_, this->arena_));
  878. }
  879. // Bind the arguments to the parameters.
  880. CARBON_CHECK(PatternMatch(&method.param_pattern().value(), converted_args,
  881. call.source_loc(), &method_scope, generic_args,
  882. trace_stream_, this->arena_));
  883. // Bring the class type arguments into scope.
  884. for (const auto& [bind, val] : m.type_args()) {
  885. method_scope.Initialize(bind->original(), val);
  886. }
  887. // Bring the deduced type arguments into scope.
  888. for (const auto& [bind, val] : call.deduced_args()) {
  889. method_scope.Initialize(bind->original(), val);
  890. }
  891. // Bring the impl witness tables into scope.
  892. for (const auto& [impl_bind, witness] : witnesses) {
  893. method_scope.Initialize(impl_bind->original(), witness);
  894. }
  895. for (const auto& [impl_bind, witness] : m.witnesses()) {
  896. method_scope.Initialize(impl_bind->original(), witness);
  897. }
  898. CARBON_CHECK(method.body().has_value())
  899. << "Calling a method that's missing a body";
  900. return todo_.Spawn(std::make_unique<StatementAction>(*method.body()),
  901. std::move(method_scope));
  902. }
  903. case Value::Kind::ParameterizedEntityName: {
  904. const auto& name = cast<ParameterizedEntityName>(*fun);
  905. const Declaration& decl = name.declaration();
  906. RuntimeScope params_scope(&heap_);
  907. BindingMap generic_args;
  908. CARBON_CHECK(PatternMatch(&name.params().value(), arg, call.source_loc(),
  909. &params_scope, generic_args, trace_stream_,
  910. this->arena_));
  911. Nonnull<const Bindings*> bindings =
  912. arena_->New<Bindings>(std::move(generic_args), std::move(witnesses));
  913. switch (decl.kind()) {
  914. case DeclarationKind::ClassDeclaration:
  915. return todo_.FinishAction(arena_->New<NominalClassType>(
  916. &cast<ClassDeclaration>(decl), bindings));
  917. case DeclarationKind::InterfaceDeclaration:
  918. return todo_.FinishAction(arena_->New<InterfaceType>(
  919. &cast<InterfaceDeclaration>(decl), bindings));
  920. case DeclarationKind::ConstraintDeclaration:
  921. return todo_.FinishAction(arena_->New<NamedConstraintType>(
  922. &cast<ConstraintDeclaration>(decl), bindings));
  923. case DeclarationKind::ChoiceDeclaration:
  924. return todo_.FinishAction(arena_->New<ChoiceType>(
  925. &cast<ChoiceDeclaration>(decl), bindings));
  926. default:
  927. CARBON_FATAL() << "unknown kind of ParameterizedEntityName " << decl;
  928. }
  929. }
  930. default:
  931. return ProgramError(call.source_loc())
  932. << "in call, expected a function, not " << *fun;
  933. }
  934. }
  935. auto Interpreter::StepExp() -> ErrorOr<Success> {
  936. Action& act = todo_.CurrentAction();
  937. const Expression& exp = cast<ExpressionAction>(act).expression();
  938. if (trace_stream_) {
  939. **trace_stream_ << "--- step exp " << exp << " ." << act.pos() << "."
  940. << " (" << exp.source_loc() << ") --->\n";
  941. }
  942. switch (exp.kind()) {
  943. case ExpressionKind::IndexExpression: {
  944. if (act.pos() == 0) {
  945. // { { e[i] :: C, E, F} :: S, H}
  946. // -> { { e :: [][i] :: C, E, F} :: S, H}
  947. return todo_.Spawn(std::make_unique<ExpressionAction>(
  948. &cast<IndexExpression>(exp).object()));
  949. } else if (act.pos() == 1) {
  950. return todo_.Spawn(std::make_unique<ExpressionAction>(
  951. &cast<IndexExpression>(exp).offset()));
  952. } else {
  953. // { { v :: [][i] :: C, E, F} :: S, H}
  954. // -> { { v_i :: C, E, F} : S, H}
  955. const auto& tuple = cast<TupleValue>(*act.results()[0]);
  956. int i = cast<IntValue>(*act.results()[1]).value();
  957. if (i < 0 || i >= static_cast<int>(tuple.elements().size())) {
  958. return ProgramError(exp.source_loc())
  959. << "index " << i << " out of range in " << tuple;
  960. }
  961. return todo_.FinishAction(tuple.elements()[i]);
  962. }
  963. }
  964. case ExpressionKind::TupleLiteral: {
  965. if (act.pos() <
  966. static_cast<int>(cast<TupleLiteral>(exp).fields().size())) {
  967. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  968. // H}
  969. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  970. // H}
  971. return todo_.Spawn(std::make_unique<ExpressionAction>(
  972. cast<TupleLiteral>(exp).fields()[act.pos()]));
  973. } else {
  974. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  975. }
  976. }
  977. case ExpressionKind::StructLiteral: {
  978. const auto& literal = cast<StructLiteral>(exp);
  979. if (act.pos() < static_cast<int>(literal.fields().size())) {
  980. return todo_.Spawn(std::make_unique<ExpressionAction>(
  981. &literal.fields()[act.pos()].expression()));
  982. } else {
  983. return todo_.FinishAction(
  984. CreateStruct(literal.fields(), act.results()));
  985. }
  986. }
  987. case ExpressionKind::SimpleMemberAccessExpression: {
  988. const auto& access = cast<SimpleMemberAccessExpression>(exp);
  989. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  990. if (act.pos() == 0) {
  991. // First, evaluate the first operand.
  992. if (access.is_addr_me_method()) {
  993. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  994. } else {
  995. return todo_.Spawn(
  996. std::make_unique<ExpressionAction>(&access.object()));
  997. }
  998. } else if (act.pos() == 1 && access.impl().has_value() &&
  999. !forming_member_name) {
  1000. // Next, if we're accessing an interface member, evaluate the `impl`
  1001. // expression to find the corresponding witness.
  1002. return todo_.Spawn(
  1003. std::make_unique<WitnessAction>(access.impl().value()));
  1004. } else {
  1005. // Finally, produce the result.
  1006. if (auto constant_value = access.constant_value()) {
  1007. CARBON_ASSIGN_OR_RETURN(
  1008. Nonnull<const Value*> instantiated,
  1009. InstantiateType(*constant_value, access.source_loc()));
  1010. return todo_.FinishAction(instantiated);
  1011. }
  1012. std::optional<Nonnull<const InterfaceType*>> found_in_interface =
  1013. access.found_in_interface();
  1014. if (found_in_interface) {
  1015. CARBON_ASSIGN_OR_RETURN(
  1016. Nonnull<const Value*> instantiated,
  1017. InstantiateType(*found_in_interface, exp.source_loc()));
  1018. found_in_interface = cast<InterfaceType>(instantiated);
  1019. }
  1020. if (const auto* member_name_type =
  1021. dyn_cast<TypeOfMemberName>(&access.static_type())) {
  1022. // The result is a member name, such as in `Type.field_name`. Form a
  1023. // suitable member name value.
  1024. CARBON_CHECK(phase() == Phase::CompileTime)
  1025. << "should not form MemberNames at runtime";
  1026. std::optional<const Value*> type_result;
  1027. if (!isa<InterfaceType, NamedConstraintType, ConstraintType>(
  1028. act.results()[0])) {
  1029. type_result = act.results()[0];
  1030. }
  1031. MemberName* member_name = arena_->New<MemberName>(
  1032. type_result, found_in_interface, member_name_type->member());
  1033. return todo_.FinishAction(member_name);
  1034. } else {
  1035. // The result is the value of the named field, such as in
  1036. // `value.field_name`. Extract the value within the given object.
  1037. std::optional<Nonnull<const Witness*>> witness;
  1038. if (access.impl().has_value()) {
  1039. witness = cast<Witness>(act.results()[1]);
  1040. }
  1041. FieldPath::Component member(access.member(), found_in_interface,
  1042. witness);
  1043. const Value* aggregate;
  1044. if (access.is_type_access()) {
  1045. CARBON_ASSIGN_OR_RETURN(
  1046. aggregate, InstantiateType(&access.object().static_type(),
  1047. access.source_loc()));
  1048. } else if (const auto* lvalue = dyn_cast<LValue>(act.results()[0])) {
  1049. CARBON_ASSIGN_OR_RETURN(
  1050. aggregate,
  1051. this->heap_.Read(lvalue->address(), exp.source_loc()));
  1052. } else {
  1053. aggregate = act.results()[0];
  1054. }
  1055. CARBON_ASSIGN_OR_RETURN(
  1056. Nonnull<const Value*> member_value,
  1057. aggregate->GetMember(arena_, FieldPath(member), exp.source_loc(),
  1058. act.results()[0]));
  1059. return todo_.FinishAction(member_value);
  1060. }
  1061. }
  1062. }
  1063. case ExpressionKind::CompoundMemberAccessExpression: {
  1064. const auto& access = cast<CompoundMemberAccessExpression>(exp);
  1065. bool forming_member_name = isa<TypeOfMemberName>(&access.static_type());
  1066. if (act.pos() == 0) {
  1067. // First, evaluate the first operand.
  1068. if (access.is_addr_me_method()) {
  1069. return todo_.Spawn(std::make_unique<LValAction>(&access.object()));
  1070. } else {
  1071. return todo_.Spawn(
  1072. std::make_unique<ExpressionAction>(&access.object()));
  1073. }
  1074. } else if (act.pos() == 1 && access.impl().has_value() &&
  1075. !forming_member_name) {
  1076. // Next, if we're accessing an interface member, evaluate the `impl`
  1077. // expression to find the corresponding witness.
  1078. return todo_.Spawn(
  1079. std::make_unique<WitnessAction>(access.impl().value()));
  1080. } else {
  1081. // Finally, produce the result.
  1082. if (auto constant_value = access.constant_value()) {
  1083. CARBON_ASSIGN_OR_RETURN(
  1084. Nonnull<const Value*> instantiated,
  1085. InstantiateType(*constant_value, access.source_loc()));
  1086. return todo_.FinishAction(instantiated);
  1087. }
  1088. std::optional<Nonnull<const InterfaceType*>> found_in_interface =
  1089. access.member().interface();
  1090. if (found_in_interface) {
  1091. CARBON_ASSIGN_OR_RETURN(
  1092. Nonnull<const Value*> instantiated,
  1093. InstantiateType(*found_in_interface, exp.source_loc()));
  1094. found_in_interface = cast<InterfaceType>(instantiated);
  1095. }
  1096. if (forming_member_name) {
  1097. // If we're forming a member name, we must be in the outer evaluation
  1098. // in `Type.(Interface.method)`. Produce the same method name with
  1099. // its `type` field set.
  1100. CARBON_CHECK(phase() == Phase::CompileTime)
  1101. << "should not form MemberNames at runtime";
  1102. CARBON_CHECK(!access.member().base_type().has_value())
  1103. << "compound member access forming a member name should be "
  1104. "performing impl lookup";
  1105. auto* member_name = arena_->New<MemberName>(
  1106. act.results()[0], found_in_interface, access.member().member());
  1107. return todo_.FinishAction(member_name);
  1108. } else {
  1109. // Access the object to find the named member.
  1110. Nonnull<const Value*> object = act.results()[0];
  1111. if (access.is_type_access()) {
  1112. CARBON_ASSIGN_OR_RETURN(
  1113. object, InstantiateType(&access.object().static_type(),
  1114. access.source_loc()));
  1115. }
  1116. std::optional<Nonnull<const Witness*>> witness;
  1117. if (access.impl().has_value()) {
  1118. witness = cast<Witness>(act.results()[1]);
  1119. } else {
  1120. CARBON_CHECK(access.member().base_type().has_value())
  1121. << "compound access should have base type or impl";
  1122. CARBON_ASSIGN_OR_RETURN(
  1123. object, Convert(object, *access.member().base_type(),
  1124. exp.source_loc()));
  1125. }
  1126. FieldPath::Component field(access.member().member(),
  1127. found_in_interface, witness);
  1128. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> member,
  1129. object->GetMember(arena_, FieldPath(field),
  1130. exp.source_loc(), object));
  1131. return todo_.FinishAction(member);
  1132. }
  1133. }
  1134. }
  1135. case ExpressionKind::IdentifierExpression: {
  1136. CARBON_CHECK(act.pos() == 0);
  1137. const auto& ident = cast<IdentifierExpression>(exp);
  1138. // { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
  1139. CARBON_ASSIGN_OR_RETURN(
  1140. Nonnull<const Value*> value,
  1141. todo_.ValueOfNode(ident.value_node(), ident.source_loc()));
  1142. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1143. CARBON_ASSIGN_OR_RETURN(
  1144. value, heap_.Read(lvalue->address(), exp.source_loc()));
  1145. }
  1146. return todo_.FinishAction(value);
  1147. }
  1148. case ExpressionKind::DotSelfExpression: {
  1149. CARBON_CHECK(act.pos() == 0);
  1150. const auto& dot_self = cast<DotSelfExpression>(exp);
  1151. return todo_.FinishAction(*dot_self.self_binding().symbolic_identity());
  1152. }
  1153. case ExpressionKind::IntLiteral:
  1154. CARBON_CHECK(act.pos() == 0);
  1155. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1156. return todo_.FinishAction(
  1157. arena_->New<IntValue>(cast<IntLiteral>(exp).value()));
  1158. case ExpressionKind::BoolLiteral:
  1159. CARBON_CHECK(act.pos() == 0);
  1160. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1161. return todo_.FinishAction(
  1162. arena_->New<BoolValue>(cast<BoolLiteral>(exp).value()));
  1163. case ExpressionKind::OperatorExpression: {
  1164. const auto& op = cast<OperatorExpression>(exp);
  1165. if (auto rewrite = op.rewritten_form()) {
  1166. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(*rewrite));
  1167. }
  1168. if (act.pos() != static_cast<int>(op.arguments().size())) {
  1169. // { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
  1170. // -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
  1171. Nonnull<const Expression*> arg = op.arguments()[act.pos()];
  1172. if (op.op() == Operator::AddressOf) {
  1173. return todo_.Spawn(std::make_unique<LValAction>(arg));
  1174. } else if ((op.op() == Operator::And || op.op() == Operator::Or) &&
  1175. act.pos() == 1) {
  1176. // Short-circuit evaluation for 'and' & 'or'
  1177. const auto* operand_value =
  1178. cast<BoolValue>(act.results()[act.pos() - 1]);
  1179. if ((op.op() == Operator::Or && operand_value->value()) ||
  1180. (op.op() == Operator::And && !operand_value->value())) {
  1181. return todo_.FinishAction(operand_value);
  1182. }
  1183. // No short-circuit, fall through to evaluate 2nd operand.
  1184. }
  1185. return todo_.Spawn(std::make_unique<ExpressionAction>(arg));
  1186. } else {
  1187. // { {v :: op(vs,[]) :: C, E, F} :: S, H}
  1188. // -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
  1189. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1190. EvalPrim(op.op(), &op.static_type(),
  1191. act.results(), exp.source_loc()));
  1192. return todo_.FinishAction(value);
  1193. }
  1194. }
  1195. case ExpressionKind::CallExpression: {
  1196. const auto& call = cast<CallExpression>(exp);
  1197. unsigned int num_impls = call.impls().size();
  1198. if (act.pos() == 0) {
  1199. // { {e1(e2) :: C, E, F} :: S, H}
  1200. // -> { {e1 :: [](e2) :: C, E, F} :: S, H}
  1201. return todo_.Spawn(
  1202. std::make_unique<ExpressionAction>(&call.function()));
  1203. } else if (act.pos() == 1) {
  1204. // { { v :: [](e) :: C, E, F} :: S, H}
  1205. // -> { { e :: v([]) :: C, E, F} :: S, H}
  1206. return todo_.Spawn(
  1207. std::make_unique<ExpressionAction>(&call.argument()));
  1208. } else if (num_impls > 0 && act.pos() < 2 + static_cast<int>(num_impls)) {
  1209. auto iter = call.impls().begin();
  1210. std::advance(iter, act.pos() - 2);
  1211. return todo_.Spawn(
  1212. std::make_unique<WitnessAction>(cast<Witness>(iter->second)));
  1213. } else if (act.pos() == 2 + static_cast<int>(num_impls)) {
  1214. // { { v2 :: v1([]) :: C, E, F} :: S, H}
  1215. // -> { {C',E',F'} :: {C, E, F} :: S, H}
  1216. ImplWitnessMap witnesses;
  1217. if (num_impls > 0) {
  1218. int i = 2;
  1219. for (const auto& [impl_bind, impl_exp] : call.impls()) {
  1220. witnesses[impl_bind] = act.results()[i];
  1221. ++i;
  1222. }
  1223. }
  1224. return CallFunction(call, act.results()[0], act.results()[1],
  1225. std::move(witnesses));
  1226. } else if (act.pos() == 3 + static_cast<int>(num_impls)) {
  1227. if (act.results().size() < 3 + num_impls) {
  1228. // Control fell through without explicit return.
  1229. return todo_.FinishAction(TupleValue::Empty());
  1230. } else {
  1231. return todo_.FinishAction(
  1232. act.results()[2 + static_cast<int>(num_impls)]);
  1233. }
  1234. } else {
  1235. CARBON_FATAL() << "in StepExp with Call pos " << act.pos();
  1236. }
  1237. }
  1238. case ExpressionKind::IntrinsicExpression: {
  1239. const auto& intrinsic = cast<IntrinsicExpression>(exp);
  1240. if (act.pos() == 0) {
  1241. return todo_.Spawn(
  1242. std::make_unique<ExpressionAction>(&intrinsic.args()));
  1243. }
  1244. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1245. const auto& args = cast<TupleValue>(*act.results()[0]).elements();
  1246. switch (cast<IntrinsicExpression>(exp).intrinsic()) {
  1247. case IntrinsicExpression::Intrinsic::Print: {
  1248. CARBON_ASSIGN_OR_RETURN(
  1249. Nonnull<const Value*> format_string_value,
  1250. Convert(args[0], arena_->New<StringType>(), exp.source_loc()));
  1251. const char* format_string =
  1252. cast<StringValue>(*format_string_value).value().c_str();
  1253. switch (args.size()) {
  1254. case 1:
  1255. llvm::outs() << llvm::formatv(format_string);
  1256. break;
  1257. case 2:
  1258. llvm::outs() << llvm::formatv(format_string,
  1259. cast<IntValue>(*args[1]).value());
  1260. break;
  1261. default:
  1262. CARBON_FATAL() << "Unexpected arg count: " << args.size();
  1263. }
  1264. // Implicit newline; currently no way to disable it.
  1265. llvm::outs() << "\n";
  1266. return todo_.FinishAction(TupleValue::Empty());
  1267. }
  1268. case IntrinsicExpression::Intrinsic::Assert: {
  1269. CARBON_CHECK(args.size() == 2);
  1270. CARBON_ASSIGN_OR_RETURN(
  1271. Nonnull<const Value*> condition,
  1272. Convert(args[0], arena_->New<BoolType>(), exp.source_loc()));
  1273. CARBON_ASSIGN_OR_RETURN(
  1274. Nonnull<const Value*> string_value,
  1275. Convert(args[1], arena_->New<StringType>(), exp.source_loc()));
  1276. bool condition_value = cast<BoolValue>(condition)->value();
  1277. if (!condition_value) {
  1278. return ProgramError(exp.source_loc()) << *string_value;
  1279. }
  1280. return todo_.FinishAction(TupleValue::Empty());
  1281. }
  1282. case IntrinsicExpression::Intrinsic::Alloc: {
  1283. CARBON_CHECK(args.size() == 1);
  1284. Address addr(heap_.AllocateValue(args[0]));
  1285. return todo_.FinishAction(arena_->New<PointerValue>(addr));
  1286. }
  1287. case IntrinsicExpression::Intrinsic::Dealloc: {
  1288. CARBON_CHECK(args.size() == 1);
  1289. heap_.Deallocate(cast<PointerValue>(args[0])->address());
  1290. return todo_.FinishAction(TupleValue::Empty());
  1291. }
  1292. case IntrinsicExpression::Intrinsic::Rand: {
  1293. CARBON_CHECK(args.size() == 2);
  1294. const auto& low = cast<IntValue>(*args[0]).value();
  1295. const auto& high = cast<IntValue>(*args[1]).value();
  1296. CARBON_CHECK(high > low);
  1297. // We avoid using std::uniform_int_distribution because it's not
  1298. // reproducible across builds/platforms.
  1299. int r = (generator() % (high - low)) + low;
  1300. return todo_.FinishAction(arena_->New<IntValue>(r));
  1301. }
  1302. case IntrinsicExpression::Intrinsic::IntEq: {
  1303. CARBON_CHECK(args.size() == 2);
  1304. auto lhs = cast<IntValue>(*args[0]).value();
  1305. auto rhs = cast<IntValue>(*args[1]).value();
  1306. auto* result = arena_->New<BoolValue>(lhs == rhs);
  1307. return todo_.FinishAction(result);
  1308. }
  1309. case IntrinsicExpression::Intrinsic::StrEq: {
  1310. CARBON_CHECK(args.size() == 2);
  1311. const auto& lhs = cast<StringValue>(*args[0]).value();
  1312. const auto& rhs = cast<StringValue>(*args[1]).value();
  1313. auto* result = arena_->New<BoolValue>(lhs == rhs);
  1314. return todo_.FinishAction(result);
  1315. }
  1316. case IntrinsicExpression::Intrinsic::IntCompare: {
  1317. CARBON_CHECK(args.size() == 2);
  1318. auto lhs = cast<IntValue>(*args[0]).value();
  1319. auto rhs = cast<IntValue>(*args[1]).value();
  1320. if (lhs < rhs) {
  1321. auto* result = arena_->New<IntValue>(-1);
  1322. return todo_.FinishAction(result);
  1323. }
  1324. if (lhs == rhs) {
  1325. auto* result = arena_->New<IntValue>(0);
  1326. return todo_.FinishAction(result);
  1327. }
  1328. auto* result = arena_->New<IntValue>(1);
  1329. return todo_.FinishAction(result);
  1330. }
  1331. case IntrinsicExpression::Intrinsic::StrCompare: {
  1332. CARBON_CHECK(args.size() == 2);
  1333. const auto& lhs = cast<StringValue>(*args[0]).value();
  1334. const auto& rhs = cast<StringValue>(*args[1]).value();
  1335. if (lhs < rhs) {
  1336. auto* result = arena_->New<IntValue>(-1);
  1337. return todo_.FinishAction(result);
  1338. }
  1339. if (lhs == rhs) {
  1340. auto* result = arena_->New<IntValue>(0);
  1341. return todo_.FinishAction(result);
  1342. }
  1343. auto* result = arena_->New<IntValue>(1);
  1344. return todo_.FinishAction(result);
  1345. }
  1346. case IntrinsicExpression::Intrinsic::IntBitComplement: {
  1347. CARBON_CHECK(args.size() == 1);
  1348. return todo_.FinishAction(
  1349. arena_->New<IntValue>(~cast<IntValue>(*args[0]).value()));
  1350. }
  1351. case IntrinsicExpression::Intrinsic::IntBitAnd: {
  1352. CARBON_CHECK(args.size() == 2);
  1353. return todo_.FinishAction(
  1354. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() &
  1355. cast<IntValue>(*args[1]).value()));
  1356. }
  1357. case IntrinsicExpression::Intrinsic::IntBitOr: {
  1358. CARBON_CHECK(args.size() == 2);
  1359. return todo_.FinishAction(
  1360. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() |
  1361. cast<IntValue>(*args[1]).value()));
  1362. }
  1363. case IntrinsicExpression::Intrinsic::IntBitXor: {
  1364. CARBON_CHECK(args.size() == 2);
  1365. return todo_.FinishAction(
  1366. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() ^
  1367. cast<IntValue>(*args[1]).value()));
  1368. }
  1369. case IntrinsicExpression::Intrinsic::IntLeftShift: {
  1370. CARBON_CHECK(args.size() == 2);
  1371. // TODO: Runtime error if RHS is too large.
  1372. return todo_.FinishAction(arena_->New<IntValue>(
  1373. static_cast<uint32_t>(cast<IntValue>(*args[0]).value())
  1374. << cast<IntValue>(*args[1]).value()));
  1375. }
  1376. case IntrinsicExpression::Intrinsic::IntRightShift: {
  1377. CARBON_CHECK(args.size() == 2);
  1378. // TODO: Runtime error if RHS is too large.
  1379. return todo_.FinishAction(
  1380. arena_->New<IntValue>(cast<IntValue>(*args[0]).value() >>
  1381. cast<IntValue>(*args[1]).value()));
  1382. }
  1383. }
  1384. }
  1385. case ExpressionKind::IntTypeLiteral: {
  1386. CARBON_CHECK(act.pos() == 0);
  1387. return todo_.FinishAction(arena_->New<IntType>());
  1388. }
  1389. case ExpressionKind::BoolTypeLiteral: {
  1390. CARBON_CHECK(act.pos() == 0);
  1391. return todo_.FinishAction(arena_->New<BoolType>());
  1392. }
  1393. case ExpressionKind::TypeTypeLiteral: {
  1394. CARBON_CHECK(act.pos() == 0);
  1395. return todo_.FinishAction(arena_->New<TypeType>());
  1396. }
  1397. case ExpressionKind::ContinuationTypeLiteral: {
  1398. CARBON_CHECK(act.pos() == 0);
  1399. return todo_.FinishAction(arena_->New<ContinuationType>());
  1400. }
  1401. case ExpressionKind::StringLiteral:
  1402. CARBON_CHECK(act.pos() == 0);
  1403. // { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
  1404. return todo_.FinishAction(
  1405. arena_->New<StringValue>(cast<StringLiteral>(exp).value()));
  1406. case ExpressionKind::StringTypeLiteral: {
  1407. CARBON_CHECK(act.pos() == 0);
  1408. return todo_.FinishAction(arena_->New<StringType>());
  1409. }
  1410. case ExpressionKind::FunctionTypeLiteral:
  1411. case ExpressionKind::StructTypeLiteral:
  1412. case ExpressionKind::ArrayTypeLiteral:
  1413. case ExpressionKind::ValueLiteral: {
  1414. CARBON_CHECK(act.pos() == 0);
  1415. auto* value = &cast<ConstantValueLiteral>(exp).constant_value();
  1416. CARBON_ASSIGN_OR_RETURN(
  1417. Nonnull<const Value*> destination,
  1418. InstantiateType(&exp.static_type(), exp.source_loc()));
  1419. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> result,
  1420. Convert(value, destination, exp.source_loc()));
  1421. return todo_.FinishAction(result);
  1422. }
  1423. case ExpressionKind::IfExpression: {
  1424. const auto& if_expr = cast<IfExpression>(exp);
  1425. if (act.pos() == 0) {
  1426. return todo_.Spawn(
  1427. std::make_unique<ExpressionAction>(&if_expr.condition()));
  1428. } else if (act.pos() == 1) {
  1429. const auto& condition = cast<BoolValue>(*act.results()[0]);
  1430. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1431. condition.value() ? &if_expr.then_expression()
  1432. : &if_expr.else_expression()));
  1433. } else {
  1434. return todo_.FinishAction(act.results()[1]);
  1435. }
  1436. break;
  1437. }
  1438. case ExpressionKind::WhereExpression: {
  1439. auto rewrite = cast<WhereExpression>(exp).rewritten_form();
  1440. CARBON_CHECK(rewrite) << "where expression should be rewritten";
  1441. return todo_.ReplaceWith(std::make_unique<ExpressionAction>(*rewrite));
  1442. }
  1443. case ExpressionKind::BuiltinConvertExpression: {
  1444. const auto& convert_expr = cast<BuiltinConvertExpression>(exp);
  1445. if (act.pos() == 0) {
  1446. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1447. convert_expr.source_expression()));
  1448. } else {
  1449. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> destination,
  1450. InstantiateType(&convert_expr.static_type(),
  1451. convert_expr.source_loc()));
  1452. // TODO: Remove all calls to Convert other than this one. We shouldn't
  1453. // need them any more.
  1454. CARBON_ASSIGN_OR_RETURN(
  1455. Nonnull<const Value*> result,
  1456. Convert(act.results()[0], destination, convert_expr.source_loc()));
  1457. return todo_.FinishAction(result);
  1458. }
  1459. }
  1460. case ExpressionKind::UnimplementedExpression:
  1461. CARBON_FATAL() << "Unimplemented: " << exp;
  1462. } // switch (exp->kind)
  1463. }
  1464. auto Interpreter::StepWitness() -> ErrorOr<Success> {
  1465. Action& act = todo_.CurrentAction();
  1466. const Witness* witness = cast<WitnessAction>(act).witness();
  1467. if (trace_stream_) {
  1468. **trace_stream_ << "--- step witness " << *witness << " ." << act.pos()
  1469. << ". --->\n";
  1470. }
  1471. switch (witness->kind()) {
  1472. case Value::Kind::BindingWitness: {
  1473. const ImplBinding* binding = cast<BindingWitness>(witness)->binding();
  1474. CARBON_ASSIGN_OR_RETURN(
  1475. Nonnull<const Value*> value,
  1476. todo_.ValueOfNode(binding, binding->type_var()->source_loc()));
  1477. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1478. // TODO: Why do we store values for impl bindings on the heap?
  1479. CARBON_ASSIGN_OR_RETURN(
  1480. value,
  1481. heap_.Read(lvalue->address(), binding->type_var()->source_loc()));
  1482. }
  1483. return todo_.FinishAction(value);
  1484. }
  1485. case Value::Kind::ConstraintWitness: {
  1486. llvm::ArrayRef<Nonnull<const Witness*>> witnesses =
  1487. cast<ConstraintWitness>(witness)->witnesses();
  1488. if (act.pos() < static_cast<int>(witnesses.size())) {
  1489. return todo_.Spawn(
  1490. std::make_unique<WitnessAction>(witnesses[act.pos()]));
  1491. }
  1492. std::vector<Nonnull<const Witness*>> new_witnesses;
  1493. new_witnesses.reserve(witnesses.size());
  1494. for (const auto* witness : act.results()) {
  1495. new_witnesses.push_back(cast<Witness>(witness));
  1496. }
  1497. return todo_.FinishAction(
  1498. arena_->New<ConstraintWitness>(std::move(new_witnesses)));
  1499. }
  1500. case Value::Kind::ConstraintImplWitness: {
  1501. const auto* constraint_impl = cast<ConstraintImplWitness>(witness);
  1502. if (act.pos() == 0) {
  1503. return todo_.Spawn(std::make_unique<WitnessAction>(
  1504. constraint_impl->constraint_witness()));
  1505. }
  1506. return todo_.FinishAction(ConstraintImplWitness::Make(
  1507. arena_, cast<Witness>(act.results()[0]), constraint_impl->index()));
  1508. }
  1509. case Value::Kind::ImplWitness: {
  1510. const auto* impl_witness = cast<ImplWitness>(witness);
  1511. CARBON_ASSIGN_OR_RETURN(
  1512. Nonnull<const Bindings*> new_bindings,
  1513. InstantiateBindings(&impl_witness->bindings(),
  1514. impl_witness->declaration().source_loc()));
  1515. return todo_.FinishAction(
  1516. new_bindings == &impl_witness->bindings()
  1517. ? impl_witness
  1518. : arena_->New<ImplWitness>(&impl_witness->declaration(),
  1519. new_bindings));
  1520. }
  1521. default:
  1522. CARBON_FATAL() << "unexpected kind of witness " << *witness;
  1523. }
  1524. }
  1525. auto Interpreter::StepPattern() -> ErrorOr<Success> {
  1526. Action& act = todo_.CurrentAction();
  1527. const Pattern& pattern = cast<PatternAction>(act).pattern();
  1528. if (trace_stream_) {
  1529. **trace_stream_ << "--- step pattern " << pattern << " ." << act.pos()
  1530. << ". (" << pattern.source_loc() << ") --->\n";
  1531. }
  1532. switch (pattern.kind()) {
  1533. case PatternKind::AutoPattern: {
  1534. CARBON_CHECK(act.pos() == 0);
  1535. return todo_.FinishAction(arena_->New<AutoType>());
  1536. }
  1537. case PatternKind::BindingPattern: {
  1538. const auto& binding = cast<BindingPattern>(pattern);
  1539. if (binding.name() != AnonymousName) {
  1540. return todo_.FinishAction(
  1541. arena_->New<BindingPlaceholderValue>(&binding));
  1542. } else {
  1543. return todo_.FinishAction(arena_->New<BindingPlaceholderValue>());
  1544. }
  1545. }
  1546. case PatternKind::GenericBinding: {
  1547. const auto& binding = cast<GenericBinding>(pattern);
  1548. return todo_.FinishAction(arena_->New<VariableType>(&binding));
  1549. }
  1550. case PatternKind::TuplePattern: {
  1551. const auto& tuple = cast<TuplePattern>(pattern);
  1552. if (act.pos() < static_cast<int>(tuple.fields().size())) {
  1553. // { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
  1554. // H}
  1555. // -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
  1556. // H}
  1557. return todo_.Spawn(
  1558. std::make_unique<PatternAction>(tuple.fields()[act.pos()]));
  1559. } else {
  1560. return todo_.FinishAction(arena_->New<TupleValue>(act.results()));
  1561. }
  1562. }
  1563. case PatternKind::AlternativePattern: {
  1564. const auto& alternative = cast<AlternativePattern>(pattern);
  1565. if (act.pos() == 0) {
  1566. return todo_.Spawn(
  1567. std::make_unique<ExpressionAction>(&alternative.choice_type()));
  1568. } else if (act.pos() == 1) {
  1569. return todo_.Spawn(
  1570. std::make_unique<PatternAction>(&alternative.arguments()));
  1571. } else {
  1572. CARBON_CHECK(act.pos() == 2);
  1573. const auto& choice_type = cast<ChoiceType>(*act.results()[0]);
  1574. return todo_.FinishAction(arena_->New<AlternativeValue>(
  1575. alternative.alternative_name(), choice_type.name(),
  1576. act.results()[1]));
  1577. }
  1578. }
  1579. case PatternKind::ExpressionPattern:
  1580. if (act.pos() == 0) {
  1581. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1582. &cast<ExpressionPattern>(pattern).expression()));
  1583. } else {
  1584. return todo_.FinishAction(act.results()[0]);
  1585. }
  1586. case PatternKind::VarPattern:
  1587. if (act.pos() == 0) {
  1588. return todo_.Spawn(std::make_unique<PatternAction>(
  1589. &cast<VarPattern>(pattern).pattern()));
  1590. } else {
  1591. return todo_.FinishAction(act.results()[0]);
  1592. }
  1593. case PatternKind::AddrPattern:
  1594. const auto& addr = cast<AddrPattern>(pattern);
  1595. if (act.pos() == 0) {
  1596. return todo_.Spawn(std::make_unique<PatternAction>(&addr.binding()));
  1597. } else {
  1598. return todo_.FinishAction(arena_->New<AddrValue>(act.results()[0]));
  1599. }
  1600. break;
  1601. }
  1602. }
  1603. auto Interpreter::StepStmt() -> ErrorOr<Success> {
  1604. Action& act = todo_.CurrentAction();
  1605. const Statement& stmt = cast<StatementAction>(act).statement();
  1606. if (trace_stream_) {
  1607. **trace_stream_ << "--- step stmt ";
  1608. stmt.PrintDepth(1, **trace_stream_);
  1609. **trace_stream_ << " ." << act.pos() << ". "
  1610. << "(" << stmt.source_loc() << ") --->\n";
  1611. }
  1612. switch (stmt.kind()) {
  1613. case StatementKind::Match: {
  1614. const auto& match_stmt = cast<Match>(stmt);
  1615. if (act.pos() == 0) {
  1616. // { { (match (e) ...) :: C, E, F} :: S, H}
  1617. // -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
  1618. act.StartScope(RuntimeScope(&heap_));
  1619. return todo_.Spawn(
  1620. std::make_unique<ExpressionAction>(&match_stmt.expression()));
  1621. } else {
  1622. int clause_num = act.pos() - 1;
  1623. if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
  1624. return todo_.FinishAction();
  1625. }
  1626. auto c = match_stmt.clauses()[clause_num];
  1627. RuntimeScope matches(&heap_);
  1628. BindingMap generic_args;
  1629. CARBON_ASSIGN_OR_RETURN(
  1630. Nonnull<const Value*> val,
  1631. Convert(act.results()[0], &c.pattern().static_type(),
  1632. stmt.source_loc()));
  1633. if (PatternMatch(&c.pattern().value(), val, stmt.source_loc(), &matches,
  1634. generic_args, trace_stream_, this->arena_)) {
  1635. // Ensure we don't process any more clauses.
  1636. act.set_pos(match_stmt.clauses().size() + 1);
  1637. todo_.MergeScope(std::move(matches));
  1638. return todo_.Spawn(std::make_unique<StatementAction>(&c.statement()));
  1639. } else {
  1640. return todo_.RunAgain();
  1641. }
  1642. }
  1643. }
  1644. case StatementKind::For: {
  1645. constexpr int TargetVarPosInResult = 0;
  1646. constexpr int CurrentIndexPosInResult = 1;
  1647. constexpr int EndIndexPosInResult = 2;
  1648. constexpr int LoopVarPosInResult = 3;
  1649. if (act.pos() == 0) {
  1650. return todo_.Spawn(
  1651. std::make_unique<ExpressionAction>(&cast<For>(stmt).loop_target()));
  1652. }
  1653. if (act.pos() == 1) {
  1654. const auto* source_array =
  1655. cast<TupleValue>(act.results()[TargetVarPosInResult]);
  1656. auto end_index = static_cast<int>(source_array->elements().size());
  1657. if (end_index == 0) {
  1658. return todo_.FinishAction();
  1659. }
  1660. act.AddResult(arena_->New<IntValue>(0));
  1661. act.AddResult(arena_->New<IntValue>(end_index));
  1662. return todo_.Spawn(std::make_unique<PatternAction>(
  1663. &cast<For>(stmt).variable_declaration()));
  1664. }
  1665. if (act.pos() == 2) {
  1666. const auto* loop_var =
  1667. cast<BindingPlaceholderValue>(act.results()[LoopVarPosInResult]);
  1668. const auto* source_array =
  1669. cast<TupleValue>(act.results()[TargetVarPosInResult]);
  1670. auto start_index =
  1671. cast<IntValue>(act.results()[CurrentIndexPosInResult])->value();
  1672. todo_.Initialize(*(loop_var->value_node()),
  1673. source_array->elements()[start_index]);
  1674. act.ReplaceResult(CurrentIndexPosInResult,
  1675. arena_->New<IntValue>(start_index + 1));
  1676. return todo_.Spawn(
  1677. std::make_unique<StatementAction>(&cast<For>(stmt).body()));
  1678. }
  1679. if (act.pos() >= 3) {
  1680. auto current_index =
  1681. cast<IntValue>(act.results()[CurrentIndexPosInResult])->value();
  1682. auto end_index =
  1683. cast<IntValue>(act.results()[EndIndexPosInResult])->value();
  1684. if (current_index < end_index) {
  1685. const auto* source_array =
  1686. cast<const TupleValue>(act.results()[TargetVarPosInResult]);
  1687. const auto* loop_var = cast<const BindingPlaceholderValue>(
  1688. act.results()[LoopVarPosInResult]);
  1689. CARBON_ASSIGN_OR_RETURN(
  1690. Nonnull<const Value*> assigned_array_element,
  1691. todo_.ValueOfNode(*(loop_var->value_node()), stmt.source_loc()));
  1692. const auto* lvalue = cast<LValue>(assigned_array_element);
  1693. CARBON_RETURN_IF_ERROR(heap_.Write(
  1694. lvalue->address(), source_array->elements()[current_index],
  1695. stmt.source_loc()));
  1696. act.ReplaceResult(CurrentIndexPosInResult,
  1697. arena_->New<IntValue>(current_index + 1));
  1698. return todo_.Spawn(
  1699. std::make_unique<StatementAction>(&cast<For>(stmt).body()));
  1700. }
  1701. }
  1702. return todo_.FinishAction();
  1703. }
  1704. case StatementKind::While:
  1705. // TODO: Rewrite While to use ReplaceResult to store condition result.
  1706. // This will remove the inconsistency between the while and for
  1707. // loops.
  1708. if (act.pos() % 2 == 0) {
  1709. // { { (while (e) s) :: C, E, F} :: S, H}
  1710. // -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
  1711. act.Clear();
  1712. return todo_.Spawn(
  1713. std::make_unique<ExpressionAction>(&cast<While>(stmt).condition()));
  1714. } else {
  1715. CARBON_ASSIGN_OR_RETURN(
  1716. Nonnull<const Value*> condition,
  1717. Convert(act.results().back(), arena_->New<BoolType>(),
  1718. stmt.source_loc()));
  1719. if (cast<BoolValue>(*condition).value()) {
  1720. // { {true :: (while ([]) s) :: C, E, F} :: S, H}
  1721. // -> { { s :: (while (e) s) :: C, E, F } :: S, H}
  1722. return todo_.Spawn(
  1723. std::make_unique<StatementAction>(&cast<While>(stmt).body()));
  1724. } else {
  1725. // { {false :: (while ([]) s) :: C, E, F} :: S, H}
  1726. // -> { { C, E, F } :: S, H}
  1727. return todo_.FinishAction();
  1728. }
  1729. }
  1730. case StatementKind::Break: {
  1731. CARBON_CHECK(act.pos() == 0);
  1732. // { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1733. // -> { { C, E', F} :: S, H}
  1734. return todo_.UnwindPast(&cast<Break>(stmt).loop());
  1735. }
  1736. case StatementKind::Continue: {
  1737. CARBON_CHECK(act.pos() == 0);
  1738. // { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
  1739. // -> { { (while (e) s) :: C, E', F} :: S, H}
  1740. return todo_.UnwindTo(&cast<Continue>(stmt).loop());
  1741. }
  1742. case StatementKind::Block: {
  1743. const auto& block = cast<Block>(stmt);
  1744. if (act.pos() >= static_cast<int>(block.statements().size())) {
  1745. // If the position is past the end of the block, end processing. Note
  1746. // that empty blocks immediately end.
  1747. return todo_.FinishAction();
  1748. }
  1749. // Initialize a scope when starting a block.
  1750. if (act.pos() == 0) {
  1751. act.StartScope(RuntimeScope(&heap_));
  1752. }
  1753. // Process the next statement in the block. The position will be
  1754. // incremented as part of Spawn.
  1755. return todo_.Spawn(
  1756. std::make_unique<StatementAction>(block.statements()[act.pos()]));
  1757. }
  1758. case StatementKind::VariableDefinition: {
  1759. const auto& definition = cast<VariableDefinition>(stmt);
  1760. if (act.pos() == 0 && definition.has_init()) {
  1761. // { {(var x = e) :: C, E, F} :: S, H}
  1762. // -> { {e :: (var x = []) :: C, E, F} :: S, H}
  1763. return todo_.Spawn(
  1764. std::make_unique<ExpressionAction>(&definition.init()));
  1765. } else {
  1766. // { { v :: (x = []) :: C, E, F} :: S, H}
  1767. // -> { { C, E(x := a), F} :: S, H(a := copy(v))}
  1768. Nonnull<const Value*> p =
  1769. &cast<VariableDefinition>(stmt).pattern().value();
  1770. Nonnull<const Value*> v;
  1771. if (definition.has_init()) {
  1772. CARBON_ASSIGN_OR_RETURN(
  1773. v, Convert(act.results()[0], &definition.pattern().static_type(),
  1774. stmt.source_loc()));
  1775. } else {
  1776. v = arena_->New<UninitializedValue>(p);
  1777. }
  1778. RuntimeScope matches(&heap_);
  1779. BindingMap generic_args;
  1780. CARBON_CHECK(PatternMatch(p, v, stmt.source_loc(), &matches,
  1781. generic_args, trace_stream_, this->arena_))
  1782. << stmt.source_loc()
  1783. << ": internal error in variable definition, match failed";
  1784. todo_.MergeScope(std::move(matches));
  1785. return todo_.FinishAction();
  1786. }
  1787. }
  1788. case StatementKind::ExpressionStatement:
  1789. if (act.pos() == 0) {
  1790. // { {e :: C, E, F} :: S, H}
  1791. // -> { {e :: C, E, F} :: S, H}
  1792. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1793. &cast<ExpressionStatement>(stmt).expression()));
  1794. } else {
  1795. return todo_.FinishAction();
  1796. }
  1797. case StatementKind::Assign: {
  1798. const auto& assign = cast<Assign>(stmt);
  1799. if (act.pos() == 0) {
  1800. // { {(lv = e) :: C, E, F} :: S, H}
  1801. // -> { {lv :: ([] = e) :: C, E, F} :: S, H}
  1802. return todo_.Spawn(std::make_unique<LValAction>(&assign.lhs()));
  1803. } else if (act.pos() == 1) {
  1804. // { { a :: ([] = e) :: C, E, F} :: S, H}
  1805. // -> { { e :: (a = []) :: C, E, F} :: S, H}
  1806. return todo_.Spawn(std::make_unique<ExpressionAction>(&assign.rhs()));
  1807. } else {
  1808. // { { v :: (a = []) :: C, E, F} :: S, H}
  1809. // -> { { C, E, F} :: S, H(a := v)}
  1810. const auto& lval = cast<LValue>(*act.results()[0]);
  1811. CARBON_ASSIGN_OR_RETURN(
  1812. Nonnull<const Value*> rval,
  1813. Convert(act.results()[1], &assign.lhs().static_type(),
  1814. stmt.source_loc()));
  1815. CARBON_RETURN_IF_ERROR(
  1816. heap_.Write(lval.address(), rval, stmt.source_loc()));
  1817. return todo_.FinishAction();
  1818. }
  1819. }
  1820. case StatementKind::If:
  1821. if (act.pos() == 0) {
  1822. // { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1823. // -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
  1824. return todo_.Spawn(
  1825. std::make_unique<ExpressionAction>(&cast<If>(stmt).condition()));
  1826. } else if (act.pos() == 1) {
  1827. CARBON_ASSIGN_OR_RETURN(
  1828. Nonnull<const Value*> condition,
  1829. Convert(act.results()[0], arena_->New<BoolType>(),
  1830. stmt.source_loc()));
  1831. if (cast<BoolValue>(*condition).value()) {
  1832. // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1833. // S, H}
  1834. // -> { { then_stmt :: C, E, F } :: S, H}
  1835. return todo_.Spawn(
  1836. std::make_unique<StatementAction>(&cast<If>(stmt).then_block()));
  1837. } else if (cast<If>(stmt).else_block()) {
  1838. // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} ::
  1839. // S, H}
  1840. // -> { { else_stmt :: C, E, F } :: S, H}
  1841. return todo_.Spawn(
  1842. std::make_unique<StatementAction>(*cast<If>(stmt).else_block()));
  1843. } else {
  1844. return todo_.FinishAction();
  1845. }
  1846. } else {
  1847. return todo_.FinishAction();
  1848. }
  1849. case StatementKind::ReturnVar: {
  1850. const auto& ret_var = cast<ReturnVar>(stmt);
  1851. const ValueNodeView& value_node = ret_var.value_node();
  1852. if (trace_stream_) {
  1853. **trace_stream_ << "--- step returned var "
  1854. << cast<BindingPattern>(value_node.base()).name()
  1855. << " ." << act.pos() << "."
  1856. << " (" << stmt.source_loc() << ") --->\n";
  1857. }
  1858. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> value,
  1859. todo_.ValueOfNode(value_node, stmt.source_loc()));
  1860. if (const auto* lvalue = dyn_cast<LValue>(value)) {
  1861. CARBON_ASSIGN_OR_RETURN(
  1862. value, heap_.Read(lvalue->address(), ret_var.source_loc()));
  1863. }
  1864. const CallableDeclaration& function = cast<Return>(stmt).function();
  1865. CARBON_ASSIGN_OR_RETURN(
  1866. Nonnull<const Value*> return_value,
  1867. Convert(value, &function.return_term().static_type(),
  1868. stmt.source_loc()));
  1869. return todo_.UnwindPast(*function.body(), return_value);
  1870. }
  1871. case StatementKind::ReturnExpression:
  1872. if (act.pos() == 0) {
  1873. // { {return e :: C, E, F} :: S, H}
  1874. // -> { {e :: return [] :: C, E, F} :: S, H}
  1875. return todo_.Spawn(std::make_unique<ExpressionAction>(
  1876. &cast<ReturnExpression>(stmt).expression()));
  1877. } else {
  1878. // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
  1879. // -> { {v :: C', E', F'} :: S, H}
  1880. const CallableDeclaration& function = cast<Return>(stmt).function();
  1881. CARBON_ASSIGN_OR_RETURN(
  1882. Nonnull<const Value*> return_value,
  1883. Convert(act.results()[0], &function.return_term().static_type(),
  1884. stmt.source_loc()));
  1885. return todo_.UnwindPast(*function.body(), return_value);
  1886. }
  1887. case StatementKind::Continuation: {
  1888. CARBON_CHECK(act.pos() == 0);
  1889. const auto& continuation = cast<Continuation>(stmt);
  1890. // Create a continuation object by creating a frame similar the
  1891. // way one is created in a function call.
  1892. auto* fragment = arena_->New<ContinuationValue::StackFragment>();
  1893. stack_fragments_.push_back(fragment);
  1894. todo_.InitializeFragment(*fragment, &continuation.body());
  1895. // Bind the continuation object to the continuation variable
  1896. todo_.Initialize(&cast<Continuation>(stmt),
  1897. arena_->New<ContinuationValue>(fragment));
  1898. return todo_.FinishAction();
  1899. }
  1900. case StatementKind::Run: {
  1901. const auto& run = cast<Run>(stmt);
  1902. if (act.pos() == 0) {
  1903. // Evaluate the argument of the run statement.
  1904. return todo_.Spawn(std::make_unique<ExpressionAction>(&run.argument()));
  1905. } else if (act.pos() == 1) {
  1906. // Push the continuation onto the current stack.
  1907. return todo_.Resume(cast<const ContinuationValue>(act.results()[0]));
  1908. } else {
  1909. return todo_.FinishAction();
  1910. }
  1911. }
  1912. case StatementKind::Await:
  1913. CARBON_CHECK(act.pos() == 0);
  1914. return todo_.Suspend();
  1915. }
  1916. }
  1917. auto Interpreter::StepDeclaration() -> ErrorOr<Success> {
  1918. Action& act = todo_.CurrentAction();
  1919. const Declaration& decl = cast<DeclarationAction>(act).declaration();
  1920. if (trace_stream_) {
  1921. **trace_stream_ << "--- step decl ";
  1922. decl.PrintID(**trace_stream_);
  1923. **trace_stream_ << " ." << act.pos() << ". "
  1924. << "(" << decl.source_loc() << ") --->\n";
  1925. }
  1926. switch (decl.kind()) {
  1927. case DeclarationKind::VariableDeclaration: {
  1928. const auto& var_decl = cast<VariableDeclaration>(decl);
  1929. if (var_decl.has_initializer()) {
  1930. if (act.pos() == 0) {
  1931. return todo_.Spawn(
  1932. std::make_unique<ExpressionAction>(&var_decl.initializer()));
  1933. } else {
  1934. CARBON_ASSIGN_OR_RETURN(
  1935. Nonnull<const Value*> v,
  1936. Convert(act.results()[0], &var_decl.binding().static_type(),
  1937. var_decl.source_loc()));
  1938. todo_.Initialize(&var_decl.binding(), v);
  1939. return todo_.FinishAction();
  1940. }
  1941. } else {
  1942. Nonnull<const Value*> v =
  1943. arena_->New<UninitializedValue>(&var_decl.binding().value());
  1944. todo_.Initialize(&var_decl.binding(), v);
  1945. return todo_.FinishAction();
  1946. }
  1947. }
  1948. case DeclarationKind::DestructorDeclaration:
  1949. case DeclarationKind::FunctionDeclaration:
  1950. case DeclarationKind::ClassDeclaration:
  1951. case DeclarationKind::MixinDeclaration:
  1952. case DeclarationKind::MixDeclaration:
  1953. case DeclarationKind::ChoiceDeclaration:
  1954. case DeclarationKind::InterfaceDeclaration:
  1955. case DeclarationKind::ConstraintDeclaration:
  1956. case DeclarationKind::InterfaceExtendsDeclaration:
  1957. case DeclarationKind::InterfaceImplDeclaration:
  1958. case DeclarationKind::AssociatedConstantDeclaration:
  1959. case DeclarationKind::ImplDeclaration:
  1960. case DeclarationKind::SelfDeclaration:
  1961. case DeclarationKind::AliasDeclaration:
  1962. // These declarations have no run-time effects.
  1963. return todo_.FinishAction();
  1964. }
  1965. }
  1966. auto Interpreter::StepDestroy() -> ErrorOr<Success> {
  1967. // TODO: find a way to avoid dyn_cast in this code, and instead use static
  1968. // type information the way the compiler would.
  1969. Action& act = todo_.CurrentAction();
  1970. DestroyAction& destroy_act = cast<DestroyAction>(act);
  1971. if (act.pos() == 0) {
  1972. if (const auto* class_obj =
  1973. dyn_cast<NominalClassValue>(destroy_act.value())) {
  1974. const auto& class_type = cast<NominalClassType>(class_obj->type());
  1975. const auto& class_dec = class_type.declaration();
  1976. if (class_dec.destructor().has_value()) {
  1977. return CallDestructor(*class_dec.destructor(), class_obj);
  1978. }
  1979. }
  1980. }
  1981. if (const auto* tuple = dyn_cast<TupleValue>(destroy_act.value())) {
  1982. if (tuple->elements().size() > 0) {
  1983. int index = tuple->elements().size() - act.pos() - 1;
  1984. if (index >= 0) {
  1985. const auto& item = tuple->elements()[index];
  1986. if (const auto* class_obj = dyn_cast<NominalClassValue>(item)) {
  1987. const auto& class_type = cast<NominalClassType>(class_obj->type());
  1988. const auto& class_dec = class_type.declaration();
  1989. if (class_dec.destructor().has_value()) {
  1990. return CallDestructor(*class_dec.destructor(), class_obj);
  1991. }
  1992. }
  1993. if (item->kind() == Value::Kind::TupleValue) {
  1994. return todo_.Spawn(
  1995. std::make_unique<DestroyAction>(destroy_act.lvalue(), item));
  1996. }
  1997. // Type of tuple element is integral type e.g. i32
  1998. // or the type has no destructor
  1999. }
  2000. }
  2001. }
  2002. if (act.pos() > 0) {
  2003. if (const auto* class_obj =
  2004. dyn_cast<NominalClassValue>(destroy_act.value())) {
  2005. const auto& class_type = cast<NominalClassType>(class_obj->type());
  2006. const auto& class_dec = class_type.declaration();
  2007. int index = class_dec.members().size() - act.pos();
  2008. if (index >= 0 && index < static_cast<int>(class_dec.members().size())) {
  2009. const auto& member = class_dec.members()[index];
  2010. if (const auto* var = dyn_cast<VariableDeclaration>(member)) {
  2011. Address object = destroy_act.lvalue()->address();
  2012. Address mem = object.SubobjectAddress(Member(var));
  2013. SourceLocation source_loc("destructor", 1);
  2014. auto v = heap_.Read(mem, source_loc);
  2015. return todo_.Spawn(
  2016. std::make_unique<DestroyAction>(destroy_act.lvalue(), *v));
  2017. }
  2018. }
  2019. }
  2020. }
  2021. todo_.Pop();
  2022. return Success();
  2023. }
  2024. auto Interpreter::StepCleanUp() -> ErrorOr<Success> {
  2025. Action& act = todo_.CurrentAction();
  2026. CleanupAction& cleanup = cast<CleanupAction>(act);
  2027. if (act.pos() < cleanup.allocations_count()) {
  2028. auto allocation =
  2029. act.scope()->allocations()[cleanup.allocations_count() - act.pos() - 1];
  2030. auto lvalue = arena_->New<LValue>(Address(allocation));
  2031. SourceLocation source_loc("destructor", 1);
  2032. auto value = heap_.Read(lvalue->address(), source_loc);
  2033. // Step over uninitialized values
  2034. if (value.ok()) {
  2035. return todo_.Spawn(std::make_unique<DestroyAction>(lvalue, *value));
  2036. }
  2037. }
  2038. todo_.Pop();
  2039. return Success();
  2040. }
  2041. // State transition.
  2042. auto Interpreter::Step() -> ErrorOr<Success> {
  2043. Action& act = todo_.CurrentAction();
  2044. switch (act.kind()) {
  2045. case Action::Kind::LValAction:
  2046. CARBON_RETURN_IF_ERROR(StepLvalue());
  2047. break;
  2048. case Action::Kind::ExpressionAction:
  2049. CARBON_RETURN_IF_ERROR(StepExp());
  2050. break;
  2051. case Action::Kind::WitnessAction:
  2052. CARBON_RETURN_IF_ERROR(StepWitness());
  2053. break;
  2054. case Action::Kind::PatternAction:
  2055. CARBON_RETURN_IF_ERROR(StepPattern());
  2056. break;
  2057. case Action::Kind::StatementAction:
  2058. CARBON_RETURN_IF_ERROR(StepStmt());
  2059. break;
  2060. case Action::Kind::DeclarationAction:
  2061. CARBON_RETURN_IF_ERROR(StepDeclaration());
  2062. break;
  2063. case Action::Kind::CleanUpAction:
  2064. CARBON_RETURN_IF_ERROR(StepCleanUp());
  2065. break;
  2066. case Action::Kind::DestroyAction:
  2067. CARBON_RETURN_IF_ERROR(StepDestroy());
  2068. break;
  2069. case Action::Kind::ScopeAction:
  2070. CARBON_FATAL() << "ScopeAction escaped ActionStack";
  2071. case Action::Kind::RecursiveAction:
  2072. CARBON_FATAL() << "Tried to step a RecursiveAction";
  2073. } // switch
  2074. return Success();
  2075. }
  2076. auto Interpreter::RunAllSteps(std::unique_ptr<Action> action)
  2077. -> ErrorOr<Success> {
  2078. if (trace_stream_) {
  2079. PrintState(**trace_stream_);
  2080. }
  2081. todo_.Start(std::move(action));
  2082. while (!todo_.IsEmpty()) {
  2083. CARBON_RETURN_IF_ERROR(Step());
  2084. if (trace_stream_) {
  2085. PrintState(**trace_stream_);
  2086. }
  2087. }
  2088. return Success();
  2089. }
  2090. auto InterpProgram(const AST& ast, Nonnull<Arena*> arena,
  2091. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  2092. -> ErrorOr<int> {
  2093. Interpreter interpreter(Phase::RunTime, arena, trace_stream);
  2094. if (trace_stream) {
  2095. **trace_stream << "********** initializing globals **********\n";
  2096. }
  2097. for (Nonnull<Declaration*> declaration : ast.declarations) {
  2098. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  2099. std::make_unique<DeclarationAction>(declaration)));
  2100. }
  2101. if (trace_stream) {
  2102. **trace_stream << "********** calling main function **********\n";
  2103. }
  2104. CARBON_RETURN_IF_ERROR(interpreter.RunAllSteps(
  2105. std::make_unique<ExpressionAction>(*ast.main_call)));
  2106. return cast<IntValue>(*interpreter.result()).value();
  2107. }
  2108. auto InterpExp(Nonnull<const Expression*> e, Nonnull<Arena*> arena,
  2109. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  2110. -> ErrorOr<Nonnull<const Value*>> {
  2111. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  2112. CARBON_RETURN_IF_ERROR(
  2113. interpreter.RunAllSteps(std::make_unique<ExpressionAction>(e)));
  2114. return interpreter.result();
  2115. }
  2116. auto InterpPattern(Nonnull<const Pattern*> p, Nonnull<Arena*> arena,
  2117. std::optional<Nonnull<llvm::raw_ostream*>> trace_stream)
  2118. -> ErrorOr<Nonnull<const Value*>> {
  2119. Interpreter interpreter(Phase::CompileTime, arena, trace_stream);
  2120. CARBON_RETURN_IF_ERROR(
  2121. interpreter.RunAllSteps(std::make_unique<PatternAction>(p)));
  2122. return interpreter.result();
  2123. }
  2124. } // namespace Carbon