interpreter.cpp 97 KB

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