stringify.cpp 28 KB

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