stringify.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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/concepts.h"
  10. #include "common/raw_string_ostream.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. CARBON_KIND_SWITCH(item) {
  108. case CARBON_KIND(InstId inst_id): {
  109. PushInstId(inst_id);
  110. break;
  111. }
  112. case CARBON_KIND(llvm::StringRef string): {
  113. PushString(string);
  114. break;
  115. }
  116. case CARBON_KIND(NameId name_id): {
  117. PushNameId(name_id);
  118. break;
  119. }
  120. case CARBON_KIND(ElementIndex element_index): {
  121. PushElementIndex(element_index);
  122. break;
  123. }
  124. case CARBON_KIND(QualifiedNameItem qualified_name): {
  125. PushQualifiedName(qualified_name.first, qualified_name.second);
  126. break;
  127. }
  128. case CARBON_KIND(EntityNameItem entity_name): {
  129. PushEntityName(entity_name.first, entity_name.second);
  130. break;
  131. }
  132. case CARBON_KIND(EntityNameId entity_name_id): {
  133. PushEntityNameId(entity_name_id);
  134. break;
  135. }
  136. case CARBON_KIND(TypeId type_id): {
  137. PushTypeId(type_id);
  138. break;
  139. }
  140. case CARBON_KIND(SpecificInterface specific_interface): {
  141. PushSpecificInterface(specific_interface);
  142. break;
  143. }
  144. case CARBON_KIND(llvm::ListSeparator * sep): {
  145. PushString(*sep);
  146. break;
  147. }
  148. }
  149. }
  150. }
  151. // Wraps `PushArray` without requiring `{}` for arguments.
  152. template <typename... T>
  153. auto Push(T... items) -> void {
  154. PushArray({items...});
  155. }
  156. auto empty() const -> bool { return steps_.empty(); }
  157. auto Pop() -> Step { return steps_.pop_back_val(); }
  158. private:
  159. // Handles the generic portion of a specific entity name, such as `(T)` in
  160. // `A.B(T)`.
  161. auto PushSpecificId(const EntityWithParamsBase& entity,
  162. SpecificId specific_id) -> void {
  163. if (!entity.param_patterns_id.has_value()) {
  164. return;
  165. }
  166. int num_params =
  167. sem_ir_->inst_blocks().Get(entity.param_patterns_id).size();
  168. if (!num_params) {
  169. PushString("()");
  170. return;
  171. }
  172. if (!specific_id.has_value()) {
  173. // The name of the generic was used within the generic itself.
  174. // TODO: Should we print the names of the generic parameters in this
  175. // case?
  176. return;
  177. }
  178. const auto& specific = sem_ir_->specifics().Get(specific_id);
  179. auto args =
  180. sem_ir_->inst_blocks().Get(specific.args_id).take_back(num_params);
  181. bool last = true;
  182. for (auto arg : llvm::reverse(args)) {
  183. PushString(last ? ")" : ", ");
  184. PushInstId(arg);
  185. last = false;
  186. }
  187. PushString("(");
  188. }
  189. const File* sem_ir_;
  190. // Remaining steps to take.
  191. llvm::SmallVector<Step> steps_;
  192. };
  193. // Provides `StringifyInst` overloads for each instruction.
  194. class Stringifier {
  195. public:
  196. explicit Stringifier(const File* sem_ir, StepStack* step_stack,
  197. llvm::raw_ostream* out)
  198. : sem_ir_(sem_ir), step_stack_(step_stack), out_(out) {}
  199. // By default try to print a constant, but otherwise may fail to
  200. // stringify.
  201. auto StringifyInstDefault(InstId inst_id, Inst inst) -> void {
  202. // We don't know how to print this instruction, but it might have a
  203. // constant value that we can print.
  204. auto const_inst_id = sem_ir_->constant_values().GetConstantInstId(inst_id);
  205. if (const_inst_id.has_value() && const_inst_id != inst_id) {
  206. step_stack_->PushInstId(const_inst_id);
  207. return;
  208. }
  209. // We don't need to handle stringification for instructions that don't
  210. // show up in errors, but make it clear what's going on so that it's
  211. // clearer when stringification is needed.
  212. *out_ << "<cannot stringify " << inst_id << ": " << inst << ">";
  213. }
  214. template <typename InstT>
  215. auto StringifyInst(InstId inst_id, InstT inst) -> void {
  216. // This doesn't use requires so that more specific overloads are chosen when
  217. // provided.
  218. static_assert(InstT::Kind.is_type() != InstIsType::Always ||
  219. std::same_as<InstT, WhereExpr>,
  220. "Types should have a dedicated overload");
  221. // TODO: We should have Stringify support for all types where
  222. // InstT::Kind.constant_kind() is neither Never nor Indirect.
  223. StringifyInstDefault(inst_id, inst);
  224. }
  225. // Singleton instructions use their IR name as a label.
  226. template <typename InstT>
  227. requires(IsSingletonInstKind(InstT::Kind))
  228. auto StringifyInst(InstId /*inst_id*/, InstT /*inst*/) -> void {
  229. *out_ << InstT::Kind.ir_name();
  230. }
  231. auto StringifyInst(InstId /*inst_id*/, ArrayType inst) -> void {
  232. *out_ << "array(";
  233. step_stack_->Push(inst.element_type_inst_id, ", ", inst.bound_id, ")");
  234. }
  235. auto StringifyInst(InstId /*inst_id*/, AssociatedConstantDecl inst) -> void {
  236. const auto& assoc_const =
  237. sem_ir_->associated_constants().Get(inst.assoc_const_id);
  238. step_stack_->PushQualifiedName(assoc_const.parent_scope_id,
  239. assoc_const.name_id);
  240. }
  241. auto StringifyInst(InstId /*inst_id*/, AssociatedEntityType inst) -> void {
  242. *out_ << "<associated entity in ";
  243. step_stack_->Push(">");
  244. step_stack_->PushSpecificInterface(
  245. SpecificInterface{inst.interface_id, inst.interface_specific_id});
  246. }
  247. auto StringifyInst(InstId /*inst_id*/, BoolLiteral inst) -> void {
  248. step_stack_->Push(inst.value.ToBool() ? "true" : "false");
  249. }
  250. template <typename InstT>
  251. requires(SameAsOneOf<InstT, BindAlias, BindSymbolicName, ExportDecl>)
  252. auto StringifyInst(InstId /*inst_id*/, InstT inst) -> void {
  253. step_stack_->PushEntityNameId(inst.entity_name_id);
  254. }
  255. auto StringifyInst(InstId /*inst_id*/, ClassType inst) -> void {
  256. const auto& class_info = sem_ir_->classes().Get(inst.class_id);
  257. if (auto literal_info = NumericTypeLiteralInfo::ForType(*sem_ir_, inst);
  258. literal_info.is_valid()) {
  259. literal_info.PrintLiteral(*sem_ir_, *out_);
  260. return;
  261. }
  262. step_stack_->PushEntityName(class_info, inst.specific_id);
  263. }
  264. auto StringifyInst(InstId /*inst_id*/, ConstType inst) -> void {
  265. *out_ << "const ";
  266. // Add parentheses if required.
  267. if (GetPrecedence(sem_ir_->insts().Get(inst.inner_id).kind()) <
  268. GetPrecedence(ConstType::Kind)) {
  269. *out_ << "(";
  270. // Note the `inst.inner_id` ends up here.
  271. step_stack_->PushString(")");
  272. }
  273. step_stack_->PushInstId(inst.inner_id);
  274. }
  275. auto StringifyInst(InstId /*inst_id*/, CustomLayoutType inst) -> void {
  276. auto layout = sem_ir_->custom_layouts().Get(inst.layout_id);
  277. *out_ << "<size " << layout[CustomLayoutId::SizeIndex] << ", align "
  278. << layout[CustomLayoutId::AlignIndex] << ">";
  279. }
  280. auto StringifyInst(InstId /*inst_id*/, FacetAccessType inst) -> void {
  281. // Given `T:! I`, print `T as type` as simply `T`.
  282. step_stack_->PushInstId(inst.facet_value_inst_id);
  283. }
  284. auto StringifyInst(InstId /*inst_id*/, FacetType inst) -> void {
  285. const FacetTypeInfo& facet_type_info =
  286. sem_ir_->facet_types().Get(inst.facet_type_id);
  287. // Output `where` restrictions.
  288. bool some_where = false;
  289. if (facet_type_info.other_requirements) {
  290. step_stack_->PushString("...");
  291. some_where = true;
  292. }
  293. for (auto rewrite : llvm::reverse(facet_type_info.rewrite_constraints)) {
  294. if (some_where) {
  295. step_stack_->PushString(" and");
  296. }
  297. step_stack_->Push(" ", rewrite.lhs_id, " = ", rewrite.rhs_id);
  298. some_where = true;
  299. }
  300. if (!facet_type_info.self_impls_constraints.empty()) {
  301. if (some_where) {
  302. step_stack_->PushString(" and");
  303. }
  304. llvm::ListSeparator sep(" & ");
  305. for (auto impls : llvm::reverse(facet_type_info.self_impls_constraints)) {
  306. step_stack_->Push(impls, &sep);
  307. }
  308. step_stack_->PushString(" .Self impls ");
  309. some_where = true;
  310. }
  311. // TODO: Other restrictions from facet_type_info.
  312. if (some_where) {
  313. step_stack_->PushString(" where");
  314. }
  315. // Output extend interface requirements.
  316. if (facet_type_info.extend_constraints.empty()) {
  317. step_stack_->PushString("type");
  318. return;
  319. }
  320. llvm::ListSeparator sep(" & ");
  321. for (auto impls : llvm::reverse(facet_type_info.extend_constraints)) {
  322. step_stack_->Push(impls, &sep);
  323. }
  324. }
  325. auto StringifyInst(InstId /*inst_id*/, FacetValue inst) -> void {
  326. // No need to output the witness.
  327. step_stack_->Push(inst.type_inst_id, " as ", inst.type_id);
  328. }
  329. auto StringifyInst(InstId /*inst_id*/, FloatType inst) -> void {
  330. *out_ << "<builtin ";
  331. step_stack_->PushString(">");
  332. if (auto width_value =
  333. sem_ir_->insts().TryGetAs<IntValue>(inst.bit_width_id)) {
  334. *out_ << "f";
  335. sem_ir_->ints().Get(width_value->int_id).print(*out_, /*isSigned=*/false);
  336. } else {
  337. *out_ << "Core.Float(";
  338. step_stack_->Push(inst.bit_width_id, ")");
  339. }
  340. }
  341. auto StringifyInst(InstId /*inst_id*/, CppOverloadSetType inst) -> void {
  342. const auto& overload_set =
  343. sem_ir_->cpp_overload_sets().Get(inst.overload_set_id);
  344. *out_ << "<type of ";
  345. step_stack_->Push(StepStack::QualifiedNameItem{overload_set.parent_scope_id,
  346. overload_set.name_id},
  347. ">");
  348. }
  349. auto StringifyInst(InstId /*inst_id*/, FunctionType inst) -> void {
  350. const auto& fn = sem_ir_->functions().Get(inst.function_id);
  351. *out_ << "<type of ";
  352. step_stack_->Push(
  353. StepStack::QualifiedNameItem{fn.parent_scope_id, fn.name_id}, ">");
  354. }
  355. auto StringifyInst(InstId /*inst_id*/, FunctionTypeWithSelfType inst)
  356. -> void {
  357. StepStack::PushItem fn_name = InstId::None;
  358. if (auto fn_inst = sem_ir_->insts().TryGetAs<FunctionType>(
  359. inst.interface_function_type_id)) {
  360. const auto& fn = sem_ir_->functions().Get(fn_inst->function_id);
  361. fn_name = StepStack::QualifiedNameItem(fn.parent_scope_id, fn.name_id);
  362. } else {
  363. fn_name = inst.interface_function_type_id;
  364. }
  365. *out_ << "<type of ";
  366. step_stack_->Push(fn_name, " in ", inst.self_id, ">");
  367. }
  368. auto StringifyInst(InstId /*inst_id*/, GenericClassType inst) -> void {
  369. const auto& class_info = sem_ir_->classes().Get(inst.class_id);
  370. *out_ << "<type of ";
  371. step_stack_->Push(StepStack::QualifiedNameItem{class_info.parent_scope_id,
  372. class_info.name_id},
  373. ">");
  374. }
  375. auto StringifyInst(InstId /*inst_id*/, GenericInterfaceType inst) -> void {
  376. const auto& interface = sem_ir_->interfaces().Get(inst.interface_id);
  377. *out_ << "<type of ";
  378. step_stack_->Push(StepStack::QualifiedNameItem{interface.parent_scope_id,
  379. interface.name_id},
  380. ">");
  381. }
  382. // Determine the specific interface that an impl witness instruction provides
  383. // an implementation of.
  384. // TODO: Should we track this in the type?
  385. auto TryGetSpecificInterfaceForImplWitness(InstId impl_witness_id)
  386. -> std::optional<SpecificInterface> {
  387. if (auto lookup =
  388. sem_ir_->insts().TryGetAs<LookupImplWitness>(impl_witness_id)) {
  389. return sem_ir_->specific_interfaces().Get(
  390. lookup->query_specific_interface_id);
  391. }
  392. // TODO: Handle ImplWitness.
  393. return std::nullopt;
  394. }
  395. auto StringifyInst(InstId /*inst_id*/, ImplWitnessAccess inst) -> void {
  396. auto witness_inst_id =
  397. sem_ir_->constant_values().GetConstantInstId(inst.witness_id);
  398. auto lookup = sem_ir_->insts().GetAs<LookupImplWitness>(witness_inst_id);
  399. auto specific_interface =
  400. sem_ir_->specific_interfaces().Get(lookup.query_specific_interface_id);
  401. const auto& interface =
  402. sem_ir_->interfaces().Get(specific_interface.interface_id);
  403. if (!interface.associated_entities_id.has_value()) {
  404. step_stack_->Push(".(TODO: element ", inst.index, " in incomplete ",
  405. witness_inst_id, ")");
  406. } else {
  407. auto entities =
  408. sem_ir_->inst_blocks().Get(interface.associated_entities_id);
  409. size_t index = inst.index.index;
  410. CARBON_CHECK(index < entities.size(), "Access out of bounds.");
  411. auto entity_inst_id = entities[index];
  412. step_stack_->PushString(")");
  413. if (auto associated_const =
  414. sem_ir_->insts().TryGetAs<AssociatedConstantDecl>(
  415. entity_inst_id)) {
  416. step_stack_->PushNameId(sem_ir_->associated_constants()
  417. .Get(associated_const->assoc_const_id)
  418. .name_id);
  419. } else if (auto function_decl =
  420. sem_ir_->insts().TryGetAs<FunctionDecl>(entity_inst_id)) {
  421. const auto& function =
  422. sem_ir_->functions().Get(function_decl->function_id);
  423. step_stack_->PushNameId(function.name_id);
  424. } else {
  425. step_stack_->PushInstId(entity_inst_id);
  426. }
  427. step_stack_->Push(
  428. ".(",
  429. StepStack::EntityNameItem{interface, specific_interface.specific_id},
  430. ".");
  431. }
  432. if (auto lookup =
  433. sem_ir_->insts().TryGetAs<LookupImplWitness>(witness_inst_id)) {
  434. bool period_self = false;
  435. if (auto sym_name = sem_ir_->insts().TryGetAs<BindSymbolicName>(
  436. lookup->query_self_inst_id)) {
  437. auto name_id =
  438. sem_ir_->entity_names().Get(sym_name->entity_name_id).name_id;
  439. period_self = (name_id == NameId::PeriodSelf);
  440. }
  441. if (!period_self) {
  442. step_stack_->PushInstId(lookup->query_self_inst_id);
  443. }
  444. } else {
  445. // TODO: Omit parens if not needed for precedence.
  446. step_stack_->Push("(", witness_inst_id, ")");
  447. }
  448. }
  449. auto StringifyInst(InstId /*inst_id*/, ImportRefUnloaded inst) -> void {
  450. if (inst.entity_name_id.has_value()) {
  451. step_stack_->PushEntityNameId(inst.entity_name_id);
  452. } else {
  453. *out_ << "<import ref unloaded invalid entity name>";
  454. }
  455. }
  456. auto StringifyInst(InstId /*inst_id*/, IntType inst) -> void {
  457. *out_ << "<builtin ";
  458. step_stack_->PushString(">");
  459. if (auto width_value =
  460. sem_ir_->insts().TryGetAs<IntValue>(inst.bit_width_id)) {
  461. *out_ << (inst.int_kind.is_signed() ? "i" : "u");
  462. sem_ir_->ints().Get(width_value->int_id).print(*out_, /*isSigned=*/false);
  463. } else {
  464. *out_ << (inst.int_kind.is_signed() ? "Int(" : "UInt(");
  465. step_stack_->Push(inst.bit_width_id, ")");
  466. }
  467. }
  468. auto StringifyInst(InstId /*inst_id*/, IntValue inst) -> void {
  469. sem_ir_->ints().Get(inst.int_id).print(*out_, /*isSigned=*/true);
  470. }
  471. auto StringifyInst(InstId /*inst_id*/, LookupImplWitness inst) -> void {
  472. step_stack_->Push(
  473. inst.query_self_inst_id, " as ",
  474. sem_ir_->specific_interfaces().Get(inst.query_specific_interface_id));
  475. }
  476. auto StringifyInst(InstId /*inst_id*/, MaybeUnformedType inst) -> void {
  477. step_stack_->Push("<builtin MaybeUnformed(", inst.inner_id, ")>");
  478. }
  479. auto StringifyInst(InstId /*inst_id*/, NameRef inst) -> void {
  480. *out_ << sem_ir_->names().GetFormatted(inst.name_id);
  481. }
  482. auto StringifyInst(InstId /*inst_id*/, Namespace inst) -> void {
  483. const auto& name_scope = sem_ir_->name_scopes().Get(inst.name_scope_id);
  484. step_stack_->PushQualifiedName(name_scope.parent_scope_id(),
  485. name_scope.name_id());
  486. }
  487. auto StringifyInst(InstId /*inst_id*/, PartialType inst) -> void {
  488. *out_ << "partial ";
  489. step_stack_->PushInstId(inst.inner_id);
  490. }
  491. auto StringifyInst(InstId /*inst_id*/, PatternType inst) -> void {
  492. *out_ << "<pattern for ";
  493. step_stack_->Push(inst.scrutinee_type_inst_id, ">");
  494. }
  495. auto StringifyInst(InstId /*inst_id*/, PointerType inst) -> void {
  496. step_stack_->Push(inst.pointee_id, "*");
  497. }
  498. auto StringifyInst(InstId /*inst_id*/, SpecificFunction inst) -> void {
  499. auto callee = GetCalleeFunction(*sem_ir_, inst.callee_id);
  500. if (callee.function_id.has_value()) {
  501. step_stack_->PushEntityName(sem_ir_->functions().Get(callee.function_id),
  502. inst.specific_id);
  503. } else {
  504. step_stack_->PushString("<invalid specific function>");
  505. }
  506. }
  507. auto StringifyInst(InstId /*inst_id*/, SpecificImplFunction inst) -> void {
  508. auto callee = GetCalleeFunction(*sem_ir_, inst.callee_id);
  509. if (callee.function_id.has_value()) {
  510. // TODO: The specific_id here is for the interface member, but the
  511. // entity we're passing is the impl member. This might result in
  512. // strange output once we render specific arguments properly.
  513. step_stack_->PushEntityName(sem_ir_->functions().Get(callee.function_id),
  514. inst.specific_id);
  515. } else {
  516. step_stack_->PushString("<invalid specific function>");
  517. }
  518. }
  519. auto StringifyInst(InstId /*inst_id*/, StructType inst) -> void {
  520. auto fields = sem_ir_->struct_type_fields().Get(inst.fields_id);
  521. if (fields.empty()) {
  522. *out_ << "{}";
  523. return;
  524. }
  525. *out_ << "{";
  526. step_stack_->PushString("}");
  527. llvm::ListSeparator sep;
  528. for (auto field : llvm::reverse(fields)) {
  529. step_stack_->Push(".", field.name_id, ": ", field.type_inst_id, &sep);
  530. }
  531. }
  532. auto StringifyInst(InstId /*inst_id*/, StructValue inst) -> void {
  533. auto field_values = sem_ir_->inst_blocks().Get(inst.elements_id);
  534. if (field_values.empty()) {
  535. *out_ << "{}";
  536. return;
  537. }
  538. auto struct_type = sem_ir_->types().GetAs<StructType>(
  539. sem_ir_->types().GetObjectRepr(inst.type_id));
  540. auto fields = sem_ir_->struct_type_fields().Get(struct_type.fields_id);
  541. if (fields.size() != field_values.size()) {
  542. *out_ << "{<struct value type length mismatch>}";
  543. return;
  544. }
  545. *out_ << "{";
  546. step_stack_->PushString("}");
  547. llvm::ListSeparator sep;
  548. for (auto [field, value_inst_id] :
  549. llvm::reverse(llvm::zip(fields, field_values))) {
  550. step_stack_->Push(".", field.name_id, " = ", value_inst_id, &sep);
  551. }
  552. }
  553. auto StringifyInst(InstId /*inst_id*/, TupleType inst) -> void {
  554. auto refs = sem_ir_->inst_blocks().Get(inst.type_elements_id);
  555. if (refs.empty()) {
  556. *out_ << "()";
  557. return;
  558. }
  559. *out_ << "(";
  560. step_stack_->PushString(")");
  561. // A tuple of one element has a comma to disambiguate from an
  562. // expression.
  563. if (refs.size() == 1) {
  564. step_stack_->PushString(",");
  565. }
  566. llvm::ListSeparator sep;
  567. for (auto ref : llvm::reverse(refs)) {
  568. step_stack_->Push(ref, &sep);
  569. }
  570. }
  571. auto StringifyInst(InstId /*inst_id*/, TupleValue inst) -> void {
  572. auto refs = sem_ir_->inst_blocks().Get(inst.elements_id);
  573. if (refs.empty()) {
  574. *out_ << "()";
  575. return;
  576. }
  577. *out_ << "(";
  578. step_stack_->PushString(")");
  579. // A tuple of one element has a comma to disambiguate from an
  580. // expression.
  581. if (refs.size() == 1) {
  582. step_stack_->PushString(",");
  583. }
  584. llvm::ListSeparator sep;
  585. for (auto ref : llvm::reverse(refs)) {
  586. step_stack_->Push(ref, &sep);
  587. }
  588. }
  589. auto StringifyInst(InstId inst_id, TypeOfInst /*inst*/) -> void {
  590. // Print the constant value if we've already computed the inst.
  591. auto const_inst_id = sem_ir_->constant_values().GetConstantInstId(inst_id);
  592. if (const_inst_id.has_value() && const_inst_id != inst_id) {
  593. step_stack_->PushInstId(const_inst_id);
  594. return;
  595. }
  596. *out_ << "<dependent type>";
  597. }
  598. auto StringifyInst(InstId /*inst_id*/, UnboundElementType inst) -> void {
  599. *out_ << "<unbound element of class ";
  600. step_stack_->Push(inst.class_type_inst_id, ">");
  601. }
  602. auto StringifyInst(InstId /*inst_id*/, VtablePtr /*inst*/) -> void {
  603. *out_ << "<vtable ptr>";
  604. }
  605. private:
  606. const File* sem_ir_;
  607. StepStack* step_stack_;
  608. llvm::raw_ostream* out_;
  609. };
  610. } // namespace
  611. // NOLINTNEXTLINE(readability-function-size)
  612. static auto Stringify(const File& sem_ir, StepStack& step_stack)
  613. -> std::string {
  614. RawStringOstream out;
  615. Stringifier stringifier(&sem_ir, &step_stack, &out);
  616. while (!step_stack.empty()) {
  617. CARBON_KIND_SWITCH(step_stack.Pop()) {
  618. case CARBON_KIND(InstId inst_id): {
  619. if (!inst_id.has_value()) {
  620. out << "<invalid>";
  621. break;
  622. }
  623. auto untyped_inst = sem_ir.insts().Get(inst_id);
  624. CARBON_KIND_SWITCH(untyped_inst) {
  625. #define CARBON_SEM_IR_INST_KIND(InstT) \
  626. case CARBON_KIND(InstT typed_inst): { \
  627. stringifier.StringifyInst(inst_id, typed_inst); \
  628. break; \
  629. }
  630. #include "toolchain/sem_ir/inst_kind.def"
  631. }
  632. break;
  633. }
  634. case CARBON_KIND(llvm::StringRef string):
  635. out << string;
  636. break;
  637. case CARBON_KIND(NameId name_id):
  638. out << sem_ir.names().GetFormatted(name_id);
  639. break;
  640. case CARBON_KIND(ElementIndex element_index):
  641. out << element_index.index;
  642. break;
  643. }
  644. }
  645. return out.TakeStr();
  646. }
  647. auto StringifyConstantInst(const File& sem_ir, InstId outer_inst_id)
  648. -> std::string {
  649. StepStack step_stack(&sem_ir);
  650. step_stack.PushInstId(outer_inst_id);
  651. return Stringify(sem_ir, step_stack);
  652. }
  653. auto StringifySpecific(const File& sem_ir, SpecificId specific_id)
  654. -> std::string {
  655. StepStack step_stack(&sem_ir);
  656. const auto& specific = sem_ir.specifics().Get(specific_id);
  657. const auto& generic = sem_ir.generics().Get(specific.generic_id);
  658. auto decl = sem_ir.insts().Get(generic.decl_id);
  659. CARBON_KIND_SWITCH(decl) {
  660. case CARBON_KIND(ClassDecl class_decl): {
  661. // Print `Core.Int(N)` as `iN`.
  662. // TODO: This duplicates work done in StringifyInst for ClassType.
  663. const auto& class_info = sem_ir.classes().Get(class_decl.class_id);
  664. if (auto literal_info = NumericTypeLiteralInfo::ForType(
  665. sem_ir, ClassType{.type_id = TypeType::TypeId,
  666. .class_id = class_decl.class_id,
  667. .specific_id = specific_id});
  668. literal_info.is_valid()) {
  669. RawStringOstream out;
  670. literal_info.PrintLiteral(sem_ir, out);
  671. return out.TakeStr();
  672. }
  673. step_stack.PushEntityName(class_info, specific_id);
  674. break;
  675. }
  676. case CARBON_KIND(FunctionDecl function_decl): {
  677. step_stack.PushEntityName(
  678. sem_ir.functions().Get(function_decl.function_id), specific_id);
  679. break;
  680. }
  681. case CARBON_KIND(ImplDecl impl_decl): {
  682. step_stack.PushEntityName(sem_ir.impls().Get(impl_decl.impl_id),
  683. specific_id);
  684. break;
  685. }
  686. case CARBON_KIND(InterfaceDecl interface_decl): {
  687. step_stack.PushEntityName(
  688. sem_ir.interfaces().Get(interface_decl.interface_id), specific_id);
  689. break;
  690. }
  691. default: {
  692. // TODO: Include the specific arguments here.
  693. step_stack.PushInstId(generic.decl_id);
  694. break;
  695. }
  696. }
  697. return Stringify(sem_ir, step_stack);
  698. }
  699. auto StringifySpecificInterface(const File& sem_ir,
  700. SpecificInterface specific_interface)
  701. -> std::string {
  702. if (specific_interface.specific_id.has_value()) {
  703. return StringifySpecific(sem_ir, specific_interface.specific_id);
  704. } else {
  705. auto name_id =
  706. sem_ir.interfaces().Get(specific_interface.interface_id).name_id;
  707. return sem_ir.names().GetFormatted(name_id).str();
  708. }
  709. }
  710. } // namespace Carbon::SemIR