stringify.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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, AliasBinding, SymbolicBinding, 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*/, CppVoidType /*inst*/) -> void {
  277. *out_ << "Cpp.void";
  278. }
  279. auto StringifyInst(InstId /*inst_id*/, CustomLayoutType inst) -> void {
  280. auto layout = sem_ir_->custom_layouts().Get(inst.layout_id);
  281. *out_ << "<size " << layout[CustomLayoutId::SizeIndex] << ", align "
  282. << layout[CustomLayoutId::AlignIndex] << ">";
  283. }
  284. auto StringifyInst(InstId /*inst_id*/, FacetAccessType inst) -> void {
  285. // Given `T:! I`, print `T as type` as simply `T`.
  286. step_stack_->PushInstId(inst.facet_value_inst_id);
  287. }
  288. auto StringifyInst(InstId /*inst_id*/, FacetType inst) -> void {
  289. const FacetTypeInfo& facet_type_info =
  290. sem_ir_->facet_types().Get(inst.facet_type_id);
  291. // Output `where` restrictions.
  292. bool some_where = false;
  293. if (facet_type_info.other_requirements) {
  294. step_stack_->PushString("...");
  295. some_where = true;
  296. }
  297. if (facet_type_info.builtin_constraint_mask.HasAnyOf(
  298. SemIR::BuiltinConstraintMask::TypeCanDestroy)) {
  299. if (some_where) {
  300. step_stack_->PushString(" and");
  301. }
  302. step_stack_->PushString(" .Self impls Core.CanDestroy");
  303. some_where = true;
  304. }
  305. for (auto rewrite : llvm::reverse(facet_type_info.rewrite_constraints)) {
  306. if (some_where) {
  307. step_stack_->PushString(" and");
  308. }
  309. step_stack_->Push(" ", rewrite.lhs_id, " = ", rewrite.rhs_id);
  310. some_where = true;
  311. }
  312. if (!facet_type_info.self_impls_constraints.empty()) {
  313. if (some_where) {
  314. step_stack_->PushString(" and");
  315. }
  316. llvm::ListSeparator sep(" & ");
  317. for (auto impls : llvm::reverse(facet_type_info.self_impls_constraints)) {
  318. step_stack_->Push(impls, &sep);
  319. }
  320. step_stack_->PushString(" .Self impls ");
  321. some_where = true;
  322. }
  323. // TODO: Other restrictions from facet_type_info.
  324. if (some_where) {
  325. step_stack_->PushString(" where");
  326. }
  327. // Output extend interface requirements.
  328. if (facet_type_info.extend_constraints.empty()) {
  329. step_stack_->PushString("type");
  330. return;
  331. }
  332. llvm::ListSeparator sep(" & ");
  333. for (auto impls : llvm::reverse(facet_type_info.extend_constraints)) {
  334. step_stack_->Push(impls, &sep);
  335. }
  336. }
  337. auto StringifyInst(InstId /*inst_id*/, FacetValue inst) -> void {
  338. // No need to output the witness.
  339. step_stack_->Push(inst.type_inst_id, " as ", inst.type_id);
  340. }
  341. auto StringifyInst(InstId /*inst_id*/, FloatType inst) -> void {
  342. *out_ << "<builtin ";
  343. step_stack_->PushString(">");
  344. if (auto width_value =
  345. sem_ir_->insts().TryGetAs<IntValue>(inst.bit_width_id)) {
  346. *out_ << "f";
  347. sem_ir_->ints().Get(width_value->int_id).print(*out_, /*isSigned=*/false);
  348. } else {
  349. *out_ << "Core.Float(";
  350. step_stack_->Push(inst.bit_width_id, ")");
  351. }
  352. }
  353. auto StringifyInst(InstId /*inst_id*/, CppOverloadSetType inst) -> void {
  354. const auto& overload_set =
  355. sem_ir_->cpp_overload_sets().Get(inst.overload_set_id);
  356. *out_ << "<type of ";
  357. step_stack_->Push(StepStack::QualifiedNameItem{overload_set.parent_scope_id,
  358. overload_set.name_id},
  359. ">");
  360. }
  361. auto StringifyInst(InstId /*inst_id*/, FunctionType inst) -> void {
  362. const auto& fn = sem_ir_->functions().Get(inst.function_id);
  363. *out_ << "<type of ";
  364. step_stack_->Push(
  365. StepStack::QualifiedNameItem{fn.parent_scope_id, fn.name_id}, ">");
  366. }
  367. auto StringifyInst(InstId /*inst_id*/, FunctionTypeWithSelfType inst)
  368. -> void {
  369. StepStack::PushItem fn_name = InstId::None;
  370. if (auto fn_inst = sem_ir_->insts().TryGetAs<FunctionType>(
  371. inst.interface_function_type_id)) {
  372. const auto& fn = sem_ir_->functions().Get(fn_inst->function_id);
  373. fn_name = StepStack::QualifiedNameItem(fn.parent_scope_id, fn.name_id);
  374. } else {
  375. fn_name = inst.interface_function_type_id;
  376. }
  377. *out_ << "<type of ";
  378. step_stack_->Push(fn_name, " in ", inst.self_id, ">");
  379. }
  380. auto StringifyInst(InstId /*inst_id*/, GenericClassType inst) -> void {
  381. const auto& class_info = sem_ir_->classes().Get(inst.class_id);
  382. *out_ << "<type of ";
  383. step_stack_->Push(StepStack::QualifiedNameItem{class_info.parent_scope_id,
  384. class_info.name_id},
  385. ">");
  386. }
  387. auto StringifyInst(InstId /*inst_id*/, GenericInterfaceType inst) -> void {
  388. const auto& interface = sem_ir_->interfaces().Get(inst.interface_id);
  389. *out_ << "<type of ";
  390. step_stack_->Push(StepStack::QualifiedNameItem{interface.parent_scope_id,
  391. interface.name_id},
  392. ">");
  393. }
  394. auto StringifyInst(InstId /*inst_id*/, GenericNamedConstraintType inst)
  395. -> void {
  396. const auto& constraint =
  397. sem_ir_->named_constraints().Get(inst.named_constraint_id);
  398. *out_ << "<type of ";
  399. step_stack_->Push(StepStack::QualifiedNameItem{constraint.parent_scope_id,
  400. constraint.name_id},
  401. ">");
  402. }
  403. // Determine the specific interface that an impl witness instruction provides
  404. // an implementation of.
  405. // TODO: Should we track this in the type?
  406. auto TryGetSpecificInterfaceForImplWitness(InstId impl_witness_id)
  407. -> std::optional<SpecificInterface> {
  408. if (auto lookup =
  409. sem_ir_->insts().TryGetAs<LookupImplWitness>(impl_witness_id)) {
  410. return sem_ir_->specific_interfaces().Get(
  411. lookup->query_specific_interface_id);
  412. }
  413. // TODO: Handle ImplWitness.
  414. return std::nullopt;
  415. }
  416. auto StringifyInst(InstId /*inst_id*/, ImplWitnessAccess inst) -> void {
  417. auto witness_inst_id =
  418. sem_ir_->constant_values().GetConstantInstId(inst.witness_id);
  419. auto lookup = sem_ir_->insts().GetAs<LookupImplWitness>(witness_inst_id);
  420. auto specific_interface =
  421. sem_ir_->specific_interfaces().Get(lookup.query_specific_interface_id);
  422. const auto& interface =
  423. sem_ir_->interfaces().Get(specific_interface.interface_id);
  424. if (!interface.associated_entities_id.has_value()) {
  425. step_stack_->Push(".(TODO: element ", inst.index, " in incomplete ",
  426. witness_inst_id, ")");
  427. } else {
  428. auto entities =
  429. sem_ir_->inst_blocks().Get(interface.associated_entities_id);
  430. size_t index = inst.index.index;
  431. CARBON_CHECK(index < entities.size(), "Access out of bounds.");
  432. auto entity_inst_id = entities[index];
  433. step_stack_->PushString(")");
  434. if (auto associated_const =
  435. sem_ir_->insts().TryGetAs<AssociatedConstantDecl>(
  436. entity_inst_id)) {
  437. step_stack_->PushNameId(sem_ir_->associated_constants()
  438. .Get(associated_const->assoc_const_id)
  439. .name_id);
  440. } else if (auto function_decl =
  441. sem_ir_->insts().TryGetAs<FunctionDecl>(entity_inst_id)) {
  442. const auto& function =
  443. sem_ir_->functions().Get(function_decl->function_id);
  444. step_stack_->PushNameId(function.name_id);
  445. } else {
  446. step_stack_->PushInstId(entity_inst_id);
  447. }
  448. step_stack_->Push(
  449. ".(",
  450. StepStack::EntityNameItem{interface, specific_interface.specific_id},
  451. ".");
  452. }
  453. if (auto lookup =
  454. sem_ir_->insts().TryGetAs<LookupImplWitness>(witness_inst_id)) {
  455. bool period_self = false;
  456. if (auto sym_name = sem_ir_->insts().TryGetAs<SymbolicBinding>(
  457. lookup->query_self_inst_id)) {
  458. auto name_id =
  459. sem_ir_->entity_names().Get(sym_name->entity_name_id).name_id;
  460. period_self = (name_id == NameId::PeriodSelf);
  461. }
  462. if (!period_self) {
  463. step_stack_->PushInstId(lookup->query_self_inst_id);
  464. }
  465. } else {
  466. // TODO: Omit parens if not needed for precedence.
  467. step_stack_->Push("(", witness_inst_id, ")");
  468. }
  469. }
  470. auto StringifyInst(InstId /*inst_id*/, ImportRefUnloaded inst) -> void {
  471. if (inst.entity_name_id.has_value()) {
  472. step_stack_->PushEntityNameId(inst.entity_name_id);
  473. } else {
  474. *out_ << "<import ref unloaded invalid entity name>";
  475. }
  476. }
  477. auto StringifyInst(InstId /*inst_id*/, IntType inst) -> void {
  478. *out_ << "<builtin ";
  479. step_stack_->PushString(">");
  480. if (auto width_value =
  481. sem_ir_->insts().TryGetAs<IntValue>(inst.bit_width_id)) {
  482. *out_ << (inst.int_kind.is_signed() ? "i" : "u");
  483. sem_ir_->ints().Get(width_value->int_id).print(*out_, /*isSigned=*/false);
  484. } else {
  485. *out_ << (inst.int_kind.is_signed() ? "Int(" : "UInt(");
  486. step_stack_->Push(inst.bit_width_id, ")");
  487. }
  488. }
  489. auto StringifyInst(InstId /*inst_id*/, IntValue inst) -> void {
  490. sem_ir_->ints().Get(inst.int_id).print(*out_, /*isSigned=*/true);
  491. }
  492. auto StringifyInst(InstId /*inst_id*/, LookupImplWitness inst) -> void {
  493. step_stack_->Push(
  494. inst.query_self_inst_id, " as ",
  495. sem_ir_->specific_interfaces().Get(inst.query_specific_interface_id));
  496. }
  497. auto StringifyInst(InstId /*inst_id*/, MaybeUnformedType inst) -> void {
  498. step_stack_->Push("<builtin MaybeUnformed(", inst.inner_id, ")>");
  499. }
  500. auto StringifyInst(InstId /*inst_id*/, NameRef inst) -> void {
  501. *out_ << sem_ir_->names().GetFormatted(inst.name_id);
  502. }
  503. auto StringifyInst(InstId /*inst_id*/, Namespace inst) -> void {
  504. const auto& name_scope = sem_ir_->name_scopes().Get(inst.name_scope_id);
  505. step_stack_->PushQualifiedName(name_scope.parent_scope_id(),
  506. name_scope.name_id());
  507. }
  508. auto StringifyInst(InstId /*inst_id*/, PartialType inst) -> void {
  509. *out_ << "partial ";
  510. step_stack_->PushInstId(inst.inner_id);
  511. }
  512. auto StringifyInst(InstId /*inst_id*/, PatternType inst) -> void {
  513. *out_ << "<pattern for ";
  514. step_stack_->Push(inst.scrutinee_type_inst_id, ">");
  515. }
  516. auto StringifyInst(InstId /*inst_id*/, PointerType inst) -> void {
  517. step_stack_->Push(inst.pointee_id, "*");
  518. }
  519. auto StringifyInst(InstId /*inst_id*/, SpecificFunction inst) -> void {
  520. auto callee = GetCallee(*sem_ir_, inst.callee_id);
  521. if (auto* fn = std::get_if<CalleeFunction>(&callee)) {
  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*/, SpecificImplFunction inst) -> void {
  529. auto callee = GetCallee(*sem_ir_, inst.callee_id);
  530. if (auto* fn = std::get_if<CalleeFunction>(&callee)) {
  531. // TODO: The specific_id here is for the interface member, but the
  532. // entity we're passing is the impl member. This might result in
  533. // strange output once we render specific arguments properly.
  534. step_stack_->PushEntityName(sem_ir_->functions().Get(fn->function_id),
  535. inst.specific_id);
  536. return;
  537. }
  538. step_stack_->PushString("<invalid specific function>");
  539. }
  540. auto StringifyInst(InstId /*inst_id*/, StructType inst) -> void {
  541. auto fields = sem_ir_->struct_type_fields().Get(inst.fields_id);
  542. if (fields.empty()) {
  543. *out_ << "{}";
  544. return;
  545. }
  546. *out_ << "{";
  547. step_stack_->PushString("}");
  548. llvm::ListSeparator sep;
  549. for (auto field : llvm::reverse(fields)) {
  550. step_stack_->Push(".", field.name_id, ": ", field.type_inst_id, &sep);
  551. }
  552. }
  553. auto StringifyInst(InstId /*inst_id*/, StructValue inst) -> void {
  554. auto field_values = sem_ir_->inst_blocks().Get(inst.elements_id);
  555. if (field_values.empty()) {
  556. *out_ << "{}";
  557. return;
  558. }
  559. auto struct_type = sem_ir_->types().GetAs<StructType>(
  560. sem_ir_->types().GetObjectRepr(inst.type_id));
  561. auto fields = sem_ir_->struct_type_fields().Get(struct_type.fields_id);
  562. if (fields.size() != field_values.size()) {
  563. *out_ << "{<struct value type length mismatch>}";
  564. return;
  565. }
  566. *out_ << "{";
  567. step_stack_->PushString("}");
  568. llvm::ListSeparator sep;
  569. for (auto [field, value_inst_id] :
  570. llvm::reverse(llvm::zip(fields, field_values))) {
  571. step_stack_->Push(".", field.name_id, " = ", value_inst_id, &sep);
  572. }
  573. }
  574. auto StringifyInst(InstId /*inst_id*/, SymbolicBindingType inst) -> void {
  575. step_stack_->PushEntityNameId(inst.entity_name_id);
  576. }
  577. auto StringifyInst(InstId /*inst_id*/, TupleType inst) -> void {
  578. auto refs = sem_ir_->inst_blocks().Get(inst.type_elements_id);
  579. if (refs.empty()) {
  580. *out_ << "()";
  581. return;
  582. }
  583. *out_ << "(";
  584. step_stack_->PushString(")");
  585. // A tuple of one element has a comma to disambiguate from an
  586. // expression.
  587. if (refs.size() == 1) {
  588. step_stack_->PushString(",");
  589. }
  590. llvm::ListSeparator sep;
  591. for (auto ref : llvm::reverse(refs)) {
  592. step_stack_->Push(ref, &sep);
  593. }
  594. }
  595. auto StringifyInst(InstId /*inst_id*/, TupleValue inst) -> void {
  596. auto refs = sem_ir_->inst_blocks().Get(inst.elements_id);
  597. if (refs.empty()) {
  598. *out_ << "()";
  599. return;
  600. }
  601. *out_ << "(";
  602. step_stack_->PushString(")");
  603. // A tuple of one element has a comma to disambiguate from an
  604. // expression.
  605. if (refs.size() == 1) {
  606. step_stack_->PushString(",");
  607. }
  608. llvm::ListSeparator sep;
  609. for (auto ref : llvm::reverse(refs)) {
  610. step_stack_->Push(ref, &sep);
  611. }
  612. }
  613. auto StringifyInst(InstId inst_id, TypeOfInst /*inst*/) -> void {
  614. // Print the constant value if we've already computed the inst.
  615. auto const_inst_id = sem_ir_->constant_values().GetConstantInstId(inst_id);
  616. if (const_inst_id.has_value() && const_inst_id != inst_id) {
  617. step_stack_->PushInstId(const_inst_id);
  618. return;
  619. }
  620. *out_ << "<dependent type>";
  621. }
  622. auto StringifyInst(InstId /*inst_id*/, UnboundElementType inst) -> void {
  623. *out_ << "<unbound element of class ";
  624. step_stack_->Push(inst.class_type_inst_id, ">");
  625. }
  626. auto StringifyInst(InstId /*inst_id*/, VtablePtr /*inst*/) -> void {
  627. *out_ << "<vtable ptr>";
  628. }
  629. private:
  630. const File* sem_ir_;
  631. StepStack* step_stack_;
  632. llvm::raw_ostream* out_;
  633. };
  634. } // namespace
  635. // NOLINTNEXTLINE(readability-function-size)
  636. static auto Stringify(const File& sem_ir, StepStack& step_stack)
  637. -> std::string {
  638. RawStringOstream out;
  639. Stringifier stringifier(&sem_ir, &step_stack, &out);
  640. while (!step_stack.empty()) {
  641. CARBON_KIND_SWITCH(step_stack.Pop()) {
  642. case CARBON_KIND(InstId inst_id): {
  643. if (!inst_id.has_value()) {
  644. out << "<invalid>";
  645. break;
  646. }
  647. auto untyped_inst = sem_ir.insts().Get(inst_id);
  648. CARBON_KIND_SWITCH(untyped_inst) {
  649. #define CARBON_SEM_IR_INST_KIND(InstT) \
  650. case CARBON_KIND(InstT typed_inst): { \
  651. stringifier.StringifyInst(inst_id, typed_inst); \
  652. break; \
  653. }
  654. #include "toolchain/sem_ir/inst_kind.def"
  655. }
  656. break;
  657. }
  658. case CARBON_KIND(llvm::StringRef string):
  659. out << string;
  660. break;
  661. case CARBON_KIND(NameId name_id):
  662. out << sem_ir.names().GetFormatted(name_id);
  663. break;
  664. case CARBON_KIND(ElementIndex element_index):
  665. out << element_index.index;
  666. break;
  667. }
  668. }
  669. return out.TakeStr();
  670. }
  671. auto StringifyConstantInst(const File& sem_ir, InstId outer_inst_id)
  672. -> std::string {
  673. StepStack step_stack(&sem_ir);
  674. step_stack.PushInstId(outer_inst_id);
  675. return Stringify(sem_ir, step_stack);
  676. }
  677. auto StringifySpecific(const File& sem_ir, SpecificId specific_id)
  678. -> std::string {
  679. StepStack step_stack(&sem_ir);
  680. const auto& specific = sem_ir.specifics().Get(specific_id);
  681. const auto& generic = sem_ir.generics().Get(specific.generic_id);
  682. auto decl = sem_ir.insts().Get(generic.decl_id);
  683. CARBON_KIND_SWITCH(decl) {
  684. case CARBON_KIND(ClassDecl class_decl): {
  685. // Print `Core.Int(N)` as `iN`.
  686. // TODO: This duplicates work done in StringifyInst for ClassType.
  687. const auto& class_info = sem_ir.classes().Get(class_decl.class_id);
  688. if (auto literal_info = TypeLiteralInfo::ForType(
  689. sem_ir, ClassType{.type_id = TypeType::TypeId,
  690. .class_id = class_decl.class_id,
  691. .specific_id = specific_id});
  692. literal_info.is_valid()) {
  693. RawStringOstream out;
  694. literal_info.PrintLiteral(sem_ir, out);
  695. return out.TakeStr();
  696. }
  697. step_stack.PushEntityName(class_info, specific_id);
  698. break;
  699. }
  700. case CARBON_KIND(FunctionDecl function_decl): {
  701. step_stack.PushEntityName(
  702. sem_ir.functions().Get(function_decl.function_id), specific_id);
  703. break;
  704. }
  705. case CARBON_KIND(ImplDecl impl_decl): {
  706. step_stack.PushEntityName(sem_ir.impls().Get(impl_decl.impl_id),
  707. specific_id);
  708. break;
  709. }
  710. case CARBON_KIND(InterfaceDecl interface_decl): {
  711. step_stack.PushEntityName(
  712. sem_ir.interfaces().Get(interface_decl.interface_id), specific_id);
  713. break;
  714. }
  715. default: {
  716. // TODO: Include the specific arguments here.
  717. step_stack.PushInstId(generic.decl_id);
  718. break;
  719. }
  720. }
  721. return Stringify(sem_ir, step_stack);
  722. }
  723. auto StringifySpecificInterface(const File& sem_ir,
  724. SpecificInterface specific_interface)
  725. -> std::string {
  726. if (specific_interface.specific_id.has_value()) {
  727. return StringifySpecific(sem_ir, specific_interface.specific_id);
  728. } else {
  729. auto name_id =
  730. sem_ir.interfaces().Get(specific_interface.interface_id).name_id;
  731. return sem_ir.names().GetFormatted(name_id).str();
  732. }
  733. }
  734. } // namespace Carbon::SemIR