stringify.cpp 30 KB

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