stringify.cpp 29 KB

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