formatter.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  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/formatter.h"
  5. #include <string>
  6. #include <utility>
  7. #include "common/ostream.h"
  8. #include "llvm/ADT/Sequence.h"
  9. #include "llvm/ADT/StringExtras.h"
  10. #include "llvm/Support/SaveAndRestore.h"
  11. #include "toolchain/base/fixed_size_value_store.h"
  12. #include "toolchain/base/kind_switch.h"
  13. #include "toolchain/base/shared_value_stores.h"
  14. #include "toolchain/lex/tokenized_buffer.h"
  15. #include "toolchain/parse/tree.h"
  16. #include "toolchain/parse/tree_and_subtrees.h"
  17. #include "toolchain/sem_ir/builtin_function_kind.h"
  18. #include "toolchain/sem_ir/constant.h"
  19. #include "toolchain/sem_ir/entity_with_params_base.h"
  20. #include "toolchain/sem_ir/expr_info.h"
  21. #include "toolchain/sem_ir/formatter_chunks.h"
  22. #include "toolchain/sem_ir/function.h"
  23. #include "toolchain/sem_ir/ids.h"
  24. #include "toolchain/sem_ir/inst_categories.h"
  25. #include "toolchain/sem_ir/name_scope.h"
  26. #include "toolchain/sem_ir/typed_insts.h"
  27. #include "toolchain/sem_ir/vtable.h"
  28. // TODO: Consider addressing recursion here, although it's not critical because
  29. // the formatter isn't required to work on arbitrary code. Still, it may help
  30. // in the future to debug complex code.
  31. // NOLINTBEGIN(misc-no-recursion)
  32. namespace Carbon::SemIR {
  33. using TentativeScopeArray =
  34. std::array<std::pair<InstNamer::ScopeId, llvm::ArrayRef<InstId>>,
  35. static_cast<size_t>(InstNamer::ScopeId::FirstEntityScope) - 1>;
  36. // Returns blocks for the tentative scopes.
  37. static auto GetTentativeScopes(const SemIR::File& sem_ir)
  38. -> TentativeScopeArray {
  39. return TentativeScopeArray({
  40. {InstNamer::ScopeId::Constants, sem_ir.constants().array_ref()},
  41. {InstNamer::ScopeId::Imports,
  42. sem_ir.inst_blocks().Get(InstBlockId::Imports)},
  43. {InstNamer::ScopeId::Generated,
  44. sem_ir.inst_blocks().Get(InstBlockId::Generated)},
  45. });
  46. }
  47. Formatter::Formatter(
  48. const File* sem_ir, int total_ir_count,
  49. Parse::GetTreeAndSubtreesFn get_tree_and_subtrees,
  50. const FixedSizeValueStore<CheckIRId, bool>* include_ir_in_dumps,
  51. bool use_dump_sem_ir_ranges)
  52. : sem_ir_(sem_ir),
  53. inst_namer_(sem_ir_, total_ir_count),
  54. get_tree_and_subtrees_(get_tree_and_subtrees),
  55. include_ir_in_dumps_(include_ir_in_dumps),
  56. use_dump_sem_ir_ranges_(use_dump_sem_ir_ranges),
  57. tentative_inst_chunks_(sem_ir_->insts(), FormatterChunks::None) {
  58. if (use_dump_sem_ir_ranges_) {
  59. ComputeNodeParents();
  60. }
  61. // Reserve space for parents. There will be more content, but we don't try to
  62. // guess how much.
  63. size_t reserve_chunks = scope_label_chunks_.size();
  64. for (auto [_, insts] : GetTentativeScopes(*sem_ir_)) {
  65. reserve_chunks += insts.size();
  66. }
  67. chunks_.Reserve(reserve_chunks);
  68. // Create parent chunks for scopes.
  69. for (auto& chunk : scope_label_chunks_) {
  70. chunk = chunks_.AddParent();
  71. }
  72. // Create parent chunks for the tentative instructions.
  73. for (auto [scope_id, insts] : GetTentativeScopes(*sem_ir_)) {
  74. auto scope_chunk = scope_label_chunks_[static_cast<size_t>(scope_id)];
  75. for (auto inst_id : insts) {
  76. // Instructions are "parents" of their scopes because if any instruction
  77. // is printed, the label is also printed.
  78. tentative_inst_chunks_.Set(inst_id, chunks_.AddParent(scope_chunk));
  79. }
  80. }
  81. CARBON_CHECK(chunks_.size() == reserve_chunks);
  82. // Prepare to add content.
  83. chunks_.StartContent();
  84. }
  85. auto Formatter::Format() -> void {
  86. out() << "--- " << sem_ir_->filename() << "\n";
  87. for (auto [scope_id, insts] : GetTentativeScopes(*sem_ir_)) {
  88. FormatTopLevelScope(scope_id, insts);
  89. }
  90. FormatTopLevelScope(
  91. InstNamer::ScopeId::File,
  92. sem_ir_->inst_blocks().GetOrEmpty(sem_ir_->top_inst_block_id()));
  93. for (const auto& [id, interface] : sem_ir_->interfaces().enumerate()) {
  94. FormatInterface(id, interface);
  95. }
  96. for (const auto& [id, constraint] :
  97. sem_ir_->named_constraints().enumerate()) {
  98. FormatNamedConstraint(id, constraint);
  99. }
  100. for (const auto& [id, require] : sem_ir_->require_impls().enumerate()) {
  101. FormatRequireImpls(id, require);
  102. }
  103. for (const auto& [id, impl] : sem_ir_->impls().enumerate()) {
  104. FormatImpl(id, impl);
  105. }
  106. for (const auto& [id, class_info] : sem_ir_->classes().enumerate()) {
  107. FormatClass(id, class_info);
  108. }
  109. for (const auto& [id, vtable] : sem_ir_->vtables().enumerate()) {
  110. FormatVtable(id, vtable);
  111. }
  112. for (const auto& [id, function] : sem_ir_->functions().enumerate()) {
  113. FormatFunction(id, function);
  114. }
  115. for (const auto& [id, specific] : sem_ir_->specifics().enumerate()) {
  116. FormatSpecific(id, specific);
  117. }
  118. out() << "\n";
  119. }
  120. auto Formatter::ComputeNodeParents() -> void {
  121. CARBON_CHECK(!node_parents_);
  122. node_parents_ = NodeParentStore::MakeWithExplicitSize(
  123. sem_ir_->parse_tree().size(), Parse::NodeId::None);
  124. for (auto n : sem_ir_->parse_tree().postorder()) {
  125. for (auto child : get_tree_and_subtrees_().children(n)) {
  126. node_parents_->Set(child, n);
  127. }
  128. }
  129. }
  130. auto Formatter::Write(llvm::raw_ostream& out) -> void { chunks_.Write(out); }
  131. auto Formatter::ShouldIncludeInstByIR(InstId inst_id) -> bool {
  132. const auto* import_ir = GetCanonicalFileAndInstId(sem_ir_, inst_id).first;
  133. return include_ir_in_dumps_->Get(import_ir->check_ir_id());
  134. }
  135. // Returns true for a `DefinitionStart` node.
  136. static auto IsDefinitionStart(Parse::NodeKind node_kind) -> bool {
  137. switch (node_kind) {
  138. case Parse::NodeKind::BuiltinFunctionDefinitionStart:
  139. case Parse::NodeKind::ChoiceDefinitionStart:
  140. case Parse::NodeKind::ClassDefinitionStart:
  141. case Parse::NodeKind::FunctionDefinitionStart:
  142. case Parse::NodeKind::ImplDefinitionStart:
  143. case Parse::NodeKind::InterfaceDefinitionStart:
  144. case Parse::NodeKind::NamedConstraintDefinitionStart:
  145. return true;
  146. default:
  147. return false;
  148. }
  149. }
  150. auto Formatter::ShouldFormatEntity(InstId decl_id) -> bool {
  151. if (!decl_id.has_value()) {
  152. return true;
  153. }
  154. if (!ShouldIncludeInstByIR(decl_id)) {
  155. return false;
  156. }
  157. if (!use_dump_sem_ir_ranges_) {
  158. return true;
  159. }
  160. // When there are dump ranges, ignore imported instructions.
  161. auto loc_id = sem_ir_->insts().GetCanonicalLocId(decl_id);
  162. if (loc_id.kind() != LocId::Kind::NodeId) {
  163. return false;
  164. }
  165. const auto& tree_and_subtrees = get_tree_and_subtrees_();
  166. // This takes the earliest token from either the node or its first postorder
  167. // child. The first postorder child isn't necessarily the earliest token in
  168. // the subtree (for example, it can miss modifiers), but finding the earliest
  169. // token requires walking *all* children, whereas this approach is
  170. // constant-time.
  171. auto begin_node_id = *tree_and_subtrees.postorder(loc_id.node_id()).begin();
  172. // Non-defining declarations will be associated with a `Decl` node.
  173. // Definitions will have a `DefinitionStart` for which we can use the parent
  174. // to find the `Definition`, giving a range that includes the definition's
  175. // body.
  176. auto end_node_id = loc_id.node_id();
  177. if (IsDefinitionStart(sem_ir_->parse_tree().node_kind(end_node_id))) {
  178. end_node_id = node_parents_->Get(end_node_id);
  179. }
  180. Lex::InclusiveTokenRange range = {
  181. .begin = sem_ir_->parse_tree().node_token(begin_node_id),
  182. .end = sem_ir_->parse_tree().node_token(end_node_id)};
  183. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(range);
  184. }
  185. auto Formatter::ShouldFormatEntity(const EntityWithParamsBase& entity) -> bool {
  186. return ShouldFormatEntity(entity.latest_decl_id());
  187. }
  188. auto Formatter::ShouldFormatInst(InstId inst_id) -> bool {
  189. if (!use_dump_sem_ir_ranges_) {
  190. return true;
  191. }
  192. // When there are dump ranges, ignore imported instructions.
  193. auto loc_id = sem_ir_->insts().GetCanonicalLocId(inst_id);
  194. if (loc_id.kind() != LocId::Kind::NodeId) {
  195. return false;
  196. }
  197. auto token = sem_ir_->parse_tree().node_token(loc_id.node_id());
  198. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(
  199. Lex::InclusiveTokenRange{.begin = token, .end = token});
  200. }
  201. auto Formatter::OpenBrace() -> void {
  202. // Put the constant value of an instruction before any braced block, rather
  203. // than at the end.
  204. FormatPendingConstantValue(AddSpace::After);
  205. // Put the imported-from library name before the definition of the entity.
  206. FormatPendingImportedFrom(AddSpace::After);
  207. out() << '{';
  208. indent_ += 2;
  209. after_open_brace_ = true;
  210. }
  211. auto Formatter::CloseBrace() -> void {
  212. indent_ -= 2;
  213. if (!after_open_brace_) {
  214. Indent();
  215. }
  216. out() << '}';
  217. after_open_brace_ = false;
  218. }
  219. auto Formatter::Semicolon() -> void {
  220. FormatPendingImportedFrom(AddSpace::Before);
  221. out() << ';';
  222. }
  223. auto Formatter::Indent(int offset) -> void {
  224. if (after_open_brace_) {
  225. out() << '\n';
  226. after_open_brace_ = false;
  227. }
  228. out().indent(indent_ + offset);
  229. }
  230. auto Formatter::IndentLabel() -> void {
  231. CARBON_CHECK(indent_ >= 2);
  232. if (!after_open_brace_) {
  233. out() << '\n';
  234. }
  235. Indent(-2);
  236. }
  237. auto Formatter::FormatTopLevelScope(InstNamer::ScopeId scope_id,
  238. llvm::ArrayRef<InstId> block) -> void {
  239. if (block.empty()) {
  240. return;
  241. }
  242. llvm::SaveAndRestore scope(scope_, scope_id);
  243. auto scope_chunk = scope_label_chunks_[static_cast<size_t>(scope_id)];
  244. chunks_.FormatChildContent(scope_chunk, [&] {
  245. // Note, we don't use OpenBrace() / CloseBrace() here because we always want
  246. // a newline to avoid misformatting if the first instruction is omitted.
  247. out() << "\n" << inst_namer_.GetScopeName(scope_id) << " {\n";
  248. });
  249. indent_ += 2;
  250. for (const InstId inst_id : block) {
  251. // Format instructions when needed, but do nothing for elided entries;
  252. // unlike normal code blocks, scopes are non-sequential so skipped
  253. // instructions are assumed to be uninteresting.
  254. if (scope_id == InstNamer::ScopeId::File) {
  255. // Applies range-based filtering of instructions.
  256. if (!ShouldFormatInst(inst_id)) {
  257. continue;
  258. }
  259. FormatInst(inst_id);
  260. // Include the `file` scope label directly here.
  261. chunks_.AppendChildToCurrentParent(scope_chunk);
  262. } else {
  263. // Other scopes format each instruction in its own chunk, to support
  264. // tentative formatting.
  265. chunks_.FormatChildContent(tentative_inst_chunks_.Get(inst_id),
  266. [&] { FormatInst(inst_id); });
  267. }
  268. }
  269. indent_ -= 2;
  270. chunks_.FormatChildContent(scope_chunk, [&] { out() << "}\n"; });
  271. }
  272. auto Formatter::FormatClass(ClassId id, const Class& class_info) -> void {
  273. if (!ShouldFormatEntity(class_info)) {
  274. return;
  275. }
  276. PrepareToFormatDecl(class_info.first_owning_decl_id);
  277. FormatEntityStart("class", class_info, id);
  278. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  279. if (class_info.scope_id.has_value()) {
  280. out() << ' ';
  281. OpenBrace();
  282. FormatCodeBlock(class_info.body_block_id);
  283. Indent();
  284. out() << "complete_type_witness = ";
  285. FormatName(class_info.complete_type_witness_id);
  286. out() << "\n";
  287. if (class_info.vtable_decl_id.has_value()) {
  288. Indent();
  289. out() << "vtable_decl = ";
  290. FormatName(class_info.vtable_decl_id);
  291. out() << "\n";
  292. }
  293. FormatNameScope(class_info.scope_id, "!members:\n");
  294. CloseBrace();
  295. } else {
  296. Semicolon();
  297. }
  298. out() << '\n';
  299. FormatEntityEnd(class_info.generic_id);
  300. }
  301. auto Formatter::FormatVtable(VtableId id, const Vtable& vtable_info) -> void {
  302. out() << '\n';
  303. Indent();
  304. out() << "vtable ";
  305. FormatName(id);
  306. out() << ' ';
  307. OpenBrace();
  308. for (auto function_id :
  309. sem_ir_->inst_blocks().Get(vtable_info.virtual_functions_id)) {
  310. Indent();
  311. FormatArg(function_id);
  312. out() << '\n';
  313. }
  314. CloseBrace();
  315. out() << '\n';
  316. }
  317. auto Formatter::FormatInterface(InterfaceId id, const Interface& interface_info)
  318. -> void {
  319. if (!ShouldFormatEntity(interface_info)) {
  320. return;
  321. }
  322. PrepareToFormatDecl(interface_info.first_owning_decl_id);
  323. FormatEntityStart("interface", interface_info, id);
  324. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  325. if (interface_info.is_complete()) {
  326. out() << ' ';
  327. OpenBrace();
  328. FormatCodeBlock(interface_info.body_block_without_self_id);
  329. bool body_block_empty =
  330. sem_ir_->inst_blocks()
  331. .GetOrEmpty(interface_info.body_block_with_self_id)
  332. .empty();
  333. if (!body_block_empty) {
  334. IndentLabel();
  335. out() << "!with Self:\n";
  336. llvm::SaveAndRestore with_self_scope(
  337. scope_, inst_namer_.GetScopeFor(InstNamer::InterfaceWithSelfId{id}));
  338. FormatCodeBlock(interface_info.body_block_with_self_id);
  339. }
  340. // Always include the !members without self label because we always list the
  341. // witness in this section.
  342. IndentLabel();
  343. out() << "!members:\n";
  344. FormatNameScope(interface_info.scope_without_self_id);
  345. FormatNameScope(interface_info.scope_with_self_id);
  346. Indent();
  347. out() << "witness = ";
  348. FormatArg(interface_info.associated_entities_id);
  349. out() << "\n";
  350. FormatRequireImplsBlock(interface_info.require_impls_block_id);
  351. CloseBrace();
  352. } else {
  353. Semicolon();
  354. }
  355. out() << '\n';
  356. FormatEntityEnd(interface_info.generic_id);
  357. }
  358. auto Formatter::FormatNamedConstraint(NamedConstraintId id,
  359. const NamedConstraint& constraint_info)
  360. -> void {
  361. if (!ShouldFormatEntity(constraint_info)) {
  362. return;
  363. }
  364. PrepareToFormatDecl(constraint_info.first_owning_decl_id);
  365. FormatEntityStart("constraint", constraint_info, id);
  366. llvm::SaveAndRestore constraint_scope(scope_, inst_namer_.GetScopeFor(id));
  367. if (constraint_info.is_complete()) {
  368. out() << ' ';
  369. OpenBrace();
  370. FormatCodeBlock(constraint_info.body_block_without_self_id);
  371. bool body_block_empty =
  372. sem_ir_->inst_blocks()
  373. .GetOrEmpty(constraint_info.body_block_with_self_id)
  374. .empty();
  375. if (!body_block_empty) {
  376. IndentLabel();
  377. out() << "!with Self:\n";
  378. llvm::SaveAndRestore with_self_scope(
  379. scope_,
  380. inst_namer_.GetScopeFor(InstNamer::NamedConstraintWithSelfId{id}));
  381. FormatCodeBlock(constraint_info.body_block_with_self_id);
  382. }
  383. // Always include the !members label because we always list the witness in
  384. // this section.
  385. IndentLabel();
  386. out() << "!members:\n";
  387. FormatNameScope(constraint_info.scope_without_self_id);
  388. FormatNameScope(constraint_info.scope_with_self_id);
  389. FormatRequireImplsBlock(constraint_info.require_impls_block_id);
  390. CloseBrace();
  391. } else {
  392. Semicolon();
  393. }
  394. out() << '\n';
  395. FormatEntityEnd(constraint_info.generic_id);
  396. }
  397. auto Formatter::FormatRequireImpls(RequireImplsId /*id*/,
  398. const RequireImpls& require) -> void {
  399. if (!ShouldFormatEntity(require.decl_id)) {
  400. return;
  401. }
  402. PrepareToFormatDecl(require.decl_id);
  403. FormatGenericStart("require", require.generic_id);
  404. FormatGenericEnd();
  405. }
  406. auto Formatter::FormatImpl(ImplId id, const Impl& impl_info) -> void {
  407. if (!ShouldFormatEntity(impl_info)) {
  408. return;
  409. }
  410. PrepareToFormatDecl(impl_info.first_owning_decl_id);
  411. FormatEntityStart("impl", impl_info, id);
  412. llvm::SaveAndRestore impl_scope(scope_, inst_namer_.GetScopeFor(id));
  413. out() << ": ";
  414. FormatName(impl_info.self_id);
  415. out() << " as ";
  416. FormatName(impl_info.constraint_id);
  417. if (impl_info.is_complete()) {
  418. out() << ' ';
  419. OpenBrace();
  420. FormatCodeBlock(impl_info.body_block_id);
  421. FormatCodeBlock(impl_info.witness_block_id);
  422. // Print the !members label even if the name scope is empty because we
  423. // always list the witness in this section.
  424. IndentLabel();
  425. out() << "!members:\n";
  426. if (impl_info.scope_id.has_value()) {
  427. FormatNameScope(impl_info.scope_id);
  428. }
  429. Indent();
  430. out() << "witness = ";
  431. FormatArg(impl_info.witness_id);
  432. out() << "\n";
  433. CloseBrace();
  434. } else {
  435. Semicolon();
  436. }
  437. out() << '\n';
  438. FormatEntityEnd(impl_info.generic_id);
  439. }
  440. auto Formatter::FormatFunction(FunctionId id, const Function& fn) -> void {
  441. if (!ShouldFormatEntity(fn)) {
  442. return;
  443. }
  444. std::string function_start;
  445. switch (fn.virtual_modifier) {
  446. case FunctionFields::VirtualModifier::Virtual:
  447. function_start += "virtual ";
  448. break;
  449. case FunctionFields::VirtualModifier::Abstract:
  450. function_start += "abstract ";
  451. break;
  452. case FunctionFields::VirtualModifier::Override:
  453. function_start += "override ";
  454. break;
  455. case FunctionFields::VirtualModifier::None:
  456. break;
  457. }
  458. if (fn.is_extern) {
  459. function_start += "extern ";
  460. }
  461. function_start += "fn";
  462. PrepareToFormatDecl(fn.first_owning_decl_id);
  463. FormatEntityStart(function_start, fn, id);
  464. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  465. FormatFunctionSignature(fn.call_params_id,
  466. fn.call_param_ranges.return_begin(),
  467. fn.GetDeclaredReturnForm(*sem_ir_));
  468. if (fn.builtin_function_kind() != BuiltinFunctionKind::None) {
  469. out() << " = \""
  470. << FormatEscaped(fn.builtin_function_kind().name(),
  471. /*use_hex_escapes=*/true)
  472. << "\"";
  473. }
  474. if (fn.thunk_decl_id().has_value()) {
  475. out() << " [thunk ";
  476. FormatArg(fn.thunk_decl_id());
  477. out() << "]";
  478. }
  479. if (!fn.body_block_ids.empty()) {
  480. out() << ' ';
  481. OpenBrace();
  482. for (auto block_id : fn.body_block_ids) {
  483. IndentLabel();
  484. FormatLabel(block_id);
  485. out() << ":\n";
  486. FormatCodeBlock(block_id);
  487. }
  488. CloseBrace();
  489. } else {
  490. Semicolon();
  491. }
  492. out() << '\n';
  493. FormatEntityEnd(fn.generic_id);
  494. }
  495. auto Formatter::FormatSpecificRegion(const Generic& generic,
  496. const Specific& specific,
  497. GenericInstIndex::Region region,
  498. llvm::StringRef region_name) -> void {
  499. if (!specific.GetValueBlock(region).has_value()) {
  500. return;
  501. }
  502. if (!region_name.empty()) {
  503. IndentLabel();
  504. out() << "!" << region_name << ":\n";
  505. }
  506. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  507. sem_ir_->inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  508. sem_ir_->inst_blocks().GetOrEmpty(specific.GetValueBlock(region)))) {
  509. Indent();
  510. if (generic_inst_id) {
  511. FormatName(*generic_inst_id);
  512. } else {
  513. out() << "<missing>";
  514. }
  515. out() << " => ";
  516. if (specific_inst_id) {
  517. FormatName(*specific_inst_id);
  518. } else {
  519. out() << "<missing>";
  520. }
  521. out() << "\n";
  522. }
  523. }
  524. auto Formatter::FormatSpecific(SpecificId id, const Specific& specific)
  525. -> void {
  526. const auto& generic = sem_ir_->generics().Get(specific.generic_id);
  527. if (!ShouldFormatEntity(generic.decl_id)) {
  528. // Omit specifics if we also omitted the generic.
  529. return;
  530. }
  531. if (specific.IsUnresolved()) {
  532. // Omit specifics that were never resolved. Such specifics exist only to
  533. // track the way the arguments were spelled, and that information is
  534. // conveyed entirely by the name of the specific. These specifics may also
  535. // not be referenced by any SemIR that we format, so including them adds
  536. // clutter and possibly emits references to instructions we didn't name.
  537. return;
  538. }
  539. llvm::SaveAndRestore generic_scope(
  540. scope_, inst_namer_.GetScopeFor(specific.generic_id));
  541. out() << "\n";
  542. out() << "specific ";
  543. FormatName(id);
  544. out() << " ";
  545. OpenBrace();
  546. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Declaration,
  547. "");
  548. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Definition,
  549. "definition");
  550. CloseBrace();
  551. out() << "\n";
  552. }
  553. auto Formatter::PrepareToFormatDecl(InstId first_owning_decl_id) -> void {
  554. // If this decl was imported from a different IR, annotate the name of
  555. // that IR in the output before the `{` or `;`.
  556. if (first_owning_decl_id.has_value()) {
  557. auto import_ir_inst_id =
  558. sem_ir_->insts().GetImportSource(first_owning_decl_id);
  559. if (import_ir_inst_id.has_value()) {
  560. auto import_ir_id =
  561. sem_ir_->import_ir_insts().Get(import_ir_inst_id).ir_id();
  562. if (const auto* import_file =
  563. sem_ir_->import_irs().Get(import_ir_id).sem_ir) {
  564. pending_imported_from_ = import_file->filename();
  565. }
  566. }
  567. }
  568. }
  569. auto Formatter::FormatGenericStart(llvm::StringRef entity_kind,
  570. GenericId generic_id) -> void {
  571. const auto& generic = sem_ir_->generics().Get(generic_id);
  572. out() << "\n";
  573. Indent();
  574. out() << "generic " << entity_kind << " ";
  575. FormatName(generic_id);
  576. llvm::SaveAndRestore generic_scope(scope_,
  577. inst_namer_.GetScopeFor(generic_id));
  578. FormatParamList(generic.bindings_id);
  579. out() << " ";
  580. OpenBrace();
  581. FormatCodeBlock(generic.decl_block_id);
  582. if (generic.definition_block_id.has_value()) {
  583. IndentLabel();
  584. out() << "!definition:\n";
  585. FormatCodeBlock(generic.definition_block_id);
  586. }
  587. }
  588. auto Formatter::FormatEntityEnd(GenericId generic_id) -> void {
  589. if (generic_id.has_value()) {
  590. FormatGenericEnd();
  591. }
  592. }
  593. auto Formatter::FormatGenericEnd() -> void {
  594. CloseBrace();
  595. out() << '\n';
  596. }
  597. auto Formatter::FormatFunctionSignature(InstBlockId params_id,
  598. SemIR::CallParamIndex return_begin,
  599. InstId return_form_id) -> void {
  600. if (!params_id.has_value()) {
  601. // TODO: This happens for imported functions, for which we don't currently
  602. // import the call parameters list.
  603. return;
  604. }
  605. auto params = sem_ir_->inst_blocks().Get(params_id);
  606. out() << "(";
  607. llvm::ListSeparator sep;
  608. int i = 0;
  609. for (auto param_id : params) {
  610. if (return_begin.has_value() && i >= return_begin.index) {
  611. break;
  612. }
  613. out() << sep;
  614. if (!param_id.has_value()) {
  615. out() << "invalid";
  616. continue;
  617. }
  618. if (sem_ir_->insts().Is<OutParam>(param_id)) {
  619. out() << "<unexpected out> ";
  620. }
  621. FormatNameAndForm(param_id, sem_ir_->insts().Get(param_id));
  622. ++i;
  623. }
  624. out() << ")";
  625. if (return_form_id.has_value()) {
  626. out() << " -> ";
  627. auto return_form = sem_ir_->insts().Get(return_form_id);
  628. CARBON_KIND_SWITCH(return_form) {
  629. case CARBON_KIND(InitForm _): {
  630. out() << "out ";
  631. FormatName(params[i]);
  632. out() << ": ";
  633. FormatTypeOfInst(params[i]);
  634. ++i;
  635. break;
  636. }
  637. case CARBON_KIND(RefForm ref_form): {
  638. out() << "ref ";
  639. FormatInstAsType(ref_form.type_component_inst_id);
  640. break;
  641. }
  642. case CARBON_KIND(ValueForm val_form): {
  643. out() << "val ";
  644. FormatInstAsType(val_form.type_component_inst_id);
  645. break;
  646. }
  647. case CARBON_KIND(ErrorInst _): {
  648. FormatInstAsType(return_form_id);
  649. break;
  650. }
  651. case CARBON_KIND(SpliceInst splice): {
  652. out() << "out ";
  653. FormatName(params[i]);
  654. out() << ":? ";
  655. // A form isn't a type, but it's close enough for formatting purposes.
  656. FormatInstAsType(splice.inst_id);
  657. ++i;
  658. break;
  659. }
  660. default:
  661. CARBON_FATAL("Unexpected inst kind: {0}", return_form);
  662. }
  663. }
  664. CARBON_CHECK(i == static_cast<int>(params.size()),
  665. "`return_begin` and `return_form_id` imply different numbers of "
  666. "return params.");
  667. }
  668. auto Formatter::FormatCodeBlock(InstBlockId block_id) -> void {
  669. bool elided = false;
  670. for (const InstId inst_id : sem_ir_->inst_blocks().GetOrEmpty(block_id)) {
  671. if (ShouldFormatInst(inst_id)) {
  672. FormatInst(inst_id);
  673. elided = false;
  674. } else if (!elided) {
  675. // When formatting a block, leave a hint that instructions were elided.
  676. Indent();
  677. out() << "<elided>\n";
  678. elided = true;
  679. }
  680. }
  681. }
  682. auto Formatter::FormatTrailingBlock(InstBlockId block_id) -> void {
  683. out() << ' ';
  684. OpenBrace();
  685. FormatCodeBlock(block_id);
  686. CloseBrace();
  687. }
  688. auto Formatter::FormatNameScope(NameScopeId id, llvm::StringRef label) -> void {
  689. const auto& scope = sem_ir_->name_scopes().Get(id);
  690. if (scope.entries().empty() && scope.extended_scopes().empty() &&
  691. scope.import_ir_scopes().empty() && !scope.is_cpp_scope() &&
  692. !scope.has_error()) {
  693. // Name scope is empty.
  694. return;
  695. }
  696. if (!label.empty()) {
  697. IndentLabel();
  698. out() << label;
  699. }
  700. for (auto [name_id, result] : scope.entries()) {
  701. Indent();
  702. out() << ".";
  703. FormatName(name_id);
  704. switch (result.access_kind()) {
  705. case AccessKind::Public:
  706. break;
  707. case AccessKind::Protected:
  708. out() << " [protected]";
  709. break;
  710. case AccessKind::Private:
  711. out() << " [private]";
  712. break;
  713. }
  714. out() << " = ";
  715. if (result.is_poisoned()) {
  716. out() << "<poisoned>";
  717. } else {
  718. FormatName(result.is_found() ? result.target_inst_id() : InstId::None);
  719. }
  720. out() << "\n";
  721. }
  722. for (auto extended_scope_id : scope.extended_scopes()) {
  723. Indent();
  724. out() << "extend ";
  725. FormatName(extended_scope_id);
  726. out() << "\n";
  727. }
  728. // This is used to cluster all "Core//prelude/..." imports, but not
  729. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  730. // add or remove an unused prelude file, but is intended to still show the
  731. // existence of indirect imports.
  732. bool has_prelude_components = false;
  733. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  734. auto label = GetImportIRLabel(import_ir_id);
  735. if (label.starts_with("Core//prelude/")) {
  736. if (has_prelude_components) {
  737. // Only print the existence once.
  738. continue;
  739. } else {
  740. has_prelude_components = true;
  741. label = "Core//prelude/...";
  742. }
  743. }
  744. Indent();
  745. out() << "import " << label << "\n";
  746. }
  747. if (scope.is_cpp_scope()) {
  748. Indent();
  749. out() << "import Cpp//...\n";
  750. }
  751. if (scope.has_error()) {
  752. Indent();
  753. out() << "has_error\n";
  754. }
  755. }
  756. auto Formatter::FormatInst(InstId inst_id) -> void {
  757. if (!inst_id.has_value()) {
  758. Indent();
  759. out() << "none\n";
  760. return;
  761. }
  762. if (!in_terminator_sequence_) {
  763. Indent();
  764. }
  765. auto inst = sem_ir_->insts().GetWithAttachedType(inst_id);
  766. CARBON_KIND_SWITCH(inst) {
  767. case CARBON_KIND(Branch branch): {
  768. out() << Branch::Kind.ir_name() << " ";
  769. FormatLabel(branch.target_id);
  770. out() << "\n";
  771. in_terminator_sequence_ = false;
  772. return;
  773. }
  774. case CARBON_KIND(BranchIf branch_if): {
  775. out() << "if ";
  776. FormatName(branch_if.cond_id);
  777. out() << " " << Branch::Kind.ir_name() << " ";
  778. FormatLabel(branch_if.target_id);
  779. out() << " else ";
  780. in_terminator_sequence_ = true;
  781. return;
  782. }
  783. case CARBON_KIND(BranchWithArg branch_with_arg): {
  784. out() << BranchWithArg::Kind.ir_name() << " ";
  785. FormatLabel(branch_with_arg.target_id);
  786. out() << "(";
  787. FormatName(branch_with_arg.arg_id);
  788. out() << ")\n";
  789. in_terminator_sequence_ = false;
  790. return;
  791. }
  792. default: {
  793. FormatInstLhs(inst_id, inst);
  794. out() << inst.kind().ir_name();
  795. // Add constants for everything except `ImportRefUnloaded`.
  796. if (!inst.Is<ImportRefUnloaded>()) {
  797. pending_constant_value_ =
  798. sem_ir_->constant_values().GetAttached(inst_id);
  799. pending_constant_value_is_self_ =
  800. sem_ir_->constant_values().GetInstIdIfValid(
  801. pending_constant_value_) == inst_id;
  802. }
  803. FormatInstRhs(inst);
  804. // This usually prints the constant, but when `FormatInstRhs` prints it
  805. // first (or for `ImportRefUnloaded`), this does nothing.
  806. FormatPendingConstantValue(AddSpace::Before);
  807. out() << "\n";
  808. return;
  809. }
  810. }
  811. }
  812. auto Formatter::FormatPendingImportedFrom(AddSpace space_where) -> void {
  813. if (pending_imported_from_.empty()) {
  814. return;
  815. }
  816. if (space_where == AddSpace::Before) {
  817. out() << ' ';
  818. }
  819. out() << "[from \"" << FormatEscaped(pending_imported_from_) << "\"]";
  820. if (space_where == AddSpace::After) {
  821. out() << ' ';
  822. }
  823. pending_imported_from_ = llvm::StringRef();
  824. }
  825. auto Formatter::FormatPendingConstantValue(AddSpace space_where) -> void {
  826. if (pending_constant_value_ == ConstantId::NotConstant) {
  827. return;
  828. }
  829. if (space_where == AddSpace::Before) {
  830. out() << ' ';
  831. }
  832. out() << '[';
  833. if (pending_constant_value_.has_value()) {
  834. switch (sem_ir_->constant_values().GetDependence(pending_constant_value_)) {
  835. case ConstantDependence::None:
  836. out() << "concrete";
  837. break;
  838. case ConstantDependence::PeriodSelf:
  839. out() << "symbolic_self";
  840. break;
  841. // TODO: Consider renaming this. This will cause a lot of SemIR churn.
  842. case ConstantDependence::Checked:
  843. out() << "symbolic";
  844. break;
  845. case ConstantDependence::Template:
  846. out() << "template";
  847. break;
  848. }
  849. if (!pending_constant_value_is_self_) {
  850. out() << " = ";
  851. FormatConstant(pending_constant_value_);
  852. }
  853. } else {
  854. out() << pending_constant_value_;
  855. }
  856. out() << ']';
  857. if (space_where == AddSpace::After) {
  858. out() << ' ';
  859. }
  860. pending_constant_value_ = ConstantId::NotConstant;
  861. }
  862. auto Formatter::FormatInstLhs(InstId inst_id, Inst inst) -> void {
  863. // Every typed instruction is named, and there are some untyped instructions
  864. // that have names (such as `ImportRefUnloaded`). When there's a typed
  865. // instruction with no name, it means an instruction is incorrectly not named
  866. // -- but should be printed as such.
  867. bool has_name = inst_namer_.has_name(inst_id);
  868. if (!has_name && !inst.kind().has_type()) {
  869. return;
  870. }
  871. FormatNameAndForm(inst_id, inst);
  872. out() << " = ";
  873. }
  874. auto Formatter::FormatNameAndForm(InstId inst_id, Inst inst) -> void {
  875. FormatName(inst_id);
  876. if (inst.kind().has_type()) {
  877. out() << ": ";
  878. switch (GetExprCategory(*sem_ir_, inst_id)) {
  879. case ExprCategory::NotExpr:
  880. case ExprCategory::Error:
  881. case ExprCategory::Value:
  882. case ExprCategory::Pattern:
  883. case ExprCategory::Mixed:
  884. case ExprCategory::RefTagged:
  885. case ExprCategory::Dependent:
  886. FormatTypeOfInst(inst_id);
  887. break;
  888. case ExprCategory::DurableRef:
  889. case ExprCategory::EphemeralRef:
  890. out() << "ref ";
  891. FormatTypeOfInst(inst_id);
  892. break;
  893. case ExprCategory::InPlaceInitializing:
  894. case ExprCategory::ReprInitializing: {
  895. out() << "init ";
  896. FormatTypeOfInst(inst_id);
  897. auto init_target_id = FindStorageArgForInitializer(
  898. *sem_ir_, inst_id, /*allow_transitive=*/false);
  899. FormatReturnSlotArg(init_target_id);
  900. break;
  901. }
  902. }
  903. }
  904. }
  905. auto Formatter::FormatInstArgAndKind(Inst::ArgAndKind arg_and_kind) -> void {
  906. GetFormatArgFn(arg_and_kind.kind())(*this, arg_and_kind.value());
  907. }
  908. auto Formatter::FormatInstRhs(Inst inst) -> void {
  909. CARBON_KIND_SWITCH(inst) {
  910. case CARBON_KIND_ANY(AnyAggregateInit, init): {
  911. FormatArgs(init.elements_id);
  912. return;
  913. }
  914. case CARBON_KIND_ANY(AnyImportRef, import_ref): {
  915. FormatImportRefRhs(import_ref);
  916. return;
  917. }
  918. case CARBON_KIND_ANY(AnyParam, param): {
  919. FormatArgs(param.index);
  920. // Omit pretty_name because it's an implementation detail of
  921. // pretty-printing.
  922. return;
  923. }
  924. case CARBON_KIND_ANY(AnyLeafParamPattern, _): {
  925. // Omit pretty_name because it's an implementation detail of
  926. // pretty-printing.
  927. return;
  928. }
  929. case CARBON_KIND(VarParamPattern param): {
  930. FormatArgs(param.subpattern_id);
  931. // Omit pretty_name because it's an implementation detail of
  932. // pretty-printing.
  933. return;
  934. }
  935. case CARBON_KIND(AssociatedConstantDecl decl): {
  936. FormatArgs(decl.assoc_const_id);
  937. llvm::SaveAndRestore scope(scope_,
  938. inst_namer_.GetScopeFor(decl.assoc_const_id));
  939. FormatTrailingBlock(decl.decl_block_id);
  940. return;
  941. }
  942. case CARBON_KIND(SymbolicBinding bind): {
  943. // A SymbolicBinding with no value is a purely symbolic binding, such as
  944. // the `Self` in an interface. Don't print out `none` for the value.
  945. if (bind.value_id.has_value()) {
  946. FormatArgs(bind.entity_name_id, bind.value_id);
  947. } else {
  948. FormatArgs(bind.entity_name_id);
  949. }
  950. return;
  951. }
  952. case CARBON_KIND(BlockArg block): {
  953. out() << " ";
  954. FormatLabel(block.block_id);
  955. return;
  956. }
  957. case CARBON_KIND(Call call): {
  958. FormatCallRhs(call);
  959. return;
  960. }
  961. case CARBON_KIND(ClassDecl decl): {
  962. FormatDeclRhs(decl.class_id,
  963. sem_ir_->classes().Get(decl.class_id).pattern_block_id,
  964. decl.decl_block_id);
  965. return;
  966. }
  967. case CARBON_KIND(CppTemplateNameType type): {
  968. // Omit the Clang declaration. We don't have a good way to format it, and
  969. // the entity name should suffice to identify the template.
  970. FormatArgs(type.name_id);
  971. return;
  972. }
  973. case CARBON_KIND(CustomLayoutType type): {
  974. out() << " {";
  975. auto layout = sem_ir_->custom_layouts().Get(type.layout_id);
  976. out() << "size=" << layout[CustomLayoutId::SizeIndex]
  977. << ", align=" << layout[CustomLayoutId::AlignIndex];
  978. for (auto [field, offset] : llvm::zip_equal(
  979. sem_ir_->struct_type_fields().Get(type.fields_id),
  980. layout.drop_front(CustomLayoutId::FirstFieldIndex))) {
  981. out() << ", .";
  982. FormatName(field.name_id);
  983. out() << "@" << offset << ": ";
  984. FormatInstAsType(field.type_inst_id);
  985. }
  986. out() << "}";
  987. return;
  988. }
  989. case CARBON_KIND(FloatValue value): {
  990. llvm::SmallVector<char, 16> buffer;
  991. sem_ir_->floats().Get(value.float_id).toString(buffer);
  992. out() << " " << buffer;
  993. return;
  994. }
  995. case CARBON_KIND(FunctionDecl decl): {
  996. FormatDeclRhs(decl.function_id,
  997. sem_ir_->functions().Get(decl.function_id).pattern_block_id,
  998. decl.decl_block_id);
  999. return;
  1000. }
  1001. case ImportCppDecl::Kind: {
  1002. FormatImportCppDeclRhs();
  1003. return;
  1004. }
  1005. case CARBON_KIND(ImplDecl decl): {
  1006. FormatDeclRhs(decl.impl_id,
  1007. sem_ir_->impls().Get(decl.impl_id).pattern_block_id,
  1008. decl.decl_block_id);
  1009. return;
  1010. }
  1011. case CARBON_KIND(InPlaceInit init): {
  1012. FormatArgs(init.src_id);
  1013. return;
  1014. }
  1015. case CARBON_KIND(InstValue inst): {
  1016. out() << ' ';
  1017. OpenBrace();
  1018. // TODO: Should we use a more compact representation in the case where the
  1019. // inst is a SpliceBlock?
  1020. FormatInst(inst.inst_id);
  1021. CloseBrace();
  1022. return;
  1023. }
  1024. case CARBON_KIND(InterfaceDecl decl): {
  1025. FormatDeclRhs(
  1026. decl.interface_id,
  1027. sem_ir_->interfaces().Get(decl.interface_id).pattern_block_id,
  1028. decl.decl_block_id);
  1029. return;
  1030. }
  1031. case CARBON_KIND(IntValue value): {
  1032. out() << " ";
  1033. sem_ir_->ints()
  1034. .Get(value.int_id)
  1035. .print(out(), sem_ir_->types().IsSignedInt(value.type_id));
  1036. return;
  1037. }
  1038. case CARBON_KIND(NameBindingDecl name): {
  1039. FormatTrailingBlock(name.pattern_block_id);
  1040. return;
  1041. }
  1042. case CARBON_KIND(NamedConstraintDecl decl): {
  1043. FormatDeclRhs(decl.named_constraint_id,
  1044. sem_ir_->named_constraints()
  1045. .Get(decl.named_constraint_id)
  1046. .pattern_block_id,
  1047. decl.decl_block_id);
  1048. return;
  1049. }
  1050. case CARBON_KIND(Namespace ns): {
  1051. if (ns.import_id.has_value()) {
  1052. FormatArgs(ns.import_id, ns.name_scope_id);
  1053. } else {
  1054. FormatArgs(ns.name_scope_id);
  1055. }
  1056. return;
  1057. }
  1058. case CARBON_KIND(RequireImplsDecl decl): {
  1059. FormatArgs(decl.require_impls_id);
  1060. llvm::SaveAndRestore scope(
  1061. scope_, inst_namer_.GetScopeFor(decl.require_impls_id));
  1062. FormatRequireImpls(decl.require_impls_id);
  1063. FormatTrailingBlock(decl.decl_block_id);
  1064. return;
  1065. }
  1066. case CARBON_KIND(ReturnExpr ret): {
  1067. FormatArgs(ret.expr_id);
  1068. if (ret.dest_id.has_value()) {
  1069. FormatReturnSlotArg(ret.dest_id);
  1070. }
  1071. return;
  1072. }
  1073. case CARBON_KIND(ReturnSlot ret): {
  1074. // Omit inst.type_inst_id because it's not semantically significant.
  1075. FormatArgs(ret.storage_id);
  1076. return;
  1077. }
  1078. case CARBON_KIND(SpliceBlock splice): {
  1079. FormatArgs(splice.result_id);
  1080. FormatTrailingBlock(splice.block_id);
  1081. return;
  1082. }
  1083. case CARBON_KIND(StructType struct_type): {
  1084. out() << " {";
  1085. llvm::ListSeparator sep;
  1086. for (auto field :
  1087. sem_ir_->struct_type_fields().Get(struct_type.fields_id)) {
  1088. out() << sep << ".";
  1089. FormatName(field.name_id);
  1090. out() << ": ";
  1091. FormatInstAsType(field.type_inst_id);
  1092. }
  1093. out() << "}";
  1094. return;
  1095. }
  1096. case CARBON_KIND(WhereExpr where): {
  1097. FormatTrailingBlock(where.requirements_id);
  1098. return;
  1099. }
  1100. default:
  1101. FormatInstRhsDefault(inst);
  1102. return;
  1103. }
  1104. }
  1105. auto Formatter::FormatInstRhsDefault(Inst inst) -> void {
  1106. auto arg0 = inst.arg0_and_kind();
  1107. if (arg0.kind() == IdKind::None) {
  1108. return;
  1109. }
  1110. out() << " ";
  1111. FormatInstArgAndKind(arg0);
  1112. auto arg1 = inst.arg1_and_kind();
  1113. if (arg1.kind() == IdKind::None) {
  1114. return;
  1115. }
  1116. // Several instructions have a second operand that's a specific ID. We
  1117. // don't include it in the argument list if there is no corresponding
  1118. // specific, that is, when we're not in a generic context.
  1119. if (auto arg1_specific_id = arg1.TryAs<SpecificId>();
  1120. arg1_specific_id && !arg1_specific_id->has_value()) {
  1121. return;
  1122. }
  1123. // Similarly, instructions that have a `DestInstId` as the second operand
  1124. // typically use it for the output argument, so we omit it because it should
  1125. // already be part of the inst's formatted form expression.
  1126. if (arg1.kind() == IdKind::For<DestInstId>) {
  1127. return;
  1128. }
  1129. out() << ", ";
  1130. FormatInstArgAndKind(arg1);
  1131. }
  1132. auto Formatter::FormatCallRhs(Call inst) -> void {
  1133. out() << " ";
  1134. FormatArg(inst.callee_id);
  1135. if (!inst.args_id.has_value()) {
  1136. out() << "(<none>)";
  1137. return;
  1138. }
  1139. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  1140. // If there are return arguments, don't print them here, because it's printed
  1141. // on the LHS.
  1142. auto explicit_end = SemIR::CallParamIndex::None;
  1143. auto callee = GetCallee(*sem_ir_, inst.callee_id);
  1144. if (auto* callee_function = std::get_if<CalleeFunction>(&callee)) {
  1145. explicit_end = sem_ir_->functions()
  1146. .Get(callee_function->function_id)
  1147. .call_param_ranges.explicit_end();
  1148. }
  1149. llvm::ListSeparator sep;
  1150. out() << '(';
  1151. for (auto [i, inst_id] : llvm::enumerate(args)) {
  1152. if (explicit_end.has_value() && static_cast<int>(i) >= explicit_end.index) {
  1153. break;
  1154. }
  1155. out() << sep;
  1156. FormatArg(inst_id);
  1157. }
  1158. out() << ')';
  1159. }
  1160. auto Formatter::FormatImportCppDeclRhs() -> void {
  1161. out() << " ";
  1162. OpenBrace();
  1163. for (const Parse::Tree::PackagingNames& import :
  1164. sem_ir_->parse_tree().imports()) {
  1165. if (import.package_id != PackageNameId::Cpp) {
  1166. continue;
  1167. }
  1168. Indent();
  1169. out() << "import Cpp";
  1170. if (import.library_id.has_value()) {
  1171. out() << " \""
  1172. << FormatEscaped(
  1173. sem_ir_->string_literal_values().Get(import.library_id))
  1174. << "\"";
  1175. } else if (import.inline_body_id.has_value()) {
  1176. out() << " inline";
  1177. }
  1178. out() << "\n";
  1179. }
  1180. CloseBrace();
  1181. }
  1182. auto Formatter::FormatImportRefRhs(AnyImportRef inst) -> void {
  1183. out() << " ";
  1184. auto import_ir_inst = sem_ir_->import_ir_insts().Get(inst.import_ir_inst_id);
  1185. FormatArg(import_ir_inst.ir_id());
  1186. out() << ", ";
  1187. if (inst.entity_name_id.has_value()) {
  1188. // Prefer to show the entity name when possible.
  1189. FormatArg(inst.entity_name_id);
  1190. } else {
  1191. // Show a name based on the location when possible, or the numeric
  1192. // instruction as a last resort.
  1193. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  1194. auto loc_id =
  1195. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  1196. switch (loc_id.kind()) {
  1197. case LocId::Kind::None: {
  1198. out() << import_ir_inst.inst_id() << " [no loc]";
  1199. break;
  1200. }
  1201. case LocId::Kind::ImportIRInstId: {
  1202. // TODO: Probably don't want to format each indirection, but maybe
  1203. // reuse GetCanonicalImportIRInst?
  1204. out() << import_ir_inst.inst_id() << " [indirect]";
  1205. break;
  1206. }
  1207. case LocId::Kind::NodeId: {
  1208. // Formats a NodeId from the import.
  1209. const auto& tree = import_ir.sem_ir->parse_tree();
  1210. auto token = tree.node_token(loc_id.node_id());
  1211. out() << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1212. << tree.tokens().GetColumnNumber(token);
  1213. break;
  1214. }
  1215. case LocId::Kind::InstId:
  1216. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1217. }
  1218. }
  1219. out() << ", "
  1220. << (inst.kind == InstKind::ImportRefLoaded ? "loaded" : "unloaded");
  1221. }
  1222. auto Formatter::FormatRequireImpls(RequireImplsId id) -> void {
  1223. out() << ' ';
  1224. const auto& require = sem_ir_->require_impls().Get(id);
  1225. OpenBrace();
  1226. Indent();
  1227. out() << "require ";
  1228. FormatArg(require.self_id);
  1229. out() << " impls ";
  1230. FormatArg(require.facet_type_inst_id);
  1231. out() << "\n";
  1232. CloseBrace();
  1233. }
  1234. auto Formatter::FormatRequireImplsBlock(RequireImplsBlockId block_id) -> void {
  1235. IndentLabel();
  1236. out() << "!requires:\n";
  1237. if (!block_id.has_value()) {
  1238. return;
  1239. }
  1240. for (auto require_impls_id : sem_ir_->require_impls_blocks().Get(block_id)) {
  1241. Indent();
  1242. FormatArg(require_impls_id);
  1243. FormatRequireImpls(require_impls_id);
  1244. out() << "\n";
  1245. }
  1246. }
  1247. auto Formatter::FormatArg(EntityNameId id) -> void {
  1248. if (!id.has_value()) {
  1249. out() << "_";
  1250. return;
  1251. }
  1252. const auto& info = sem_ir_->entity_names().Get(id);
  1253. FormatName(info.name_id);
  1254. if (info.bind_index().has_value()) {
  1255. out() << ", " << info.bind_index().index;
  1256. }
  1257. if (info.is_template) {
  1258. out() << ", template";
  1259. }
  1260. }
  1261. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1262. const auto& info = sem_ir_->facet_types().Get(id);
  1263. // Nothing output to indicate that this is a facet type since this is only
  1264. // used as the argument to a `facet_type` instruction.
  1265. out() << "<";
  1266. auto format_specific = [&](SemIR::SpecificId specific_id) {
  1267. if (specific_id.has_value()) {
  1268. out() << ", ";
  1269. FormatName(specific_id);
  1270. }
  1271. };
  1272. llvm::ListSeparator sep(" & ");
  1273. if (info.extend_constraints.empty() &&
  1274. info.extend_named_constraints.empty()) {
  1275. out() << "type";
  1276. } else {
  1277. for (auto extend : info.extend_constraints) {
  1278. out() << sep;
  1279. FormatName(extend.interface_id);
  1280. format_specific(extend.specific_id);
  1281. }
  1282. for (auto extend : info.extend_named_constraints) {
  1283. out() << sep;
  1284. FormatName(extend.named_constraint_id);
  1285. format_specific(extend.specific_id);
  1286. }
  1287. }
  1288. if (info.other_requirements || !info.self_impls_constraints.empty() ||
  1289. !info.type_impls_interfaces.empty() ||
  1290. !info.type_impls_named_constraints.empty() ||
  1291. !info.rewrite_constraints.empty()) {
  1292. out() << " where ";
  1293. llvm::ListSeparator and_sep(" and ");
  1294. int num_self_impls = info.self_impls_constraints.size() +
  1295. info.self_impls_named_constraints.size();
  1296. if (num_self_impls > 0) {
  1297. out() << and_sep << ".Self impls ";
  1298. llvm::ListSeparator amp_sep(" & ");
  1299. if (num_self_impls > 1) {
  1300. out() << "(";
  1301. }
  1302. for (auto self_impls : info.self_impls_constraints) {
  1303. out() << amp_sep;
  1304. FormatName(self_impls.interface_id);
  1305. format_specific(self_impls.specific_id);
  1306. }
  1307. for (auto self_impls : info.self_impls_named_constraints) {
  1308. out() << amp_sep;
  1309. FormatName(self_impls.named_constraint_id);
  1310. format_specific(self_impls.specific_id);
  1311. }
  1312. if (num_self_impls > 1) {
  1313. out() << ")";
  1314. }
  1315. }
  1316. for (const auto& type_impls : info.type_impls_interfaces) {
  1317. out() << and_sep;
  1318. FormatName(type_impls.self_type);
  1319. out() << " impls ";
  1320. FormatName(type_impls.specific_interface.interface_id);
  1321. format_specific(type_impls.specific_interface.specific_id);
  1322. }
  1323. for (const auto& type_impls : info.type_impls_named_constraints) {
  1324. out() << and_sep;
  1325. FormatName(type_impls.self_type);
  1326. out() << " impls ";
  1327. FormatName(type_impls.specific_named_constraint.named_constraint_id);
  1328. format_specific(type_impls.specific_named_constraint.specific_id);
  1329. }
  1330. for (auto rewrite : info.rewrite_constraints) {
  1331. out() << and_sep;
  1332. FormatArg(rewrite.lhs_id);
  1333. out() << " = ";
  1334. FormatArg(rewrite.rhs_id);
  1335. }
  1336. if (info.other_requirements) {
  1337. out() << and_sep << "TODO";
  1338. }
  1339. }
  1340. out() << ">";
  1341. }
  1342. auto Formatter::FormatArg(ImportIRId id) -> void {
  1343. if (id.has_value()) {
  1344. out() << GetImportIRLabel(id);
  1345. } else {
  1346. out() << id;
  1347. }
  1348. }
  1349. auto Formatter::FormatArg(IntId id) -> void {
  1350. // We don't know the signedness to use here. Default to unsigned.
  1351. sem_ir_->ints().Get(id).print(out(), /*isSigned=*/false);
  1352. }
  1353. auto Formatter::FormatArg(NameScopeId id) -> void {
  1354. OpenBrace();
  1355. FormatNameScope(id);
  1356. CloseBrace();
  1357. }
  1358. auto Formatter::FormatArg(InstBlockId id) -> void {
  1359. if (!id.has_value()) {
  1360. out() << "invalid";
  1361. return;
  1362. }
  1363. out() << '(';
  1364. llvm::ListSeparator sep;
  1365. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1366. out() << sep;
  1367. FormatArg(inst_id);
  1368. }
  1369. out() << ')';
  1370. }
  1371. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1372. FormatArg(static_cast<InstBlockId>(id));
  1373. }
  1374. auto Formatter::FormatArg(ExprRegionId id) -> void {
  1375. const auto& region = sem_ir_->expr_regions().Get(id);
  1376. FormatArg(region.result_id);
  1377. out() << " in ";
  1378. OpenBrace();
  1379. for (auto [i, block_id] : llvm::enumerate(region.block_ids)) {
  1380. if (i != 0) {
  1381. IndentLabel();
  1382. FormatLabel(block_id);
  1383. out() << ":\n";
  1384. }
  1385. FormatCodeBlock(block_id);
  1386. }
  1387. CloseBrace();
  1388. }
  1389. auto Formatter::FormatArg(RealId id) -> void {
  1390. // TODO: Format with a `.` when the exponent is near zero.
  1391. const auto& real = sem_ir_->reals().Get(id);
  1392. real.mantissa.print(out(), /*isSigned=*/false);
  1393. out() << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1394. }
  1395. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1396. out() << '"'
  1397. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1398. /*use_hex_escapes=*/true)
  1399. << '"';
  1400. }
  1401. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1402. if (dest_id.has_value()) {
  1403. out() << " to ";
  1404. FormatArg(dest_id);
  1405. }
  1406. }
  1407. auto Formatter::FormatName(NameId id) -> void {
  1408. out() << sem_ir_->names().GetFormatted(id);
  1409. }
  1410. auto Formatter::FormatName(InstId id) -> void {
  1411. if (id.has_value()) {
  1412. if (auto chunk = tentative_inst_chunks_.Get(id);
  1413. chunk != FormatterChunks::None) {
  1414. chunks_.AppendChildToCurrentParent(chunk);
  1415. }
  1416. }
  1417. out() << inst_namer_.GetNameFor(scope_, id);
  1418. }
  1419. auto Formatter::FormatName(SpecificId id) -> void {
  1420. const auto& specific = sem_ir_->specifics().Get(id);
  1421. FormatName(specific.generic_id);
  1422. FormatArg(specific.args_id);
  1423. }
  1424. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1425. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1426. FormatName(interface.interface_id);
  1427. if (interface.specific_id.has_value()) {
  1428. out() << ", ";
  1429. FormatArg(interface.specific_id);
  1430. }
  1431. }
  1432. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1433. out() << inst_namer_.GetLabelFor(scope_, id);
  1434. }
  1435. auto Formatter::FormatConstant(ConstantId id) -> void {
  1436. if (!id.has_value()) {
  1437. out() << "<not constant>";
  1438. return;
  1439. }
  1440. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1441. FormatName(inst_id);
  1442. // For an attached constant, also list the unattached constant.
  1443. if (id.is_symbolic() && sem_ir_->constant_values()
  1444. .GetSymbolicConstant(id)
  1445. .generic_id.has_value()) {
  1446. // TODO: Skip printing this if it's the same as `inst_id`.
  1447. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1448. out() << " (";
  1449. FormatName(unattached_inst_id);
  1450. out() << ")";
  1451. }
  1452. }
  1453. auto Formatter::FormatInstAsType(InstId id) -> void {
  1454. if (!id.has_value()) {
  1455. out() << "invalid";
  1456. return;
  1457. }
  1458. // Types are formatted in the `constants` scope because they typically refer
  1459. // to constants.
  1460. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1461. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1462. const_id.has_value()) {
  1463. FormatConstant(const_id);
  1464. } else {
  1465. // Type instruction didn't have a constant value. Fall back to printing
  1466. // the instruction name.
  1467. FormatArg(id);
  1468. }
  1469. }
  1470. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1471. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1472. if (!type_id.has_value()) {
  1473. out() << "invalid";
  1474. return;
  1475. }
  1476. // Types are formatted in the `constants` scope because they typically refer
  1477. // to constants.
  1478. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1479. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1480. }
  1481. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1482. CARBON_CHECK(id.has_value(),
  1483. "Callers are responsible for checking `id.has_value`");
  1484. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1485. CARBON_CHECK(import_ir.library_id().has_value());
  1486. auto package_id = import_ir.package_id();
  1487. llvm::StringRef package_name =
  1488. package_id.AsIdentifierId().has_value()
  1489. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1490. : package_id.AsSpecialName();
  1491. llvm::StringRef library_name =
  1492. (import_ir.library_id() != LibraryNameId::Default)
  1493. ? import_ir.string_literal_values().Get(
  1494. import_ir.library_id().AsStringLiteralValueId())
  1495. : "default";
  1496. return llvm::formatv("{0}//{1}", package_name, library_name);
  1497. }
  1498. } // namespace Carbon::SemIR
  1499. // NOLINTEND(misc-no-recursion)