stringify.cpp 26 KB

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