stringify.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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 "toolchain/sem_ir/stringify.h"
  5. #include "common/raw_string_ostream.h"
  6. #include "common/variant_helpers.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/sem_ir/entity_with_params_base.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. #include "toolchain/sem_ir/inst_kind.h"
  11. #include "toolchain/sem_ir/singleton_insts.h"
  12. #include "toolchain/sem_ir/struct_type_field.h"
  13. #include "toolchain/sem_ir/type_info.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::SemIR {
  16. // Map an instruction kind representing an expression into an integer describing
  17. // the precedence of that expression's syntax. Higher numbers correspond to
  18. // higher precedence.
  19. static auto GetPrecedence(InstKind kind) -> int {
  20. if (kind == ConstType::Kind) {
  21. return -1;
  22. }
  23. if (kind == PointerType::Kind) {
  24. return -2;
  25. }
  26. // TODO: Handle other kinds of expressions with precedence.
  27. return 0;
  28. }
  29. namespace {
  30. // Contains the stack of steps for `Stringify`.
  31. //
  32. // Note that when pushing items onto the stack, they're printed in the reverse
  33. // order of when they were pushed. All reference lifetimes must match the
  34. // lifetime of `Stringify`.
  35. class StepStack {
  36. public:
  37. // An individual step in the stack, which stringifies some component of a type
  38. // name.
  39. using Step = std::variant<InstId, llvm::StringRef, NameId, ElementIndex>;
  40. // Support `Push` for a qualified name. e.g., `A.B.C`.
  41. using QualifiedNameItem = std::pair<NameScopeId, NameId>;
  42. // Support `Push` for a qualified entity name. e.g., `A.B.C`.
  43. using EntityNameItem = std::pair<const EntityWithParamsBase&, SpecificId>;
  44. // The full set of things which can be pushed, including all members of
  45. // `Step`.
  46. using PushItem =
  47. std::variant<InstId, llvm::StringRef, NameId, ElementIndex,
  48. QualifiedNameItem, EntityNameItem, EntityNameId, TypeId,
  49. SpecificInterface, llvm::ListSeparator*>;
  50. // Starts a new stack, which always contains the first instruction to
  51. // stringify.
  52. explicit StepStack(const SemIR::File* file) : sem_ir_(file) {}
  53. // These push basic entries onto the stack.
  54. auto PushInstId(InstId inst_id) -> void { steps_.push_back(inst_id); }
  55. auto PushString(llvm::StringRef string) -> void { steps_.push_back(string); }
  56. auto PushNameId(NameId name_id) -> void { steps_.push_back(name_id); }
  57. auto PushElementIndex(ElementIndex element_index) -> void {
  58. steps_.push_back(element_index);
  59. }
  60. // Pushes all components of a qualified name (`A.B.C`) onto the stack.
  61. auto PushQualifiedName(NameScopeId name_scope_id, NameId name_id) -> void {
  62. PushNameId(name_id);
  63. while (name_scope_id.has_value() && name_scope_id != NameScopeId::Package) {
  64. const auto& name_scope = sem_ir_->name_scopes().Get(name_scope_id);
  65. // TODO: Decide how to print unnamed scopes.
  66. if (name_scope.name_id().has_value()) {
  67. PushString(".");
  68. // TODO: For a generic scope, pass a SpecificId to this function and
  69. // include the relevant arguments.
  70. PushNameId(name_scope.name_id());
  71. }
  72. name_scope_id = name_scope.parent_scope_id();
  73. }
  74. }
  75. // Pushes a specific's entity name onto the stack, such as `A.B(T)`.
  76. auto PushEntityName(const EntityWithParamsBase& entity,
  77. SpecificId specific_id) -> void {
  78. PushSpecificId(entity, specific_id);
  79. PushQualifiedName(entity.parent_scope_id, entity.name_id);
  80. }
  81. // Pushes a entity name onto the stack, such as `A.B`.
  82. auto PushEntityNameId(EntityNameId entity_name_id) -> void {
  83. const auto& entity_name = sem_ir_->entity_names().Get(entity_name_id);
  84. PushQualifiedName(entity_name.parent_scope_id, entity_name.name_id);
  85. }
  86. // Pushes an instruction by its TypeId.
  87. auto PushTypeId(TypeId type_id) -> void {
  88. PushInstId(sem_ir_->types().GetInstId(type_id));
  89. }
  90. // Pushes a specific interface.
  91. auto PushSpecificInterface(SpecificInterface specific_interface) -> void {
  92. PushEntityName(sem_ir_->interfaces().Get(specific_interface.interface_id),
  93. specific_interface.specific_id);
  94. }
  95. // Pushes a sequence of items onto the stack. This handles reversal, such that
  96. // the caller can pass items in print order instead of stack order.
  97. //
  98. // Note that with `ListSeparator`, the object's reference isn't stored, but
  99. // the separator `StringRef` will be. That should be a constant though, so is
  100. // safe.
  101. auto PushArray(llvm::ArrayRef<PushItem> items) -> void {
  102. for (auto item : llvm::reverse(items)) {
  103. VariantMatch(
  104. item, [&](InstId inst_id) { PushInstId(inst_id); },
  105. [&](llvm::StringRef string) { PushString(string); },
  106. [&](NameId name_id) { PushNameId(name_id); },
  107. [&](ElementIndex element_index) { PushElementIndex(element_index); },
  108. [&](QualifiedNameItem qualified_name) {
  109. PushQualifiedName(qualified_name.first, qualified_name.second);
  110. },
  111. [&](EntityNameItem entity_name) {
  112. PushEntityName(entity_name.first, entity_name.second);
  113. },
  114. [&](EntityNameId entity_name_id) {
  115. PushEntityNameId(entity_name_id);
  116. },
  117. [&](TypeId type_id) { PushTypeId(type_id); },
  118. [&](SpecificInterface specific_interface) {
  119. PushSpecificInterface(specific_interface);
  120. },
  121. [&](llvm::ListSeparator* sep) { PushString(*sep); });
  122. }
  123. }
  124. // Wraps `PushArray` without requiring `{}` for arguments.
  125. template <typename... T>
  126. auto Push(T... items) -> void {
  127. PushArray({items...});
  128. }
  129. auto empty() const -> bool { return steps_.empty(); }
  130. auto Pop() -> Step { return steps_.pop_back_val(); }
  131. private:
  132. // Handles the generic portion of a specific entity name, such as `(T)` in
  133. // `A.B(T)`.
  134. auto PushSpecificId(const EntityWithParamsBase& entity,
  135. SpecificId specific_id) -> void {
  136. if (!entity.param_patterns_id.has_value()) {
  137. return;
  138. }
  139. int num_params =
  140. sem_ir_->inst_blocks().Get(entity.param_patterns_id).size();
  141. if (!num_params) {
  142. PushString("()");
  143. return;
  144. }
  145. if (!specific_id.has_value()) {
  146. // The name of the generic was used within the generic itself.
  147. // TODO: Should we print the names of the generic parameters in this
  148. // case?
  149. return;
  150. }
  151. const auto& specific = sem_ir_->specifics().Get(specific_id);
  152. auto args =
  153. sem_ir_->inst_blocks().Get(specific.args_id).take_back(num_params);
  154. bool last = true;
  155. for (auto arg : llvm::reverse(args)) {
  156. PushString(last ? ")" : ", ");
  157. PushInstId(arg);
  158. last = false;
  159. }
  160. PushString("(");
  161. }
  162. const SemIR::File* sem_ir_;
  163. // Remaining steps to take.
  164. llvm::SmallVector<Step> steps_;
  165. };
  166. // Provides `StringifyInst` overloads for each instruction.
  167. class Stringifier {
  168. public:
  169. explicit Stringifier(const SemIR::File* sem_ir, StepStack* step_stack,
  170. llvm::raw_ostream* out)
  171. : sem_ir_(sem_ir), step_stack_(step_stack), out_(out) {}
  172. // By default try to print a constant, but otherwise may fail to
  173. // stringify.
  174. auto StringifyInstDefault(SemIR::InstId inst_id, Inst inst) -> void {
  175. // We don't know how to print this instruction, but it might have a
  176. // constant value that we can print.
  177. auto const_inst_id = sem_ir_->constant_values().GetConstantInstId(inst_id);
  178. if (const_inst_id.has_value() && const_inst_id != inst_id) {
  179. step_stack_->PushInstId(const_inst_id);
  180. return;
  181. }
  182. // We don't need to handle stringification for instructions that don't
  183. // show up in errors, but make it clear what's going on so that it's
  184. // clearer when stringification is needed.
  185. *out_ << "<cannot stringify " << inst_id << ": " << inst << ">";
  186. }
  187. template <typename InstT>
  188. auto StringifyInst(SemIR::InstId inst_id, InstT inst) -> void {
  189. // This doesn't use requires so that more specific overloads are chosen when
  190. // provided.
  191. static_assert(InstT::Kind.is_type() != InstIsType::Always ||
  192. std::same_as<InstT, WhereExpr>,
  193. "Types should have a dedicated overload");
  194. // TODO: We should have Stringify support for all types where
  195. // InstT::Kind.constant_kind() is neither Never nor Indirect.
  196. StringifyInstDefault(inst_id, inst);
  197. }
  198. // Singleton instructions use their IR name as a label.
  199. template <typename InstT>
  200. requires(IsSingletonInstKind(InstT::Kind))
  201. auto StringifyInst(SemIR::InstId /*inst_id*/, InstT /*inst*/) -> void {
  202. *out_ << InstT::Kind.ir_name();
  203. }
  204. auto StringifyInst(SemIR::InstId /*inst_id*/, ArrayType inst) -> void {
  205. *out_ << "array(";
  206. step_stack_->Push(inst.element_type_inst_id, ", ", inst.bound_id, ")");
  207. }
  208. auto StringifyInst(SemIR::InstId /*inst_id*/, AssociatedConstantDecl inst)
  209. -> void {
  210. const auto& assoc_const =
  211. sem_ir_->associated_constants().Get(inst.assoc_const_id);
  212. step_stack_->PushQualifiedName(assoc_const.parent_scope_id,
  213. assoc_const.name_id);
  214. }
  215. auto StringifyInst(SemIR::InstId /*inst_id*/, AssociatedEntityType inst)
  216. -> void {
  217. *out_ << "<associated entity in ";
  218. step_stack_->Push(">");
  219. step_stack_->PushSpecificInterface(
  220. SpecificInterface{inst.interface_id, inst.interface_specific_id});
  221. }
  222. auto StringifyInst(SemIR::InstId /*inst_id*/, BoolLiteral inst) -> void {
  223. step_stack_->Push(inst.value.ToBool() ? "true" : "false");
  224. }
  225. template <typename InstT>
  226. requires(std::same_as<InstT, BindAlias> ||
  227. std::same_as<InstT, BindSymbolicName> ||
  228. std::same_as<InstT, ExportDecl>)
  229. auto StringifyInst(SemIR::InstId /*inst_id*/, InstT inst) -> void {
  230. step_stack_->PushEntityNameId(inst.entity_name_id);
  231. }
  232. auto StringifyInst(SemIR::InstId /*inst_id*/, ClassType inst) -> void {
  233. const auto& class_info = sem_ir_->classes().Get(inst.class_id);
  234. if (auto literal_info = NumericTypeLiteralInfo::ForType(*sem_ir_, inst);
  235. literal_info.is_valid()) {
  236. literal_info.PrintLiteral(*sem_ir_, *out_);
  237. return;
  238. }
  239. step_stack_->PushEntityName(class_info, inst.specific_id);
  240. }
  241. auto StringifyInst(SemIR::InstId /*inst_id*/, ConstType inst) -> void {
  242. *out_ << "const ";
  243. // Add parentheses if required.
  244. if (GetPrecedence(sem_ir_->insts().Get(inst.inner_id).kind()) <
  245. GetPrecedence(SemIR::ConstType::Kind)) {
  246. *out_ << "(";
  247. // Note the `inst.inner_id` ends up here.
  248. step_stack_->PushString(")");
  249. }
  250. step_stack_->PushInstId(inst.inner_id);
  251. }
  252. auto StringifyInst(SemIR::InstId /*inst_id*/, FacetAccessType inst) -> void {
  253. // Given `T:! I`, print `T as type` as simply `T`.
  254. step_stack_->PushInstId(inst.facet_value_inst_id);
  255. }
  256. auto StringifyInst(SemIR::InstId /*inst_id*/, FacetAccessWitness inst)
  257. -> void {
  258. *out_ << "<witness for ";
  259. step_stack_->Push(inst.facet_value_inst_id, ", interface ", inst.index,
  260. ">");
  261. }
  262. auto StringifyInst(SemIR::InstId /*inst_id*/, FacetType inst) -> void {
  263. const FacetTypeInfo& facet_type_info =
  264. sem_ir_->facet_types().Get(inst.facet_type_id);
  265. // Output `where` restrictions.
  266. bool some_where = false;
  267. if (facet_type_info.other_requirements) {
  268. step_stack_->PushString("...");
  269. some_where = true;
  270. }
  271. for (auto rewrite : llvm::reverse(facet_type_info.rewrite_constraints)) {
  272. if (some_where) {
  273. step_stack_->PushString(" and");
  274. }
  275. step_stack_->Push(" ", rewrite.lhs_id, " = ", rewrite.rhs_id);
  276. some_where = true;
  277. }
  278. if (!facet_type_info.self_impls_constraints.empty()) {
  279. if (some_where) {
  280. step_stack_->PushString(" and");
  281. }
  282. llvm::ListSeparator sep(" & ");
  283. for (auto impls : llvm::reverse(facet_type_info.self_impls_constraints)) {
  284. step_stack_->Push(impls, &sep);
  285. }
  286. step_stack_->PushString(" .Self impls ");
  287. some_where = true;
  288. }
  289. // TODO: Other restrictions from facet_type_info.
  290. if (some_where) {
  291. step_stack_->PushString(" where");
  292. }
  293. // Output extend interface requirements.
  294. if (facet_type_info.extend_constraints.empty()) {
  295. step_stack_->PushString("type");
  296. return;
  297. }
  298. llvm::ListSeparator sep(" & ");
  299. for (auto impls : llvm::reverse(facet_type_info.extend_constraints)) {
  300. step_stack_->Push(impls, &sep);
  301. }
  302. }
  303. auto StringifyInst(SemIR::InstId /*inst_id*/, FacetValue inst) -> void {
  304. // No need to output the witness.
  305. step_stack_->Push(inst.type_inst_id, " as ", inst.type_id);
  306. }
  307. auto StringifyInst(SemIR::InstId /*inst_id*/, FloatType inst) -> void {
  308. // TODO: Is this okay?
  309. if (auto width_value =
  310. sem_ir_->insts().TryGetAs<IntValue>(inst.bit_width_id)) {
  311. *out_ << "f";
  312. sem_ir_->ints().Get(width_value->int_id).print(*out_, /*isSigned=*/false);
  313. } else {
  314. *out_ << "Core.Float(";
  315. step_stack_->Push(inst.bit_width_id, ")");
  316. }
  317. }
  318. auto StringifyInst(SemIR::InstId /*inst_id*/, FunctionType inst) -> void {
  319. const auto& fn = sem_ir_->functions().Get(inst.function_id);
  320. *out_ << "<type of ";
  321. step_stack_->Push(
  322. StepStack::QualifiedNameItem{fn.parent_scope_id, fn.name_id}, ">");
  323. }
  324. auto StringifyInst(SemIR::InstId /*inst_id*/, FunctionTypeWithSelfType inst)
  325. -> void {
  326. StepStack::PushItem fn_name = SemIR::InstId::None;
  327. if (auto fn_inst = sem_ir_->insts().TryGetAs<FunctionType>(
  328. inst.interface_function_type_id)) {
  329. const auto& fn = sem_ir_->functions().Get(fn_inst->function_id);
  330. fn_name = StepStack::QualifiedNameItem(fn.parent_scope_id, fn.name_id);
  331. } else {
  332. fn_name = inst.interface_function_type_id;
  333. }
  334. *out_ << "<type of ";
  335. step_stack_->Push(fn_name, " in ", inst.self_id, ">");
  336. }
  337. auto StringifyInst(SemIR::InstId /*inst_id*/, GenericClassType inst) -> void {
  338. const auto& class_info = sem_ir_->classes().Get(inst.class_id);
  339. *out_ << "<type of ";
  340. step_stack_->Push(StepStack::QualifiedNameItem{class_info.parent_scope_id,
  341. class_info.name_id},
  342. ">");
  343. }
  344. auto StringifyInst(SemIR::InstId /*inst_id*/, GenericInterfaceType inst)
  345. -> void {
  346. const auto& interface = sem_ir_->interfaces().Get(inst.interface_id);
  347. *out_ << "<type of ";
  348. step_stack_->Push(StepStack::QualifiedNameItem{interface.parent_scope_id,
  349. interface.name_id},
  350. ">");
  351. }
  352. // Determine the specific interface that an impl witness instruction provides
  353. // an implementation of.
  354. // TODO: Should we track this in the type?
  355. auto TryGetSpecificInterfaceForImplWitness(SemIR::InstId impl_witness_id)
  356. -> std::optional<SpecificInterface> {
  357. if (auto lookup = sem_ir_->insts().TryGetAs<SemIR::LookupImplWitness>(
  358. impl_witness_id)) {
  359. return sem_ir_->specific_interfaces().Get(
  360. lookup->query_specific_interface_id);
  361. }
  362. if (auto witness =
  363. sem_ir_->insts().TryGetAs<FacetAccessWitness>(impl_witness_id)) {
  364. auto witness_type_id =
  365. sem_ir_->insts().Get(witness->facet_value_inst_id).type_id();
  366. auto facet_type = sem_ir_->types().GetAs<FacetType>(witness_type_id);
  367. // TODO: Support != 1 interface better.
  368. const auto& facet_type_info =
  369. sem_ir_->facet_types().Get(facet_type.facet_type_id);
  370. if (facet_type_info.extend_constraints.size() == 1) {
  371. return facet_type_info.extend_constraints.front();
  372. }
  373. }
  374. // TODO: Handle other cases.
  375. return std::nullopt;
  376. }
  377. auto StringifyInst(SemIR::InstId /*inst_id*/, ImplWitnessAccess inst)
  378. -> void {
  379. auto witness_inst_id =
  380. sem_ir_->constant_values().GetConstantInstId(inst.witness_id);
  381. if (auto specific_interface =
  382. TryGetSpecificInterfaceForImplWitness(witness_inst_id)) {
  383. const auto& interface =
  384. sem_ir_->interfaces().Get(specific_interface->interface_id);
  385. auto entities =
  386. sem_ir_->inst_blocks().Get(interface.associated_entities_id);
  387. size_t index = inst.index.index;
  388. CARBON_CHECK(index < entities.size(), "Access out of bounds.");
  389. auto entity_inst_id = entities[index];
  390. step_stack_->PushString(")");
  391. if (auto associated_const =
  392. sem_ir_->insts().TryGetAs<AssociatedConstantDecl>(
  393. entity_inst_id)) {
  394. step_stack_->PushNameId(sem_ir_->associated_constants()
  395. .Get(associated_const->assoc_const_id)
  396. .name_id);
  397. } else if (auto function_decl =
  398. sem_ir_->insts().TryGetAs<FunctionDecl>(entity_inst_id)) {
  399. const auto& function =
  400. sem_ir_->functions().Get(function_decl->function_id);
  401. step_stack_->PushNameId(function.name_id);
  402. } else {
  403. step_stack_->PushInstId(entity_inst_id);
  404. }
  405. step_stack_->Push(
  406. ".(",
  407. StepStack::EntityNameItem{interface, specific_interface->specific_id},
  408. ".");
  409. } else {
  410. step_stack_->Push(".(TODO: element ", inst.index, " in ", witness_inst_id,
  411. ")");
  412. }
  413. if (auto witness =
  414. sem_ir_->insts().TryGetAs<FacetAccessWitness>(witness_inst_id)) {
  415. bool period_self = false;
  416. if (auto sym_name = sem_ir_->insts().TryGetAs<BindSymbolicName>(
  417. witness->facet_value_inst_id)) {
  418. auto name_id =
  419. sem_ir_->entity_names().Get(sym_name->entity_name_id).name_id;
  420. period_self = (name_id == SemIR::NameId::PeriodSelf);
  421. }
  422. if (!period_self) {
  423. step_stack_->PushInstId(witness->facet_value_inst_id);
  424. }
  425. } else {
  426. // TODO: Omit parens if not needed for precedence.
  427. step_stack_->Push("(", witness_inst_id, ")");
  428. }
  429. }
  430. auto StringifyInst(SemIR::InstId /*inst_id*/, ImportRefUnloaded inst)
  431. -> void {
  432. if (inst.entity_name_id.has_value()) {
  433. step_stack_->PushEntityNameId(inst.entity_name_id);
  434. } else {
  435. *out_ << "<import ref unloaded invalid entity name>";
  436. }
  437. }
  438. auto StringifyInst(SemIR::InstId /*inst_id*/, IntType inst) -> void {
  439. *out_ << "<builtin ";
  440. step_stack_->PushString(">");
  441. if (auto width_value =
  442. sem_ir_->insts().TryGetAs<IntValue>(inst.bit_width_id)) {
  443. *out_ << (inst.int_kind.is_signed() ? "i" : "u");
  444. sem_ir_->ints().Get(width_value->int_id).print(*out_, /*isSigned=*/false);
  445. } else {
  446. *out_ << (inst.int_kind.is_signed() ? "Int(" : "UInt(");
  447. step_stack_->Push(inst.bit_width_id, ")");
  448. }
  449. }
  450. auto StringifyInst(SemIR::InstId /*inst_id*/, IntValue inst) -> void {
  451. sem_ir_->ints().Get(inst.int_id).print(*out_, /*isSigned=*/true);
  452. }
  453. auto StringifyInst(SemIR::InstId /*inst_id*/, LookupImplWitness inst)
  454. -> void {
  455. step_stack_->Push(
  456. inst.query_self_inst_id, " as ",
  457. sem_ir_->specific_interfaces().Get(inst.query_specific_interface_id));
  458. }
  459. auto StringifyInst(SemIR::InstId /*inst_id*/, NameRef inst) -> void {
  460. *out_ << sem_ir_->names().GetFormatted(inst.name_id);
  461. }
  462. auto StringifyInst(SemIR::InstId /*inst_id*/, Namespace inst) -> void {
  463. const auto& name_scope = sem_ir_->name_scopes().Get(inst.name_scope_id);
  464. step_stack_->PushQualifiedName(name_scope.parent_scope_id(),
  465. name_scope.name_id());
  466. }
  467. auto StringifyInst(SemIR::InstId /*inst_id*/, PointerType inst) -> void {
  468. step_stack_->Push(inst.pointee_id, "*");
  469. }
  470. auto StringifyInst(SemIR::InstId /*inst_id*/, SpecificFunction inst) -> void {
  471. auto callee = SemIR::GetCalleeFunction(*sem_ir_, inst.callee_id);
  472. if (callee.function_id.has_value()) {
  473. step_stack_->PushEntityName(sem_ir_->functions().Get(callee.function_id),
  474. inst.specific_id);
  475. } else {
  476. step_stack_->PushString("<invalid specific function>");
  477. }
  478. }
  479. auto StringifyInst(SemIR::InstId /*inst_id*/, SpecificImplFunction inst)
  480. -> void {
  481. auto callee = SemIR::GetCalleeFunction(*sem_ir_, inst.callee_id);
  482. if (callee.function_id.has_value()) {
  483. // TODO: The specific_id here is for the interface member, but the
  484. // entity we're passing is the impl member. This might result in
  485. // strange output once we render specific arguments properly.
  486. step_stack_->PushEntityName(sem_ir_->functions().Get(callee.function_id),
  487. inst.specific_id);
  488. } else {
  489. step_stack_->PushString("<invalid specific function>");
  490. }
  491. }
  492. auto StringifyInst(SemIR::InstId /*inst_id*/, StructType inst) -> void {
  493. auto fields = sem_ir_->struct_type_fields().Get(inst.fields_id);
  494. if (fields.empty()) {
  495. *out_ << "{}";
  496. return;
  497. }
  498. *out_ << "{";
  499. step_stack_->PushString("}");
  500. llvm::ListSeparator sep;
  501. for (auto field : llvm::reverse(fields)) {
  502. step_stack_->Push(".", field.name_id, ": ", field.type_inst_id, &sep);
  503. }
  504. }
  505. auto StringifyInst(SemIR::InstId /*inst_id*/, StructValue inst) -> void {
  506. auto field_values = sem_ir_->inst_blocks().Get(inst.elements_id);
  507. if (field_values.empty()) {
  508. *out_ << "{}";
  509. return;
  510. }
  511. auto struct_type = sem_ir_->types().GetAs<StructType>(
  512. sem_ir_->types().GetObjectRepr(inst.type_id));
  513. auto fields = sem_ir_->struct_type_fields().Get(struct_type.fields_id);
  514. if (fields.size() != field_values.size()) {
  515. *out_ << "{<struct value type length mismatch>}";
  516. return;
  517. }
  518. *out_ << "{";
  519. step_stack_->PushString("}");
  520. llvm::ListSeparator sep;
  521. for (auto [field, value_inst_id] :
  522. llvm::reverse(llvm::zip(fields, field_values))) {
  523. step_stack_->Push(".", field.name_id, " = ", value_inst_id, &sep);
  524. }
  525. }
  526. auto StringifyInst(SemIR::InstId /*inst_id*/, TupleType inst) -> void {
  527. auto refs = sem_ir_->inst_blocks().Get(inst.elements_id);
  528. if (refs.empty()) {
  529. *out_ << "()";
  530. return;
  531. }
  532. *out_ << "(";
  533. step_stack_->PushString(")");
  534. // A tuple of one element has a comma to disambiguate from an
  535. // expression.
  536. if (refs.size() == 1) {
  537. step_stack_->PushString(",");
  538. }
  539. llvm::ListSeparator sep;
  540. for (auto ref : llvm::reverse(refs)) {
  541. step_stack_->Push(ref, &sep);
  542. }
  543. }
  544. auto StringifyInst(SemIR::InstId /*inst_id*/, TupleValue inst) -> void {
  545. auto refs = sem_ir_->inst_blocks().Get(inst.elements_id);
  546. if (refs.empty()) {
  547. *out_ << "()";
  548. return;
  549. }
  550. *out_ << "(";
  551. step_stack_->PushString(")");
  552. // A tuple of one element has a comma to disambiguate from an
  553. // expression.
  554. if (refs.size() == 1) {
  555. step_stack_->PushString(",");
  556. }
  557. llvm::ListSeparator sep;
  558. for (auto ref : llvm::reverse(refs)) {
  559. step_stack_->Push(ref, &sep);
  560. }
  561. }
  562. auto StringifyInst(SemIR::InstId inst_id, TypeOfInst /*inst*/) -> void {
  563. // Print the constant value if we've already computed the inst.
  564. auto const_inst_id = sem_ir_->constant_values().GetConstantInstId(inst_id);
  565. if (const_inst_id.has_value() && const_inst_id != inst_id) {
  566. step_stack_->PushInstId(const_inst_id);
  567. return;
  568. }
  569. *out_ << "<dependent type>";
  570. }
  571. auto StringifyInst(SemIR::InstId /*inst_id*/, UnboundElementType inst)
  572. -> void {
  573. *out_ << "<unbound element of class ";
  574. step_stack_->Push(inst.class_type_inst_id, ">");
  575. }
  576. auto StringifyInst(SemIR::InstId /*inst_id*/, VtablePtr /*inst*/) -> void {
  577. *out_ << "<vtable ptr>";
  578. }
  579. private:
  580. const SemIR::File* sem_ir_;
  581. StepStack* step_stack_;
  582. llvm::raw_ostream* out_;
  583. };
  584. } // namespace
  585. static auto Stringify(const SemIR::File& sem_ir, StepStack& step_stack)
  586. -> std::string {
  587. RawStringOstream out;
  588. Stringifier stringifier(&sem_ir, &step_stack, &out);
  589. while (!step_stack.empty()) {
  590. auto step = step_stack.Pop();
  591. VariantMatch(
  592. step,
  593. [&](InstId inst_id) {
  594. if (!inst_id.has_value()) {
  595. out << "<invalid>";
  596. return;
  597. }
  598. auto untyped_inst = sem_ir.insts().Get(inst_id);
  599. CARBON_KIND_SWITCH(untyped_inst) {
  600. #define CARBON_SEM_IR_INST_KIND(InstT) \
  601. case CARBON_KIND(InstT typed_inst): { \
  602. stringifier.StringifyInst(inst_id, typed_inst); \
  603. break; \
  604. }
  605. #include "toolchain/sem_ir/inst_kind.def"
  606. }
  607. },
  608. [&](llvm::StringRef string) { out << string; },
  609. [&](NameId name_id) { out << sem_ir.names().GetFormatted(name_id); },
  610. [&](ElementIndex element_index) { out << element_index.index; });
  611. }
  612. return out.TakeStr();
  613. }
  614. auto StringifyConstantInst(const SemIR::File& sem_ir, InstId outer_inst_id)
  615. -> std::string {
  616. StepStack step_stack(&sem_ir);
  617. step_stack.PushInstId(outer_inst_id);
  618. return Stringify(sem_ir, step_stack);
  619. }
  620. auto StringifySpecific(const File& sem_ir, SpecificId specific_id)
  621. -> std::string {
  622. StepStack step_stack(&sem_ir);
  623. const auto& specific = sem_ir.specifics().Get(specific_id);
  624. const auto& generic = sem_ir.generics().Get(specific.generic_id);
  625. auto decl = sem_ir.insts().Get(generic.decl_id);
  626. CARBON_KIND_SWITCH(decl) {
  627. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  628. // Print `Core.Int(N)` as `iN`.
  629. // TODO: This duplicates work done in StringifyInst for ClassType.
  630. const auto& class_info = sem_ir.classes().Get(class_decl.class_id);
  631. if (auto literal_info = NumericTypeLiteralInfo::ForType(
  632. sem_ir,
  633. SemIR::ClassType{.type_id = SemIR::TypeType::SingletonTypeId,
  634. .class_id = class_decl.class_id,
  635. .specific_id = specific_id});
  636. literal_info.is_valid()) {
  637. RawStringOstream out;
  638. literal_info.PrintLiteral(sem_ir, out);
  639. return out.TakeStr();
  640. }
  641. step_stack.PushEntityName(class_info, specific_id);
  642. break;
  643. }
  644. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  645. step_stack.PushEntityName(
  646. sem_ir.functions().Get(function_decl.function_id), specific_id);
  647. break;
  648. }
  649. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  650. step_stack.PushEntityName(sem_ir.impls().Get(impl_decl.impl_id),
  651. specific_id);
  652. break;
  653. }
  654. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  655. step_stack.PushEntityName(
  656. sem_ir.interfaces().Get(interface_decl.interface_id), specific_id);
  657. break;
  658. }
  659. default: {
  660. // TODO: Include the specific arguments here.
  661. step_stack.PushInstId(generic.decl_id);
  662. break;
  663. }
  664. }
  665. return Stringify(sem_ir, step_stack);
  666. }
  667. } // namespace Carbon::SemIR