formatter.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700
  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. default:
  652. CARBON_FATAL("Unexpected inst kind: {0}", return_form);
  653. }
  654. }
  655. CARBON_CHECK(i == static_cast<int>(params.size()),
  656. "`return_begin` and `return_form_id` imply different numbers of "
  657. "return params.");
  658. }
  659. auto Formatter::FormatCodeBlock(InstBlockId block_id) -> void {
  660. bool elided = false;
  661. for (const InstId inst_id : sem_ir_->inst_blocks().GetOrEmpty(block_id)) {
  662. if (ShouldFormatInst(inst_id)) {
  663. FormatInst(inst_id);
  664. elided = false;
  665. } else if (!elided) {
  666. // When formatting a block, leave a hint that instructions were elided.
  667. Indent();
  668. out() << "<elided>\n";
  669. elided = true;
  670. }
  671. }
  672. }
  673. auto Formatter::FormatTrailingBlock(InstBlockId block_id) -> void {
  674. out() << ' ';
  675. OpenBrace();
  676. FormatCodeBlock(block_id);
  677. CloseBrace();
  678. }
  679. auto Formatter::FormatNameScope(NameScopeId id, llvm::StringRef label) -> void {
  680. const auto& scope = sem_ir_->name_scopes().Get(id);
  681. if (scope.entries().empty() && scope.extended_scopes().empty() &&
  682. scope.import_ir_scopes().empty() && !scope.is_cpp_scope() &&
  683. !scope.has_error()) {
  684. // Name scope is empty.
  685. return;
  686. }
  687. if (!label.empty()) {
  688. IndentLabel();
  689. out() << label;
  690. }
  691. for (auto [name_id, result] : scope.entries()) {
  692. Indent();
  693. out() << ".";
  694. FormatName(name_id);
  695. switch (result.access_kind()) {
  696. case AccessKind::Public:
  697. break;
  698. case AccessKind::Protected:
  699. out() << " [protected]";
  700. break;
  701. case AccessKind::Private:
  702. out() << " [private]";
  703. break;
  704. }
  705. out() << " = ";
  706. if (result.is_poisoned()) {
  707. out() << "<poisoned>";
  708. } else {
  709. FormatName(result.is_found() ? result.target_inst_id() : InstId::None);
  710. }
  711. out() << "\n";
  712. }
  713. for (auto extended_scope_id : scope.extended_scopes()) {
  714. Indent();
  715. out() << "extend ";
  716. FormatName(extended_scope_id);
  717. out() << "\n";
  718. }
  719. // This is used to cluster all "Core//prelude/..." imports, but not
  720. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  721. // add or remove an unused prelude file, but is intended to still show the
  722. // existence of indirect imports.
  723. bool has_prelude_components = false;
  724. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  725. auto label = GetImportIRLabel(import_ir_id);
  726. if (label.starts_with("Core//prelude/")) {
  727. if (has_prelude_components) {
  728. // Only print the existence once.
  729. continue;
  730. } else {
  731. has_prelude_components = true;
  732. label = "Core//prelude/...";
  733. }
  734. }
  735. Indent();
  736. out() << "import " << label << "\n";
  737. }
  738. if (scope.is_cpp_scope()) {
  739. Indent();
  740. out() << "import Cpp//...\n";
  741. }
  742. if (scope.has_error()) {
  743. Indent();
  744. out() << "has_error\n";
  745. }
  746. }
  747. auto Formatter::FormatInst(InstId inst_id) -> void {
  748. if (!inst_id.has_value()) {
  749. Indent();
  750. out() << "none\n";
  751. return;
  752. }
  753. if (!in_terminator_sequence_) {
  754. Indent();
  755. }
  756. auto inst = sem_ir_->insts().GetWithAttachedType(inst_id);
  757. CARBON_KIND_SWITCH(inst) {
  758. case CARBON_KIND(Branch branch): {
  759. out() << Branch::Kind.ir_name() << " ";
  760. FormatLabel(branch.target_id);
  761. out() << "\n";
  762. in_terminator_sequence_ = false;
  763. return;
  764. }
  765. case CARBON_KIND(BranchIf branch_if): {
  766. out() << "if ";
  767. FormatName(branch_if.cond_id);
  768. out() << " " << Branch::Kind.ir_name() << " ";
  769. FormatLabel(branch_if.target_id);
  770. out() << " else ";
  771. in_terminator_sequence_ = true;
  772. return;
  773. }
  774. case CARBON_KIND(BranchWithArg branch_with_arg): {
  775. out() << BranchWithArg::Kind.ir_name() << " ";
  776. FormatLabel(branch_with_arg.target_id);
  777. out() << "(";
  778. FormatName(branch_with_arg.arg_id);
  779. out() << ")\n";
  780. in_terminator_sequence_ = false;
  781. return;
  782. }
  783. default: {
  784. FormatInstLhs(inst_id, inst);
  785. out() << inst.kind().ir_name();
  786. // Add constants for everything except `ImportRefUnloaded`.
  787. if (!inst.Is<ImportRefUnloaded>()) {
  788. pending_constant_value_ =
  789. sem_ir_->constant_values().GetAttached(inst_id);
  790. pending_constant_value_is_self_ =
  791. sem_ir_->constant_values().GetInstIdIfValid(
  792. pending_constant_value_) == inst_id;
  793. }
  794. FormatInstRhs(inst);
  795. // This usually prints the constant, but when `FormatInstRhs` prints it
  796. // first (or for `ImportRefUnloaded`), this does nothing.
  797. FormatPendingConstantValue(AddSpace::Before);
  798. out() << "\n";
  799. return;
  800. }
  801. }
  802. }
  803. auto Formatter::FormatPendingImportedFrom(AddSpace space_where) -> void {
  804. if (pending_imported_from_.empty()) {
  805. return;
  806. }
  807. if (space_where == AddSpace::Before) {
  808. out() << ' ';
  809. }
  810. out() << "[from \"" << FormatEscaped(pending_imported_from_) << "\"]";
  811. if (space_where == AddSpace::After) {
  812. out() << ' ';
  813. }
  814. pending_imported_from_ = llvm::StringRef();
  815. }
  816. auto Formatter::FormatPendingConstantValue(AddSpace space_where) -> void {
  817. if (pending_constant_value_ == ConstantId::NotConstant) {
  818. return;
  819. }
  820. if (space_where == AddSpace::Before) {
  821. out() << ' ';
  822. }
  823. out() << '[';
  824. if (pending_constant_value_.has_value()) {
  825. switch (sem_ir_->constant_values().GetDependence(pending_constant_value_)) {
  826. case ConstantDependence::None:
  827. out() << "concrete";
  828. break;
  829. case ConstantDependence::PeriodSelf:
  830. out() << "symbolic_self";
  831. break;
  832. // TODO: Consider renaming this. This will cause a lot of SemIR churn.
  833. case ConstantDependence::Checked:
  834. out() << "symbolic";
  835. break;
  836. case ConstantDependence::Template:
  837. out() << "template";
  838. break;
  839. }
  840. if (!pending_constant_value_is_self_) {
  841. out() << " = ";
  842. FormatConstant(pending_constant_value_);
  843. }
  844. } else {
  845. out() << pending_constant_value_;
  846. }
  847. out() << ']';
  848. if (space_where == AddSpace::After) {
  849. out() << ' ';
  850. }
  851. pending_constant_value_ = ConstantId::NotConstant;
  852. }
  853. auto Formatter::FormatInstLhs(InstId inst_id, Inst inst) -> void {
  854. // Every typed instruction is named, and there are some untyped instructions
  855. // that have names (such as `ImportRefUnloaded`). When there's a typed
  856. // instruction with no name, it means an instruction is incorrectly not named
  857. // -- but should be printed as such.
  858. bool has_name = inst_namer_.has_name(inst_id);
  859. if (!has_name && !inst.kind().has_type()) {
  860. return;
  861. }
  862. FormatNameAndForm(inst_id, inst);
  863. out() << " = ";
  864. }
  865. auto Formatter::FormatNameAndForm(InstId inst_id, Inst inst) -> void {
  866. FormatName(inst_id);
  867. if (inst.kind().has_type()) {
  868. out() << ": ";
  869. switch (GetExprCategory(*sem_ir_, inst_id)) {
  870. case ExprCategory::NotExpr:
  871. case ExprCategory::Error:
  872. case ExprCategory::Value:
  873. case ExprCategory::Pattern:
  874. case ExprCategory::Mixed:
  875. case ExprCategory::RefTagged:
  876. case ExprCategory::Dependent:
  877. FormatTypeOfInst(inst_id);
  878. break;
  879. case ExprCategory::DurableRef:
  880. case ExprCategory::EphemeralRef:
  881. out() << "ref ";
  882. FormatTypeOfInst(inst_id);
  883. break;
  884. case ExprCategory::InPlaceInitializing:
  885. case ExprCategory::ReprInitializing: {
  886. out() << "init ";
  887. FormatTypeOfInst(inst_id);
  888. auto init_target_id = FindStorageArgForInitializer(
  889. *sem_ir_, inst_id, /*allow_transitive=*/false);
  890. FormatReturnSlotArg(init_target_id);
  891. break;
  892. }
  893. }
  894. }
  895. }
  896. auto Formatter::FormatInstArgAndKind(Inst::ArgAndKind arg_and_kind) -> void {
  897. GetFormatArgFn(arg_and_kind.kind())(*this, arg_and_kind.value());
  898. }
  899. auto Formatter::FormatInstRhs(Inst inst) -> void {
  900. CARBON_KIND_SWITCH(inst) {
  901. case CARBON_KIND_ANY(AnyAggregateInit, init): {
  902. FormatArgs(init.elements_id);
  903. return;
  904. }
  905. case CARBON_KIND_ANY(AnyImportRef, import_ref): {
  906. FormatImportRefRhs(import_ref);
  907. return;
  908. }
  909. case CARBON_KIND_ANY(AnyParam, param): {
  910. FormatArgs(param.index);
  911. // Omit pretty_name because it's an implementation detail of
  912. // pretty-printing.
  913. return;
  914. }
  915. case CARBON_KIND_ANY(AnyLeafParamPattern, _): {
  916. // Omit pretty_name because it's an implementation detail of
  917. // pretty-printing.
  918. return;
  919. }
  920. case CARBON_KIND(VarParamPattern param): {
  921. FormatArgs(param.subpattern_id);
  922. // Omit pretty_name because it's an implementation detail of
  923. // pretty-printing.
  924. return;
  925. }
  926. case CARBON_KIND(AssociatedConstantDecl decl): {
  927. FormatArgs(decl.assoc_const_id);
  928. llvm::SaveAndRestore scope(scope_,
  929. inst_namer_.GetScopeFor(decl.assoc_const_id));
  930. FormatTrailingBlock(decl.decl_block_id);
  931. return;
  932. }
  933. case CARBON_KIND(SymbolicBinding bind): {
  934. // A SymbolicBinding with no value is a purely symbolic binding, such as
  935. // the `Self` in an interface. Don't print out `none` for the value.
  936. if (bind.value_id.has_value()) {
  937. FormatArgs(bind.entity_name_id, bind.value_id);
  938. } else {
  939. FormatArgs(bind.entity_name_id);
  940. }
  941. return;
  942. }
  943. case CARBON_KIND(BlockArg block): {
  944. out() << " ";
  945. FormatLabel(block.block_id);
  946. return;
  947. }
  948. case CARBON_KIND(Call call): {
  949. FormatCallRhs(call);
  950. return;
  951. }
  952. case CARBON_KIND(ClassDecl decl): {
  953. FormatDeclRhs(decl.class_id,
  954. sem_ir_->classes().Get(decl.class_id).pattern_block_id,
  955. decl.decl_block_id);
  956. return;
  957. }
  958. case CARBON_KIND(CppTemplateNameType type): {
  959. // Omit the Clang declaration. We don't have a good way to format it, and
  960. // the entity name should suffice to identify the template.
  961. FormatArgs(type.name_id);
  962. return;
  963. }
  964. case CARBON_KIND(CustomLayoutType type): {
  965. out() << " {";
  966. auto layout = sem_ir_->custom_layouts().Get(type.layout_id);
  967. out() << "size=" << layout[CustomLayoutId::SizeIndex]
  968. << ", align=" << layout[CustomLayoutId::AlignIndex];
  969. for (auto [field, offset] : llvm::zip_equal(
  970. sem_ir_->struct_type_fields().Get(type.fields_id),
  971. layout.drop_front(CustomLayoutId::FirstFieldIndex))) {
  972. out() << ", .";
  973. FormatName(field.name_id);
  974. out() << "@" << offset << ": ";
  975. FormatInstAsType(field.type_inst_id);
  976. }
  977. out() << "}";
  978. return;
  979. }
  980. case CARBON_KIND(FloatValue value): {
  981. llvm::SmallVector<char, 16> buffer;
  982. sem_ir_->floats().Get(value.float_id).toString(buffer);
  983. out() << " " << buffer;
  984. return;
  985. }
  986. case CARBON_KIND(FunctionDecl decl): {
  987. FormatDeclRhs(decl.function_id,
  988. sem_ir_->functions().Get(decl.function_id).pattern_block_id,
  989. decl.decl_block_id);
  990. return;
  991. }
  992. case ImportCppDecl::Kind: {
  993. FormatImportCppDeclRhs();
  994. return;
  995. }
  996. case CARBON_KIND(ImplDecl decl): {
  997. FormatDeclRhs(decl.impl_id,
  998. sem_ir_->impls().Get(decl.impl_id).pattern_block_id,
  999. decl.decl_block_id);
  1000. return;
  1001. }
  1002. case CARBON_KIND(InPlaceInit init): {
  1003. FormatArgs(init.src_id);
  1004. return;
  1005. }
  1006. case CARBON_KIND(InstValue inst): {
  1007. out() << ' ';
  1008. OpenBrace();
  1009. // TODO: Should we use a more compact representation in the case where the
  1010. // inst is a SpliceBlock?
  1011. FormatInst(inst.inst_id);
  1012. CloseBrace();
  1013. return;
  1014. }
  1015. case CARBON_KIND(InterfaceDecl decl): {
  1016. FormatDeclRhs(
  1017. decl.interface_id,
  1018. sem_ir_->interfaces().Get(decl.interface_id).pattern_block_id,
  1019. decl.decl_block_id);
  1020. return;
  1021. }
  1022. case CARBON_KIND(IntValue value): {
  1023. out() << " ";
  1024. sem_ir_->ints()
  1025. .Get(value.int_id)
  1026. .print(out(), sem_ir_->types().IsSignedInt(value.type_id));
  1027. return;
  1028. }
  1029. case CARBON_KIND(NameBindingDecl name): {
  1030. FormatTrailingBlock(name.pattern_block_id);
  1031. return;
  1032. }
  1033. case CARBON_KIND(NamedConstraintDecl decl): {
  1034. FormatDeclRhs(decl.named_constraint_id,
  1035. sem_ir_->named_constraints()
  1036. .Get(decl.named_constraint_id)
  1037. .pattern_block_id,
  1038. decl.decl_block_id);
  1039. return;
  1040. }
  1041. case CARBON_KIND(Namespace ns): {
  1042. if (ns.import_id.has_value()) {
  1043. FormatArgs(ns.import_id, ns.name_scope_id);
  1044. } else {
  1045. FormatArgs(ns.name_scope_id);
  1046. }
  1047. return;
  1048. }
  1049. case CARBON_KIND(RequireImplsDecl decl): {
  1050. FormatArgs(decl.require_impls_id);
  1051. llvm::SaveAndRestore scope(
  1052. scope_, inst_namer_.GetScopeFor(decl.require_impls_id));
  1053. FormatRequireImpls(decl.require_impls_id);
  1054. FormatTrailingBlock(decl.decl_block_id);
  1055. return;
  1056. }
  1057. case CARBON_KIND(ReturnExpr ret): {
  1058. FormatArgs(ret.expr_id);
  1059. if (ret.dest_id.has_value()) {
  1060. FormatReturnSlotArg(ret.dest_id);
  1061. }
  1062. return;
  1063. }
  1064. case CARBON_KIND(ReturnSlot ret): {
  1065. // Omit inst.type_inst_id because it's not semantically significant.
  1066. FormatArgs(ret.storage_id);
  1067. return;
  1068. }
  1069. case CARBON_KIND(SpliceBlock splice): {
  1070. FormatArgs(splice.result_id);
  1071. FormatTrailingBlock(splice.block_id);
  1072. return;
  1073. }
  1074. case CARBON_KIND(StructType struct_type): {
  1075. out() << " {";
  1076. llvm::ListSeparator sep;
  1077. for (auto field :
  1078. sem_ir_->struct_type_fields().Get(struct_type.fields_id)) {
  1079. out() << sep << ".";
  1080. FormatName(field.name_id);
  1081. out() << ": ";
  1082. FormatInstAsType(field.type_inst_id);
  1083. }
  1084. out() << "}";
  1085. return;
  1086. }
  1087. case CARBON_KIND(WhereExpr where): {
  1088. FormatArgs(where.period_self_id);
  1089. FormatTrailingBlock(where.requirements_id);
  1090. return;
  1091. }
  1092. default:
  1093. FormatInstRhsDefault(inst);
  1094. return;
  1095. }
  1096. }
  1097. auto Formatter::FormatInstRhsDefault(Inst inst) -> void {
  1098. auto arg0 = inst.arg0_and_kind();
  1099. if (arg0.kind() == IdKind::None) {
  1100. return;
  1101. }
  1102. out() << " ";
  1103. FormatInstArgAndKind(arg0);
  1104. auto arg1 = inst.arg1_and_kind();
  1105. if (arg1.kind() == IdKind::None) {
  1106. return;
  1107. }
  1108. // Several instructions have a second operand that's a specific ID. We
  1109. // don't include it in the argument list if there is no corresponding
  1110. // specific, that is, when we're not in a generic context.
  1111. if (auto arg1_specific_id = arg1.TryAs<SpecificId>();
  1112. arg1_specific_id && !arg1_specific_id->has_value()) {
  1113. return;
  1114. }
  1115. // Similarly, instructions that have a `DestInstId` as the second operand
  1116. // typically use it for the output argument, so we omit it because it should
  1117. // already be part of the inst's formatted form expression.
  1118. if (arg1.kind() == IdKind::For<DestInstId>) {
  1119. return;
  1120. }
  1121. out() << ", ";
  1122. FormatInstArgAndKind(arg1);
  1123. }
  1124. auto Formatter::FormatCallRhs(Call inst) -> void {
  1125. out() << " ";
  1126. FormatArg(inst.callee_id);
  1127. if (!inst.args_id.has_value()) {
  1128. out() << "(<none>)";
  1129. return;
  1130. }
  1131. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  1132. // If there are return arguments, don't print them here, because it's printed
  1133. // on the LHS.
  1134. auto explicit_end = SemIR::CallParamIndex::None;
  1135. auto callee = GetCallee(*sem_ir_, inst.callee_id);
  1136. if (auto* callee_function = std::get_if<CalleeFunction>(&callee)) {
  1137. explicit_end = sem_ir_->functions()
  1138. .Get(callee_function->function_id)
  1139. .call_param_ranges.explicit_end();
  1140. }
  1141. llvm::ListSeparator sep;
  1142. out() << '(';
  1143. for (auto [i, inst_id] : llvm::enumerate(args)) {
  1144. if (explicit_end.has_value() && static_cast<int>(i) >= explicit_end.index) {
  1145. break;
  1146. }
  1147. out() << sep;
  1148. FormatArg(inst_id);
  1149. }
  1150. out() << ')';
  1151. }
  1152. auto Formatter::FormatImportCppDeclRhs() -> void {
  1153. out() << " ";
  1154. OpenBrace();
  1155. for (const Parse::Tree::PackagingNames& import :
  1156. sem_ir_->parse_tree().imports()) {
  1157. if (import.package_id != PackageNameId::Cpp) {
  1158. continue;
  1159. }
  1160. Indent();
  1161. out() << "import Cpp";
  1162. if (import.library_id.has_value()) {
  1163. out() << " \""
  1164. << FormatEscaped(
  1165. sem_ir_->string_literal_values().Get(import.library_id))
  1166. << "\"";
  1167. } else if (import.inline_body_id.has_value()) {
  1168. out() << " inline";
  1169. }
  1170. out() << "\n";
  1171. }
  1172. CloseBrace();
  1173. }
  1174. auto Formatter::FormatImportRefRhs(AnyImportRef inst) -> void {
  1175. out() << " ";
  1176. auto import_ir_inst = sem_ir_->import_ir_insts().Get(inst.import_ir_inst_id);
  1177. FormatArg(import_ir_inst.ir_id());
  1178. out() << ", ";
  1179. if (inst.entity_name_id.has_value()) {
  1180. // Prefer to show the entity name when possible.
  1181. FormatArg(inst.entity_name_id);
  1182. } else {
  1183. // Show a name based on the location when possible, or the numeric
  1184. // instruction as a last resort.
  1185. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  1186. auto loc_id =
  1187. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  1188. switch (loc_id.kind()) {
  1189. case LocId::Kind::None: {
  1190. out() << import_ir_inst.inst_id() << " [no loc]";
  1191. break;
  1192. }
  1193. case LocId::Kind::ImportIRInstId: {
  1194. // TODO: Probably don't want to format each indirection, but maybe
  1195. // reuse GetCanonicalImportIRInst?
  1196. out() << import_ir_inst.inst_id() << " [indirect]";
  1197. break;
  1198. }
  1199. case LocId::Kind::NodeId: {
  1200. // Formats a NodeId from the import.
  1201. const auto& tree = import_ir.sem_ir->parse_tree();
  1202. auto token = tree.node_token(loc_id.node_id());
  1203. out() << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1204. << tree.tokens().GetColumnNumber(token);
  1205. break;
  1206. }
  1207. case LocId::Kind::InstId:
  1208. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1209. }
  1210. }
  1211. out() << ", "
  1212. << (inst.kind == InstKind::ImportRefLoaded ? "loaded" : "unloaded");
  1213. }
  1214. auto Formatter::FormatRequireImpls(RequireImplsId id) -> void {
  1215. out() << ' ';
  1216. const auto& require = sem_ir_->require_impls().Get(id);
  1217. OpenBrace();
  1218. Indent();
  1219. out() << "require ";
  1220. FormatArg(require.self_id);
  1221. out() << " impls ";
  1222. FormatArg(require.facet_type_inst_id);
  1223. out() << "\n";
  1224. CloseBrace();
  1225. }
  1226. auto Formatter::FormatRequireImplsBlock(RequireImplsBlockId block_id) -> void {
  1227. IndentLabel();
  1228. out() << "!requires:\n";
  1229. if (!block_id.has_value()) {
  1230. return;
  1231. }
  1232. for (auto require_impls_id : sem_ir_->require_impls_blocks().Get(block_id)) {
  1233. Indent();
  1234. FormatArg(require_impls_id);
  1235. FormatRequireImpls(require_impls_id);
  1236. out() << "\n";
  1237. }
  1238. }
  1239. auto Formatter::FormatArg(EntityNameId id) -> void {
  1240. if (!id.has_value()) {
  1241. out() << "_";
  1242. return;
  1243. }
  1244. const auto& info = sem_ir_->entity_names().Get(id);
  1245. FormatName(info.name_id);
  1246. if (info.bind_index().has_value()) {
  1247. out() << ", " << info.bind_index().index;
  1248. }
  1249. if (info.is_template) {
  1250. out() << ", template";
  1251. }
  1252. }
  1253. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1254. const auto& info = sem_ir_->facet_types().Get(id);
  1255. // Nothing output to indicate that this is a facet type since this is only
  1256. // used as the argument to a `facet_type` instruction.
  1257. out() << "<";
  1258. llvm::ListSeparator sep(" & ");
  1259. if (info.extend_constraints.empty() &&
  1260. info.extend_named_constraints.empty()) {
  1261. out() << "type";
  1262. } else {
  1263. for (auto extend : info.extend_constraints) {
  1264. out() << sep;
  1265. FormatName(extend.interface_id);
  1266. if (extend.specific_id.has_value()) {
  1267. out() << ", ";
  1268. FormatName(extend.specific_id);
  1269. }
  1270. }
  1271. for (auto extend : info.extend_named_constraints) {
  1272. out() << sep;
  1273. FormatName(extend.named_constraint_id);
  1274. if (extend.specific_id.has_value()) {
  1275. out() << ", ";
  1276. FormatName(extend.specific_id);
  1277. }
  1278. }
  1279. }
  1280. if (info.other_requirements || !info.self_impls_constraints.empty() ||
  1281. !info.rewrite_constraints.empty()) {
  1282. out() << " where ";
  1283. llvm::ListSeparator and_sep(" and ");
  1284. if (!info.self_impls_constraints.empty() ||
  1285. !info.self_impls_named_constraints.empty()) {
  1286. out() << and_sep << ".Self impls ";
  1287. llvm::ListSeparator amp_sep(" & ");
  1288. for (auto self_impls : info.self_impls_constraints) {
  1289. out() << amp_sep;
  1290. FormatName(self_impls.interface_id);
  1291. if (self_impls.specific_id.has_value()) {
  1292. out() << ", ";
  1293. FormatName(self_impls.specific_id);
  1294. }
  1295. }
  1296. for (auto self_impls : info.self_impls_named_constraints) {
  1297. out() << amp_sep;
  1298. FormatName(self_impls.named_constraint_id);
  1299. if (self_impls.specific_id.has_value()) {
  1300. out() << ", ";
  1301. FormatName(self_impls.specific_id);
  1302. }
  1303. }
  1304. }
  1305. for (auto rewrite : info.rewrite_constraints) {
  1306. out() << and_sep;
  1307. FormatArg(rewrite.lhs_id);
  1308. out() << " = ";
  1309. FormatArg(rewrite.rhs_id);
  1310. }
  1311. if (info.other_requirements) {
  1312. out() << and_sep << "TODO";
  1313. }
  1314. }
  1315. out() << ">";
  1316. }
  1317. auto Formatter::FormatArg(ImportIRId id) -> void {
  1318. if (id.has_value()) {
  1319. out() << GetImportIRLabel(id);
  1320. } else {
  1321. out() << id;
  1322. }
  1323. }
  1324. auto Formatter::FormatArg(IntId id) -> void {
  1325. // We don't know the signedness to use here. Default to unsigned.
  1326. sem_ir_->ints().Get(id).print(out(), /*isSigned=*/false);
  1327. }
  1328. auto Formatter::FormatArg(NameScopeId id) -> void {
  1329. OpenBrace();
  1330. FormatNameScope(id);
  1331. CloseBrace();
  1332. }
  1333. auto Formatter::FormatArg(InstBlockId id) -> void {
  1334. if (!id.has_value()) {
  1335. out() << "invalid";
  1336. return;
  1337. }
  1338. out() << '(';
  1339. llvm::ListSeparator sep;
  1340. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1341. out() << sep;
  1342. FormatArg(inst_id);
  1343. }
  1344. out() << ')';
  1345. }
  1346. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1347. FormatArg(static_cast<InstBlockId>(id));
  1348. }
  1349. auto Formatter::FormatArg(ExprRegionId id) -> void {
  1350. const auto& region = sem_ir_->expr_regions().Get(id);
  1351. FormatArg(region.result_id);
  1352. out() << " in ";
  1353. OpenBrace();
  1354. for (auto [i, block_id] : llvm::enumerate(region.block_ids)) {
  1355. if (i != 0) {
  1356. IndentLabel();
  1357. FormatLabel(block_id);
  1358. out() << ":\n";
  1359. }
  1360. FormatCodeBlock(block_id);
  1361. }
  1362. CloseBrace();
  1363. }
  1364. auto Formatter::FormatArg(RealId id) -> void {
  1365. // TODO: Format with a `.` when the exponent is near zero.
  1366. const auto& real = sem_ir_->reals().Get(id);
  1367. real.mantissa.print(out(), /*isSigned=*/false);
  1368. out() << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1369. }
  1370. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1371. out() << '"'
  1372. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1373. /*use_hex_escapes=*/true)
  1374. << '"';
  1375. }
  1376. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1377. if (dest_id.has_value()) {
  1378. out() << " to ";
  1379. FormatArg(dest_id);
  1380. }
  1381. }
  1382. auto Formatter::FormatName(NameId id) -> void {
  1383. out() << sem_ir_->names().GetFormatted(id);
  1384. }
  1385. auto Formatter::FormatName(InstId id) -> void {
  1386. if (id.has_value()) {
  1387. if (auto chunk = tentative_inst_chunks_.Get(id);
  1388. chunk != FormatterChunks::None) {
  1389. chunks_.AppendChildToCurrentParent(chunk);
  1390. }
  1391. }
  1392. out() << inst_namer_.GetNameFor(scope_, id);
  1393. }
  1394. auto Formatter::FormatName(SpecificId id) -> void {
  1395. const auto& specific = sem_ir_->specifics().Get(id);
  1396. FormatName(specific.generic_id);
  1397. FormatArg(specific.args_id);
  1398. }
  1399. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1400. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1401. FormatName(interface.interface_id);
  1402. if (interface.specific_id.has_value()) {
  1403. out() << ", ";
  1404. FormatArg(interface.specific_id);
  1405. }
  1406. }
  1407. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1408. out() << inst_namer_.GetLabelFor(scope_, id);
  1409. }
  1410. auto Formatter::FormatConstant(ConstantId id) -> void {
  1411. if (!id.has_value()) {
  1412. out() << "<not constant>";
  1413. return;
  1414. }
  1415. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1416. FormatName(inst_id);
  1417. // For an attached constant, also list the unattached constant.
  1418. if (id.is_symbolic() && sem_ir_->constant_values()
  1419. .GetSymbolicConstant(id)
  1420. .generic_id.has_value()) {
  1421. // TODO: Skip printing this if it's the same as `inst_id`.
  1422. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1423. out() << " (";
  1424. FormatName(unattached_inst_id);
  1425. out() << ")";
  1426. }
  1427. }
  1428. auto Formatter::FormatInstAsType(InstId id) -> void {
  1429. if (!id.has_value()) {
  1430. out() << "invalid";
  1431. return;
  1432. }
  1433. // Types are formatted in the `constants` scope because they typically refer
  1434. // to constants.
  1435. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1436. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1437. const_id.has_value()) {
  1438. FormatConstant(const_id);
  1439. } else {
  1440. // Type instruction didn't have a constant value. Fall back to printing
  1441. // the instruction name.
  1442. FormatArg(id);
  1443. }
  1444. }
  1445. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1446. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1447. if (!type_id.has_value()) {
  1448. out() << "invalid";
  1449. return;
  1450. }
  1451. // Types are formatted in the `constants` scope because they typically refer
  1452. // to constants.
  1453. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1454. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1455. }
  1456. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1457. CARBON_CHECK(id.has_value(),
  1458. "Callers are responsible for checking `id.has_value`");
  1459. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1460. CARBON_CHECK(import_ir.library_id().has_value());
  1461. auto package_id = import_ir.package_id();
  1462. llvm::StringRef package_name =
  1463. package_id.AsIdentifierId().has_value()
  1464. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1465. : package_id.AsSpecialName();
  1466. llvm::StringRef library_name =
  1467. (import_ir.library_id() != LibraryNameId::Default)
  1468. ? import_ir.string_literal_values().Get(
  1469. import_ir.library_id().AsStringLiteralValueId())
  1470. : "default";
  1471. return llvm::formatv("{0}//{1}", package_name, library_name);
  1472. }
  1473. } // namespace Carbon::SemIR
  1474. // NOLINTEND(misc-no-recursion)