stringify.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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().GetTypeInstId(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 drop_back_count = 0;
  196. const auto& generic = sem_ir_->generics().Get(specific.generic_id);
  197. if (sem_ir_->insts()
  198. .IsOneOf<InterfaceWithSelfDecl, NamedConstraintWithSelfDecl>(
  199. generic.decl_id)) {
  200. // The with-self generic contains an additional `Self` parameter beyond
  201. // the parameters of the entity, the argument for which we do not include
  202. // in the display.
  203. drop_back_count = 1;
  204. }
  205. auto args = sem_ir_->inst_blocks()
  206. .Get(specific.args_id)
  207. .drop_back(drop_back_count)
  208. .take_back(num_params);
  209. bool last = true;
  210. for (auto arg : llvm::reverse(args)) {
  211. PushString(last ? ")" : ", ");
  212. PushInstId(arg);
  213. last = false;
  214. }
  215. PushString("(");
  216. }
  217. const File* sem_ir_;
  218. // Remaining steps to take.
  219. llvm::SmallVector<Step> steps_;
  220. };
  221. // Provides `StringifyInst` overloads for each instruction.
  222. class Stringifier {
  223. public:
  224. explicit Stringifier(const File* sem_ir, StepStack* step_stack,
  225. llvm::raw_ostream* out)
  226. : sem_ir_(sem_ir), step_stack_(step_stack), out_(out) {}
  227. // By default try to print a constant, but otherwise may fail to
  228. // stringify.
  229. auto StringifyInstDefault(InstId inst_id, Inst inst) -> void {
  230. // We don't know how to print this instruction, but it might have a
  231. // constant value that we can print.
  232. auto const_inst_id = sem_ir_->constant_values().GetConstantInstId(inst_id);
  233. if (const_inst_id.has_value() && const_inst_id != inst_id) {
  234. step_stack_->PushInstId(const_inst_id);
  235. return;
  236. }
  237. // We don't need to handle stringification for instructions that don't
  238. // show up in errors, but make it clear what's going on so that it's
  239. // clearer when stringification is needed.
  240. *out_ << "<cannot stringify " << inst_id << ": " << inst << ">";
  241. }
  242. template <typename InstT>
  243. auto StringifyInst(InstId inst_id, InstT inst) -> void {
  244. // This doesn't use requires so that more specific overloads are chosen when
  245. // provided.
  246. static_assert(InstT::Kind.is_type() != InstIsType::Always ||
  247. std::same_as<InstT, WhereExpr>,
  248. "Types should have a dedicated overload");
  249. // TODO: We should have Stringify support for all types where
  250. // InstT::Kind.constant_kind() is neither Never nor Indirect.
  251. StringifyInstDefault(inst_id, inst);
  252. }
  253. // Singleton instructions use their IR name as a label.
  254. template <typename InstT>
  255. requires(IsSingletonInstKind(InstT::Kind))
  256. auto StringifyInst(InstId /*inst_id*/, InstT /*inst*/) -> void {
  257. *out_ << InstT::Kind.ir_name();
  258. }
  259. auto StringifyInst(InstId /*inst_id*/, ArrayType inst) -> void {
  260. *out_ << "array(";
  261. step_stack_->Push(inst.element_type_inst_id, ", ", inst.bound_id, ")");
  262. }
  263. auto StringifyInst(InstId /*inst_id*/, AssociatedConstantDecl inst) -> void {
  264. const auto& assoc_const =
  265. sem_ir_->associated_constants().Get(inst.assoc_const_id);
  266. step_stack_->PushQualifiedName(assoc_const.parent_scope_id,
  267. assoc_const.name_id);
  268. }
  269. auto StringifyInst(InstId /*inst_id*/, AssociatedEntityType inst) -> void {
  270. *out_ << "<associated entity in ";
  271. step_stack_->Push(">");
  272. step_stack_->PushSpecificInterface(inst.GetSpecificInterface());
  273. }
  274. auto StringifyInst(InstId /*inst_id*/, BoolLiteral inst) -> void {
  275. step_stack_->Push(inst.value.ToBool() ? "true" : "false");
  276. }
  277. template <typename InstT>
  278. requires(SameAsOneOf<InstT, AliasBinding, SymbolicBinding, ExportDecl>)
  279. auto StringifyInst(InstId /*inst_id*/, InstT inst) -> void {
  280. step_stack_->PushEntityNameId(inst.entity_name_id);
  281. }
  282. auto StringifyInst(InstId /*inst_id*/, ClassType inst) -> void {
  283. const auto& class_info = sem_ir_->classes().Get(inst.class_id);
  284. if (auto type_info = RecognizedTypeInfo::ForType(*sem_ir_, inst);
  285. type_info.is_valid()) {
  286. if (type_info.PrintLiteral(*sem_ir_, *out_)) {
  287. return;
  288. }
  289. }
  290. step_stack_->PushEntityName(class_info, inst.specific_id);
  291. }
  292. auto StringifyInst(InstId /*inst_id*/, ConstType inst) -> void {
  293. *out_ << "const ";
  294. // Add parentheses if required.
  295. if (GetPrecedence(sem_ir_->insts().Get(inst.inner_id).kind()) <
  296. GetPrecedence(ConstType::Kind)) {
  297. *out_ << "(";
  298. // Note the `inst.inner_id` ends up here.
  299. step_stack_->PushString(")");
  300. }
  301. step_stack_->PushInstId(inst.inner_id);
  302. }
  303. auto StringifyInst(InstId /*inst_id*/, CppTemplateNameType inst) -> void {
  304. *out_ << "<type of ";
  305. step_stack_->Push(inst.name_id, ">");
  306. }
  307. auto StringifyInst(InstId /*inst_id*/, CustomLayoutType inst) -> void {
  308. auto layout = sem_ir_->custom_layouts().Get(inst.layout_id);
  309. *out_ << "<size " << layout[CustomLayoutId::SizeIndex] << ", align "
  310. << layout[CustomLayoutId::AlignIndex] << ">";
  311. }
  312. auto StringifyInst(InstId /*inst_id*/, FacetAccessType inst) -> void {
  313. // Given `T:! I`, print `T as type` as simply `T`.
  314. step_stack_->PushInstId(inst.facet_value_inst_id);
  315. }
  316. auto StringifyInst(InstId /*inst_id*/, FacetType inst) -> void {
  317. step_stack_->PushFacetType(inst.facet_type_id);
  318. }
  319. auto StringifyInst(InstId /*inst_id*/, FacetValue inst) -> void {
  320. // No need to output the witness.
  321. step_stack_->Push(inst.type_inst_id, " as ", inst.type_id);
  322. }
  323. auto StringifyInst(InstId /*inst_id*/, FloatType inst) -> void {
  324. *out_ << "<builtin ";
  325. step_stack_->PushString(">");
  326. if (auto width_value =
  327. sem_ir_->insts().TryGetAs<IntValue>(inst.bit_width_id)) {
  328. *out_ << "f";
  329. sem_ir_->ints().Get(width_value->int_id).print(*out_, /*isSigned=*/false);
  330. } else {
  331. *out_ << "Core.Float(";
  332. step_stack_->Push(inst.bit_width_id, ")");
  333. }
  334. }
  335. auto StringifyInst(InstId /*inst_id*/, CppOverloadSetType inst) -> void {
  336. const auto& overload_set =
  337. sem_ir_->cpp_overload_sets().Get(inst.overload_set_id);
  338. *out_ << "<type of ";
  339. step_stack_->Push(StepStack::QualifiedNameItem{overload_set.parent_scope_id,
  340. overload_set.name_id},
  341. ">");
  342. }
  343. auto StringifyInst(InstId /*inst_id*/, FunctionType inst) -> void {
  344. const auto& fn = sem_ir_->functions().Get(inst.function_id);
  345. *out_ << "<type of ";
  346. step_stack_->Push(
  347. StepStack::QualifiedNameItem{fn.parent_scope_id, fn.name_id}, ">");
  348. }
  349. auto StringifyInst(InstId /*inst_id*/, FunctionTypeWithSelfType inst)
  350. -> void {
  351. StepStack::PushItem fn_name = InstId::None;
  352. if (auto fn_inst = sem_ir_->insts().TryGetAs<FunctionType>(
  353. inst.interface_function_type_id)) {
  354. const auto& fn = sem_ir_->functions().Get(fn_inst->function_id);
  355. fn_name = StepStack::QualifiedNameItem(fn.parent_scope_id, fn.name_id);
  356. } else {
  357. fn_name = inst.interface_function_type_id;
  358. }
  359. *out_ << "<type of ";
  360. step_stack_->Push(fn_name, " in ", inst.self_id, ">");
  361. }
  362. auto StringifyInst(InstId /*inst_id*/, GenericClassType inst) -> void {
  363. const auto& class_info = sem_ir_->classes().Get(inst.class_id);
  364. *out_ << "<type of ";
  365. step_stack_->Push(StepStack::QualifiedNameItem{class_info.parent_scope_id,
  366. class_info.name_id},
  367. ">");
  368. }
  369. auto StringifyInst(InstId /*inst_id*/, GenericInterfaceType inst) -> void {
  370. const auto& interface = sem_ir_->interfaces().Get(inst.interface_id);
  371. *out_ << "<type of ";
  372. step_stack_->Push(StepStack::QualifiedNameItem{interface.parent_scope_id,
  373. interface.name_id},
  374. ">");
  375. }
  376. auto StringifyInst(InstId /*inst_id*/, GenericNamedConstraintType inst)
  377. -> void {
  378. const auto& constraint =
  379. sem_ir_->named_constraints().Get(inst.named_constraint_id);
  380. *out_ << "<type of ";
  381. step_stack_->Push(StepStack::QualifiedNameItem{constraint.parent_scope_id,
  382. constraint.name_id},
  383. ">");
  384. }
  385. // Determine the specific interface that an impl witness instruction provides
  386. // an implementation of.
  387. // TODO: Should we track this in the type?
  388. auto TryGetSpecificInterfaceForImplWitness(InstId impl_witness_id)
  389. -> std::optional<SpecificInterface> {
  390. if (auto lookup =
  391. sem_ir_->insts().TryGetAs<LookupImplWitness>(impl_witness_id)) {
  392. return sem_ir_->specific_interfaces().Get(
  393. lookup->query_specific_interface_id);
  394. }
  395. // TODO: Handle ImplWitness.
  396. return std::nullopt;
  397. }
  398. auto StringifyInst(InstId /*inst_id*/, ImplWitnessAccess inst) -> void {
  399. auto witness_inst_id =
  400. sem_ir_->constant_values().GetConstantInstId(inst.witness_id);
  401. auto lookup = sem_ir_->insts().GetAs<LookupImplWitness>(witness_inst_id);
  402. auto specific_interface =
  403. sem_ir_->specific_interfaces().Get(lookup.query_specific_interface_id);
  404. const auto& interface =
  405. sem_ir_->interfaces().Get(specific_interface.interface_id);
  406. if (!interface.associated_entities_id.has_value()) {
  407. step_stack_->Push(".(TODO: element ", inst.index, " in incomplete ",
  408. witness_inst_id, ")");
  409. } else {
  410. auto entities =
  411. sem_ir_->inst_blocks().Get(interface.associated_entities_id);
  412. size_t index = inst.index.index;
  413. CARBON_CHECK(index < entities.size(), "Access out of bounds.");
  414. auto entity_inst_id = entities[index];
  415. step_stack_->PushString(")");
  416. if (auto associated_const =
  417. sem_ir_->insts().TryGetAs<AssociatedConstantDecl>(
  418. entity_inst_id)) {
  419. step_stack_->PushNameId(sem_ir_->associated_constants()
  420. .Get(associated_const->assoc_const_id)
  421. .name_id);
  422. } else if (auto function_decl =
  423. sem_ir_->insts().TryGetAs<FunctionDecl>(entity_inst_id)) {
  424. const auto& function =
  425. sem_ir_->functions().Get(function_decl->function_id);
  426. step_stack_->PushNameId(function.name_id);
  427. } else {
  428. step_stack_->PushInstId(entity_inst_id);
  429. }
  430. step_stack_->Push(
  431. ".(",
  432. StepStack::EntityNameItem{interface, specific_interface.specific_id},
  433. ".");
  434. }
  435. if (auto lookup =
  436. sem_ir_->insts().TryGetAs<LookupImplWitness>(witness_inst_id)) {
  437. bool period_self = false;
  438. if (auto sym_name = sem_ir_->insts().TryGetAs<SymbolicBinding>(
  439. lookup->query_self_inst_id)) {
  440. auto name_id =
  441. sem_ir_->entity_names().Get(sym_name->entity_name_id).name_id;
  442. period_self = (name_id == NameId::PeriodSelf);
  443. }
  444. if (!period_self) {
  445. step_stack_->PushInstId(lookup->query_self_inst_id);
  446. }
  447. } else {
  448. // TODO: Omit parens if not needed for precedence.
  449. step_stack_->Push("(", witness_inst_id, ")");
  450. }
  451. }
  452. auto StringifyInst(InstId /*inst_id*/, ImportRefUnloaded inst) -> void {
  453. if (inst.entity_name_id.has_value()) {
  454. step_stack_->PushEntityNameId(inst.entity_name_id);
  455. } else {
  456. *out_ << "<import ref unloaded invalid entity name>";
  457. }
  458. }
  459. auto StringifyInst(InstId /*inst_id*/, IntType inst) -> void {
  460. *out_ << "<builtin ";
  461. step_stack_->PushString(">");
  462. if (auto width_value =
  463. sem_ir_->insts().TryGetAs<IntValue>(inst.bit_width_id)) {
  464. *out_ << (inst.int_kind.is_signed() ? "i" : "u");
  465. sem_ir_->ints().Get(width_value->int_id).print(*out_, /*isSigned=*/false);
  466. } else {
  467. *out_ << (inst.int_kind.is_signed() ? "Int(" : "UInt(");
  468. step_stack_->Push(inst.bit_width_id, ")");
  469. }
  470. }
  471. auto StringifyInst(InstId /*inst_id*/, IntValue inst) -> void {
  472. sem_ir_->ints().Get(inst.int_id).print(*out_, /*isSigned=*/true);
  473. }
  474. auto StringifyInst(InstId /*inst_id*/, LookupImplWitness inst) -> void {
  475. step_stack_->Push(
  476. inst.query_self_inst_id, " as ",
  477. sem_ir_->specific_interfaces().Get(inst.query_specific_interface_id));
  478. }
  479. auto StringifyInst(InstId /*inst_id*/, MaybeUnformedType inst) -> void {
  480. step_stack_->Push("<builtin MaybeUnformed(", inst.inner_id, ")>");
  481. }
  482. auto StringifyInst(InstId /*inst_id*/, NameRef inst) -> void {
  483. *out_ << sem_ir_->names().GetFormatted(inst.name_id);
  484. }
  485. auto StringifyInst(InstId /*inst_id*/, Namespace inst) -> void {
  486. const auto& name_scope = sem_ir_->name_scopes().Get(inst.name_scope_id);
  487. step_stack_->PushQualifiedName(name_scope.parent_scope_id(),
  488. name_scope.name_id());
  489. }
  490. auto StringifyInst(InstId /*inst_id*/, PartialType inst) -> void {
  491. *out_ << "partial ";
  492. step_stack_->PushInstId(inst.inner_id);
  493. }
  494. auto StringifyInst(InstId /*inst_id*/, PatternType inst) -> void {
  495. *out_ << "<pattern for ";
  496. step_stack_->Push(inst.scrutinee_type_inst_id, ">");
  497. }
  498. auto StringifyInst(InstId /*inst_id*/, PointerType inst) -> void {
  499. step_stack_->Push(inst.pointee_id, "*");
  500. }
  501. auto StringifyInst(InstId /*inst_id*/, SpecificFunction inst) -> void {
  502. auto callee = GetCallee(*sem_ir_, inst.callee_id);
  503. if (auto* fn = std::get_if<CalleeFunction>(&callee)) {
  504. step_stack_->PushEntityName(sem_ir_->functions().Get(fn->function_id),
  505. inst.specific_id);
  506. return;
  507. }
  508. step_stack_->PushString("<invalid specific function>");
  509. }
  510. auto StringifyInst(InstId /*inst_id*/, SpecificImplFunction inst) -> void {
  511. auto callee = GetCallee(*sem_ir_, inst.callee_id);
  512. if (auto* fn = std::get_if<CalleeFunction>(&callee)) {
  513. // TODO: The specific_id here is for the interface member, but the
  514. // entity we're passing is the impl member. This might result in
  515. // strange output once we render specific arguments properly.
  516. step_stack_->PushEntityName(sem_ir_->functions().Get(fn->function_id),
  517. inst.specific_id);
  518. return;
  519. }
  520. step_stack_->PushString("<invalid specific function>");
  521. }
  522. auto StringifyInst(InstId /*inst_id*/, StructType inst) -> void {
  523. auto fields = sem_ir_->struct_type_fields().Get(inst.fields_id);
  524. if (fields.empty()) {
  525. *out_ << "{}";
  526. return;
  527. }
  528. *out_ << "{";
  529. step_stack_->PushString("}");
  530. llvm::ListSeparator sep;
  531. for (auto field : llvm::reverse(fields)) {
  532. step_stack_->Push(".", field.name_id, ": ", field.type_inst_id, &sep);
  533. }
  534. }
  535. auto StringifyInst(InstId /*inst_id*/, StructValue inst) -> void {
  536. auto field_values = sem_ir_->inst_blocks().Get(inst.elements_id);
  537. if (field_values.empty()) {
  538. *out_ << "{}";
  539. return;
  540. }
  541. auto struct_type = sem_ir_->types().GetAs<StructType>(
  542. sem_ir_->types().GetObjectRepr(inst.type_id));
  543. auto fields = sem_ir_->struct_type_fields().Get(struct_type.fields_id);
  544. if (fields.size() != field_values.size()) {
  545. *out_ << "{<struct value type length mismatch>}";
  546. return;
  547. }
  548. *out_ << "{";
  549. step_stack_->PushString("}");
  550. llvm::ListSeparator sep;
  551. for (auto [field, value_inst_id] :
  552. llvm::reverse(llvm::zip_equal(fields, field_values))) {
  553. step_stack_->Push(".", field.name_id, " = ", value_inst_id, &sep);
  554. }
  555. }
  556. auto StringifyInst(InstId /*inst_id*/, SymbolicBindingType inst) -> void {
  557. step_stack_->PushEntityNameId(inst.entity_name_id);
  558. }
  559. auto StringifyInst(InstId /*inst_id*/, TupleType inst) -> void {
  560. auto refs = sem_ir_->inst_blocks().Get(inst.type_elements_id);
  561. if (refs.empty()) {
  562. *out_ << "()";
  563. return;
  564. }
  565. *out_ << "(";
  566. step_stack_->PushString(")");
  567. // A tuple of one element has a comma to disambiguate from an
  568. // expression.
  569. if (refs.size() == 1) {
  570. step_stack_->PushString(",");
  571. }
  572. llvm::ListSeparator sep;
  573. for (auto ref : llvm::reverse(refs)) {
  574. step_stack_->Push(ref, &sep);
  575. }
  576. }
  577. auto StringifyInst(InstId /*inst_id*/, TupleValue inst) -> void {
  578. auto refs = sem_ir_->inst_blocks().Get(inst.elements_id);
  579. if (refs.empty()) {
  580. *out_ << "()";
  581. return;
  582. }
  583. *out_ << "(";
  584. step_stack_->PushString(")");
  585. // A tuple of one element has a comma to disambiguate from an
  586. // expression.
  587. if (refs.size() == 1) {
  588. step_stack_->PushString(",");
  589. }
  590. llvm::ListSeparator sep;
  591. for (auto ref : llvm::reverse(refs)) {
  592. step_stack_->Push(ref, &sep);
  593. }
  594. }
  595. auto StringifyInst(InstId /*inst_id*/, TypeComponentOf inst) -> void {
  596. *out_ << "<type component of form ";
  597. step_stack_->Push(inst.form_inst_id, ">");
  598. }
  599. auto StringifyInst(InstId inst_id, TypeOfInst /*inst*/) -> void {
  600. // Print the constant value if we've already computed the inst.
  601. auto const_inst_id = sem_ir_->constant_values().GetConstantInstId(inst_id);
  602. if (const_inst_id.has_value() && const_inst_id != inst_id) {
  603. step_stack_->PushInstId(const_inst_id);
  604. return;
  605. }
  606. *out_ << "<dependent type>";
  607. }
  608. auto StringifyInst(InstId /*inst_id*/, UnboundElementType inst) -> void {
  609. *out_ << "<unbound element of class ";
  610. step_stack_->Push(inst.class_type_inst_id, ">");
  611. }
  612. auto StringifyInst(InstId /*inst_id*/, VtablePtr /*inst*/) -> void {
  613. *out_ << "<vtable ptr>";
  614. }
  615. auto StringifyFacetType(FacetTypeId facet_type_id) -> void {
  616. const FacetTypeInfo& facet_type_info =
  617. sem_ir_->facet_types().Get(facet_type_id);
  618. // Output `where` restrictions.
  619. bool some_where = false;
  620. if (facet_type_info.other_requirements) {
  621. step_stack_->PushString("...");
  622. some_where = true;
  623. }
  624. for (auto rewrite : llvm::reverse(facet_type_info.rewrite_constraints)) {
  625. if (some_where) {
  626. step_stack_->PushString(" and");
  627. }
  628. step_stack_->Push(" ", rewrite.lhs_id, " = ", rewrite.rhs_id);
  629. some_where = true;
  630. }
  631. if (!facet_type_info.self_impls_constraints.empty() ||
  632. !facet_type_info.self_impls_named_constraints.empty()) {
  633. if (some_where) {
  634. step_stack_->PushString(" and");
  635. }
  636. llvm::ListSeparator sep(" & ");
  637. for (auto impls :
  638. llvm::reverse(facet_type_info.self_impls_named_constraints)) {
  639. step_stack_->Push(impls, &sep);
  640. }
  641. for (auto impls : llvm::reverse(facet_type_info.self_impls_constraints)) {
  642. step_stack_->Push(impls, &sep);
  643. }
  644. step_stack_->PushString(" .Self impls ");
  645. some_where = true;
  646. }
  647. // TODO: Other restrictions from facet_type_info.
  648. if (some_where) {
  649. step_stack_->PushString(" where");
  650. }
  651. // Output extend interface and named constraint requirements.
  652. if (facet_type_info.extend_constraints.empty() &&
  653. facet_type_info.extend_named_constraints.empty()) {
  654. step_stack_->PushString("type");
  655. return;
  656. }
  657. llvm::ListSeparator sep(" & ");
  658. for (auto extend :
  659. llvm::reverse(facet_type_info.extend_named_constraints)) {
  660. step_stack_->Push(extend, &sep);
  661. }
  662. for (auto extend : llvm::reverse(facet_type_info.extend_constraints)) {
  663. step_stack_->Push(extend, &sep);
  664. }
  665. }
  666. private:
  667. const File* sem_ir_;
  668. StepStack* step_stack_;
  669. llvm::raw_ostream* out_;
  670. };
  671. } // namespace
  672. static auto Stringify(const File& sem_ir, StepStack& step_stack)
  673. -> std::string {
  674. RawStringOstream out;
  675. Stringifier stringifier(&sem_ir, &step_stack, &out);
  676. while (!step_stack.empty()) {
  677. CARBON_KIND_SWITCH(step_stack.Pop()) {
  678. case CARBON_KIND(InstId inst_id): {
  679. if (!inst_id.has_value()) {
  680. out << "<invalid>";
  681. break;
  682. }
  683. auto untyped_inst = sem_ir.insts().Get(inst_id);
  684. CARBON_KIND_SWITCH(untyped_inst) {
  685. #define CARBON_SEM_IR_INST_KIND(InstT) \
  686. case CARBON_KIND(InstT typed_inst): { \
  687. stringifier.StringifyInst(inst_id, typed_inst); \
  688. break; \
  689. }
  690. #include "toolchain/sem_ir/inst_kind.def"
  691. }
  692. break;
  693. }
  694. case CARBON_KIND(llvm::StringRef string):
  695. out << string;
  696. break;
  697. case CARBON_KIND(NameId name_id):
  698. out << sem_ir.names().GetFormatted(name_id);
  699. break;
  700. case CARBON_KIND(ElementIndex element_index):
  701. out << element_index.index;
  702. break;
  703. case CARBON_KIND(FacetTypeId facet_type_id):
  704. stringifier.StringifyFacetType(facet_type_id);
  705. break;
  706. }
  707. }
  708. return out.TakeStr();
  709. }
  710. auto StringifyConstantInst(const File& sem_ir, InstId outer_inst_id)
  711. -> std::string {
  712. StepStack step_stack(&sem_ir);
  713. step_stack.PushInstId(outer_inst_id);
  714. return Stringify(sem_ir, step_stack);
  715. }
  716. auto StringifySpecific(const File& sem_ir, SpecificId specific_id)
  717. -> std::string {
  718. StepStack step_stack(&sem_ir);
  719. const auto& specific = sem_ir.specifics().Get(specific_id);
  720. const auto& generic = sem_ir.generics().Get(specific.generic_id);
  721. auto decl = sem_ir.insts().Get(generic.decl_id);
  722. CARBON_KIND_SWITCH(decl) {
  723. case CARBON_KIND(ClassDecl class_decl): {
  724. // Print `Core.Int(N)` as `iN`.
  725. // TODO: This duplicates work done in StringifyInst for ClassType.
  726. const auto& class_info = sem_ir.classes().Get(class_decl.class_id);
  727. if (auto type_info = RecognizedTypeInfo::ForType(
  728. sem_ir, ClassType{.type_id = TypeType::TypeId,
  729. .class_id = class_decl.class_id,
  730. .specific_id = specific_id});
  731. type_info.is_valid()) {
  732. RawStringOstream out;
  733. if (type_info.PrintLiteral(sem_ir, out)) {
  734. return out.TakeStr();
  735. }
  736. }
  737. step_stack.PushEntityName(class_info, specific_id);
  738. break;
  739. }
  740. case CARBON_KIND(FunctionDecl function_decl): {
  741. step_stack.PushEntityName(
  742. sem_ir.functions().Get(function_decl.function_id), specific_id);
  743. break;
  744. }
  745. case CARBON_KIND(ImplDecl impl_decl): {
  746. step_stack.PushEntityName(sem_ir.impls().Get(impl_decl.impl_id),
  747. specific_id);
  748. break;
  749. }
  750. case CARBON_KIND(InterfaceDecl interface_decl): {
  751. step_stack.PushEntityName(
  752. sem_ir.interfaces().Get(interface_decl.interface_id), specific_id);
  753. break;
  754. }
  755. case CARBON_KIND(InterfaceWithSelfDecl interface_with_self_decl): {
  756. step_stack.PushEntityName(
  757. sem_ir.interfaces().Get(interface_with_self_decl.interface_id),
  758. specific_id);
  759. break;
  760. }
  761. case CARBON_KIND(NamedConstraintDecl constraint_decl): {
  762. step_stack.PushEntityName(
  763. sem_ir.named_constraints().Get(constraint_decl.named_constraint_id),
  764. specific_id);
  765. break;
  766. }
  767. case CARBON_KIND(NamedConstraintWithSelfDecl constraint_with_self_decl): {
  768. step_stack.PushEntityName(
  769. sem_ir.named_constraints().Get(
  770. constraint_with_self_decl.named_constraint_id),
  771. specific_id);
  772. break;
  773. }
  774. case CARBON_KIND(RequireImplsDecl _): {
  775. step_stack.Push("require");
  776. break;
  777. }
  778. default: {
  779. // TODO: Include the specific arguments here.
  780. step_stack.PushInstId(generic.decl_id);
  781. break;
  782. }
  783. }
  784. return Stringify(sem_ir, step_stack);
  785. }
  786. auto StringifySpecificInterface(const File& sem_ir,
  787. SpecificInterface specific_interface)
  788. -> std::string {
  789. if (specific_interface.specific_id.has_value()) {
  790. return StringifySpecific(sem_ir, specific_interface.specific_id);
  791. } else {
  792. auto name_id =
  793. sem_ir.interfaces().Get(specific_interface.interface_id).name_id;
  794. return sem_ir.names().GetFormatted(name_id).str();
  795. }
  796. }
  797. auto StringifyFacetType(const File& sem_ir, FacetTypeId facet_type_id)
  798. -> std::string {
  799. StepStack step_stack(&sem_ir);
  800. step_stack.PushFacetType(facet_type_id);
  801. return Stringify(sem_ir, step_stack);
  802. }
  803. } // namespace Carbon::SemIR