interpreter.cpp 96 KB

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