stringify.cpp 29 KB

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