stringify.cpp 30 KB

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