interpreter.cpp 95 KB

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