stringify.cpp 33 KB

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