interpreter.cpp 79 KB

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