stringify.cpp 26 KB

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