interpreter.cpp 103 KB

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