stringify.cpp 26 KB

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