formatter.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  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(AssociatedConstantDecl decl): {
  916. FormatArgs(decl.assoc_const_id);
  917. llvm::SaveAndRestore scope(scope_,
  918. inst_namer_.GetScopeFor(decl.assoc_const_id));
  919. FormatTrailingBlock(decl.decl_block_id);
  920. return;
  921. }
  922. case CARBON_KIND(SymbolicBinding bind): {
  923. // A SymbolicBinding with no value is a purely symbolic binding, such as
  924. // the `Self` in an interface. Don't print out `none` for the value.
  925. if (bind.value_id.has_value()) {
  926. FormatArgs(bind.entity_name_id, bind.value_id);
  927. } else {
  928. FormatArgs(bind.entity_name_id);
  929. }
  930. return;
  931. }
  932. case CARBON_KIND(BlockArg block): {
  933. out() << " ";
  934. FormatLabel(block.block_id);
  935. return;
  936. }
  937. case CARBON_KIND(Call call): {
  938. FormatCallRhs(call);
  939. return;
  940. }
  941. case CARBON_KIND(ClassDecl decl): {
  942. FormatDeclRhs(decl.class_id,
  943. sem_ir_->classes().Get(decl.class_id).pattern_block_id,
  944. decl.decl_block_id);
  945. return;
  946. }
  947. case CARBON_KIND(CppTemplateNameType type): {
  948. // Omit the Clang declaration. We don't have a good way to format it, and
  949. // the entity name should suffice to identify the template.
  950. FormatArgs(type.name_id);
  951. return;
  952. }
  953. case CARBON_KIND(CustomLayoutType type): {
  954. out() << " {";
  955. auto layout = sem_ir_->custom_layouts().Get(type.layout_id);
  956. out() << "size=" << layout[CustomLayoutId::SizeIndex]
  957. << ", align=" << layout[CustomLayoutId::AlignIndex];
  958. for (auto [field, offset] : llvm::zip_equal(
  959. sem_ir_->struct_type_fields().Get(type.fields_id),
  960. layout.drop_front(CustomLayoutId::FirstFieldIndex))) {
  961. out() << ", .";
  962. FormatName(field.name_id);
  963. out() << "@" << offset << ": ";
  964. FormatInstAsType(field.type_inst_id);
  965. }
  966. out() << "}";
  967. return;
  968. }
  969. case CARBON_KIND(FloatValue value): {
  970. llvm::SmallVector<char, 16> buffer;
  971. sem_ir_->floats().Get(value.float_id).toString(buffer);
  972. out() << " " << buffer;
  973. return;
  974. }
  975. case CARBON_KIND(FunctionDecl decl): {
  976. FormatDeclRhs(decl.function_id,
  977. sem_ir_->functions().Get(decl.function_id).pattern_block_id,
  978. decl.decl_block_id);
  979. return;
  980. }
  981. case ImportCppDecl::Kind: {
  982. FormatImportCppDeclRhs();
  983. return;
  984. }
  985. case CARBON_KIND(ImplDecl decl): {
  986. FormatDeclRhs(decl.impl_id,
  987. sem_ir_->impls().Get(decl.impl_id).pattern_block_id,
  988. decl.decl_block_id);
  989. return;
  990. }
  991. case CARBON_KIND(InPlaceInit init): {
  992. FormatArgs(init.src_id);
  993. return;
  994. }
  995. case CARBON_KIND(InstValue inst): {
  996. out() << ' ';
  997. OpenBrace();
  998. // TODO: Should we use a more compact representation in the case where the
  999. // inst is a SpliceBlock?
  1000. FormatInst(inst.inst_id);
  1001. CloseBrace();
  1002. return;
  1003. }
  1004. case CARBON_KIND(InterfaceDecl decl): {
  1005. FormatDeclRhs(
  1006. decl.interface_id,
  1007. sem_ir_->interfaces().Get(decl.interface_id).pattern_block_id,
  1008. decl.decl_block_id);
  1009. return;
  1010. }
  1011. case CARBON_KIND(IntValue value): {
  1012. out() << " ";
  1013. sem_ir_->ints()
  1014. .Get(value.int_id)
  1015. .print(out(), sem_ir_->types().IsSignedInt(value.type_id));
  1016. return;
  1017. }
  1018. case CARBON_KIND(NameBindingDecl name): {
  1019. FormatTrailingBlock(name.pattern_block_id);
  1020. return;
  1021. }
  1022. case CARBON_KIND(NamedConstraintDecl decl): {
  1023. FormatDeclRhs(decl.named_constraint_id,
  1024. sem_ir_->named_constraints()
  1025. .Get(decl.named_constraint_id)
  1026. .pattern_block_id,
  1027. decl.decl_block_id);
  1028. return;
  1029. }
  1030. case CARBON_KIND(Namespace ns): {
  1031. if (ns.import_id.has_value()) {
  1032. FormatArgs(ns.import_id, ns.name_scope_id);
  1033. } else {
  1034. FormatArgs(ns.name_scope_id);
  1035. }
  1036. return;
  1037. }
  1038. case CARBON_KIND(RequireImplsDecl decl): {
  1039. FormatArgs(decl.require_impls_id);
  1040. llvm::SaveAndRestore scope(
  1041. scope_, inst_namer_.GetScopeFor(decl.require_impls_id));
  1042. FormatRequireImpls(decl.require_impls_id);
  1043. FormatTrailingBlock(decl.decl_block_id);
  1044. return;
  1045. }
  1046. case CARBON_KIND(ReturnExpr ret): {
  1047. FormatArgs(ret.expr_id);
  1048. if (ret.dest_id.has_value()) {
  1049. FormatReturnSlotArg(ret.dest_id);
  1050. }
  1051. return;
  1052. }
  1053. case CARBON_KIND(ReturnSlot ret): {
  1054. // Omit inst.type_inst_id because it's not semantically significant.
  1055. FormatArgs(ret.storage_id);
  1056. return;
  1057. }
  1058. case ReturnSlotPattern::Kind:
  1059. // No-op because type_id is the only semantically significant field,
  1060. // and it's handled separately.
  1061. return;
  1062. case CARBON_KIND(SpliceBlock splice): {
  1063. FormatArgs(splice.result_id);
  1064. FormatTrailingBlock(splice.block_id);
  1065. return;
  1066. }
  1067. case CARBON_KIND(StructType struct_type): {
  1068. out() << " {";
  1069. llvm::ListSeparator sep;
  1070. for (auto field :
  1071. sem_ir_->struct_type_fields().Get(struct_type.fields_id)) {
  1072. out() << sep << ".";
  1073. FormatName(field.name_id);
  1074. out() << ": ";
  1075. FormatInstAsType(field.type_inst_id);
  1076. }
  1077. out() << "}";
  1078. return;
  1079. }
  1080. case CARBON_KIND(WhereExpr where): {
  1081. FormatArgs(where.period_self_id);
  1082. FormatTrailingBlock(where.requirements_id);
  1083. return;
  1084. }
  1085. default:
  1086. FormatInstRhsDefault(inst);
  1087. return;
  1088. }
  1089. }
  1090. auto Formatter::FormatInstRhsDefault(Inst inst) -> void {
  1091. auto arg0 = inst.arg0_and_kind();
  1092. if (arg0.kind() == IdKind::None) {
  1093. return;
  1094. }
  1095. out() << " ";
  1096. FormatInstArgAndKind(arg0);
  1097. auto arg1 = inst.arg1_and_kind();
  1098. if (arg1.kind() == IdKind::None) {
  1099. return;
  1100. }
  1101. // Several instructions have a second operand that's a specific ID. We
  1102. // don't include it in the argument list if there is no corresponding
  1103. // specific, that is, when we're not in a generic context.
  1104. if (auto arg1_specific_id = arg1.TryAs<SpecificId>();
  1105. arg1_specific_id && !arg1_specific_id->has_value()) {
  1106. return;
  1107. }
  1108. // Similarly, instructions that have a `DestInstId` as the second operand
  1109. // typically use it for the output argument, so we omit it because it should
  1110. // already be part of the inst's formatted form expression.
  1111. if (arg1.kind() == IdKind::For<DestInstId>) {
  1112. return;
  1113. }
  1114. out() << ", ";
  1115. FormatInstArgAndKind(arg1);
  1116. }
  1117. auto Formatter::FormatCallRhs(Call inst) -> void {
  1118. out() << " ";
  1119. FormatArg(inst.callee_id);
  1120. if (!inst.args_id.has_value()) {
  1121. out() << "(<none>)";
  1122. return;
  1123. }
  1124. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  1125. // If there are return arguments, don't print them here, because it's printed
  1126. // on the LHS.
  1127. auto explicit_end = SemIR::CallParamIndex::None;
  1128. auto callee = GetCallee(*sem_ir_, inst.callee_id);
  1129. if (auto* callee_function = std::get_if<CalleeFunction>(&callee)) {
  1130. explicit_end = sem_ir_->functions()
  1131. .Get(callee_function->function_id)
  1132. .call_param_ranges.explicit_end();
  1133. }
  1134. llvm::ListSeparator sep;
  1135. out() << '(';
  1136. for (auto [i, inst_id] : llvm::enumerate(args)) {
  1137. if (explicit_end.has_value() && static_cast<int>(i) >= explicit_end.index) {
  1138. break;
  1139. }
  1140. out() << sep;
  1141. FormatArg(inst_id);
  1142. }
  1143. out() << ')';
  1144. }
  1145. auto Formatter::FormatImportCppDeclRhs() -> void {
  1146. out() << " ";
  1147. OpenBrace();
  1148. for (const Parse::Tree::PackagingNames& import :
  1149. sem_ir_->parse_tree().imports()) {
  1150. if (import.package_id != PackageNameId::Cpp) {
  1151. continue;
  1152. }
  1153. Indent();
  1154. out() << "import Cpp";
  1155. if (import.library_id.has_value()) {
  1156. out() << " \""
  1157. << FormatEscaped(
  1158. sem_ir_->string_literal_values().Get(import.library_id))
  1159. << "\"";
  1160. } else if (import.inline_body_id.has_value()) {
  1161. out() << " inline";
  1162. }
  1163. out() << "\n";
  1164. }
  1165. CloseBrace();
  1166. }
  1167. auto Formatter::FormatImportRefRhs(AnyImportRef inst) -> void {
  1168. out() << " ";
  1169. auto import_ir_inst = sem_ir_->import_ir_insts().Get(inst.import_ir_inst_id);
  1170. FormatArg(import_ir_inst.ir_id());
  1171. out() << ", ";
  1172. if (inst.entity_name_id.has_value()) {
  1173. // Prefer to show the entity name when possible.
  1174. FormatArg(inst.entity_name_id);
  1175. } else {
  1176. // Show a name based on the location when possible, or the numeric
  1177. // instruction as a last resort.
  1178. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  1179. auto loc_id =
  1180. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  1181. switch (loc_id.kind()) {
  1182. case LocId::Kind::None: {
  1183. out() << import_ir_inst.inst_id() << " [no loc]";
  1184. break;
  1185. }
  1186. case LocId::Kind::ImportIRInstId: {
  1187. // TODO: Probably don't want to format each indirection, but maybe
  1188. // reuse GetCanonicalImportIRInst?
  1189. out() << import_ir_inst.inst_id() << " [indirect]";
  1190. break;
  1191. }
  1192. case LocId::Kind::NodeId: {
  1193. // Formats a NodeId from the import.
  1194. const auto& tree = import_ir.sem_ir->parse_tree();
  1195. auto token = tree.node_token(loc_id.node_id());
  1196. out() << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1197. << tree.tokens().GetColumnNumber(token);
  1198. break;
  1199. }
  1200. case LocId::Kind::InstId:
  1201. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1202. }
  1203. }
  1204. out() << ", "
  1205. << (inst.kind == InstKind::ImportRefLoaded ? "loaded" : "unloaded");
  1206. }
  1207. auto Formatter::FormatRequireImpls(RequireImplsId id) -> void {
  1208. out() << ' ';
  1209. const auto& require = sem_ir_->require_impls().Get(id);
  1210. OpenBrace();
  1211. Indent();
  1212. out() << "require ";
  1213. FormatArg(require.self_id);
  1214. out() << " impls ";
  1215. FormatArg(require.facet_type_inst_id);
  1216. out() << "\n";
  1217. CloseBrace();
  1218. }
  1219. auto Formatter::FormatRequireImplsBlock(RequireImplsBlockId block_id) -> void {
  1220. IndentLabel();
  1221. out() << "!requires:\n";
  1222. if (!block_id.has_value()) {
  1223. return;
  1224. }
  1225. for (auto require_impls_id : sem_ir_->require_impls_blocks().Get(block_id)) {
  1226. Indent();
  1227. FormatArg(require_impls_id);
  1228. FormatRequireImpls(require_impls_id);
  1229. out() << "\n";
  1230. }
  1231. }
  1232. auto Formatter::FormatArg(EntityNameId id) -> void {
  1233. if (!id.has_value()) {
  1234. out() << "_";
  1235. return;
  1236. }
  1237. const auto& info = sem_ir_->entity_names().Get(id);
  1238. FormatName(info.name_id);
  1239. if (info.bind_index().has_value()) {
  1240. out() << ", " << info.bind_index().index;
  1241. }
  1242. if (info.is_template) {
  1243. out() << ", template";
  1244. }
  1245. }
  1246. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1247. const auto& info = sem_ir_->facet_types().Get(id);
  1248. // Nothing output to indicate that this is a facet type since this is only
  1249. // used as the argument to a `facet_type` instruction.
  1250. out() << "<";
  1251. llvm::ListSeparator sep(" & ");
  1252. if (info.extend_constraints.empty() &&
  1253. info.extend_named_constraints.empty()) {
  1254. out() << "type";
  1255. } else {
  1256. for (auto extend : info.extend_constraints) {
  1257. out() << sep;
  1258. FormatName(extend.interface_id);
  1259. if (extend.specific_id.has_value()) {
  1260. out() << ", ";
  1261. FormatName(extend.specific_id);
  1262. }
  1263. }
  1264. for (auto extend : info.extend_named_constraints) {
  1265. out() << sep;
  1266. FormatName(extend.named_constraint_id);
  1267. if (extend.specific_id.has_value()) {
  1268. out() << ", ";
  1269. FormatName(extend.specific_id);
  1270. }
  1271. }
  1272. }
  1273. if (info.other_requirements || !info.self_impls_constraints.empty() ||
  1274. !info.rewrite_constraints.empty()) {
  1275. out() << " where ";
  1276. llvm::ListSeparator and_sep(" and ");
  1277. if (!info.self_impls_constraints.empty() ||
  1278. !info.self_impls_named_constraints.empty()) {
  1279. out() << and_sep << ".Self impls ";
  1280. llvm::ListSeparator amp_sep(" & ");
  1281. for (auto self_impls : info.self_impls_constraints) {
  1282. out() << amp_sep;
  1283. FormatName(self_impls.interface_id);
  1284. if (self_impls.specific_id.has_value()) {
  1285. out() << ", ";
  1286. FormatName(self_impls.specific_id);
  1287. }
  1288. }
  1289. for (auto self_impls : info.self_impls_named_constraints) {
  1290. out() << amp_sep;
  1291. FormatName(self_impls.named_constraint_id);
  1292. if (self_impls.specific_id.has_value()) {
  1293. out() << ", ";
  1294. FormatName(self_impls.specific_id);
  1295. }
  1296. }
  1297. }
  1298. for (auto rewrite : info.rewrite_constraints) {
  1299. out() << and_sep;
  1300. FormatArg(rewrite.lhs_id);
  1301. out() << " = ";
  1302. FormatArg(rewrite.rhs_id);
  1303. }
  1304. if (info.other_requirements) {
  1305. out() << and_sep << "TODO";
  1306. }
  1307. }
  1308. out() << ">";
  1309. }
  1310. auto Formatter::FormatArg(ImportIRId id) -> void {
  1311. if (id.has_value()) {
  1312. out() << GetImportIRLabel(id);
  1313. } else {
  1314. out() << id;
  1315. }
  1316. }
  1317. auto Formatter::FormatArg(IntId id) -> void {
  1318. // We don't know the signedness to use here. Default to unsigned.
  1319. sem_ir_->ints().Get(id).print(out(), /*isSigned=*/false);
  1320. }
  1321. auto Formatter::FormatArg(NameScopeId id) -> void {
  1322. OpenBrace();
  1323. FormatNameScope(id);
  1324. CloseBrace();
  1325. }
  1326. auto Formatter::FormatArg(InstBlockId id) -> void {
  1327. if (!id.has_value()) {
  1328. out() << "invalid";
  1329. return;
  1330. }
  1331. out() << '(';
  1332. llvm::ListSeparator sep;
  1333. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1334. out() << sep;
  1335. FormatArg(inst_id);
  1336. }
  1337. out() << ')';
  1338. }
  1339. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1340. FormatArg(static_cast<InstBlockId>(id));
  1341. }
  1342. auto Formatter::FormatArg(RealId id) -> void {
  1343. // TODO: Format with a `.` when the exponent is near zero.
  1344. const auto& real = sem_ir_->reals().Get(id);
  1345. real.mantissa.print(out(), /*isSigned=*/false);
  1346. out() << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1347. }
  1348. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1349. out() << '"'
  1350. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1351. /*use_hex_escapes=*/true)
  1352. << '"';
  1353. }
  1354. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1355. if (dest_id.has_value()) {
  1356. out() << " to ";
  1357. FormatArg(dest_id);
  1358. }
  1359. }
  1360. auto Formatter::FormatName(NameId id) -> void {
  1361. out() << sem_ir_->names().GetFormatted(id);
  1362. }
  1363. auto Formatter::FormatName(InstId id) -> void {
  1364. if (id.has_value()) {
  1365. if (auto chunk = tentative_inst_chunks_.Get(id);
  1366. chunk != FormatterChunks::None) {
  1367. chunks_.AppendChildToCurrentParent(chunk);
  1368. }
  1369. }
  1370. out() << inst_namer_.GetNameFor(scope_, id);
  1371. }
  1372. auto Formatter::FormatName(SpecificId id) -> void {
  1373. const auto& specific = sem_ir_->specifics().Get(id);
  1374. FormatName(specific.generic_id);
  1375. FormatArg(specific.args_id);
  1376. }
  1377. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1378. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1379. FormatName(interface.interface_id);
  1380. if (interface.specific_id.has_value()) {
  1381. out() << ", ";
  1382. FormatArg(interface.specific_id);
  1383. }
  1384. }
  1385. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1386. out() << inst_namer_.GetLabelFor(scope_, id);
  1387. }
  1388. auto Formatter::FormatConstant(ConstantId id) -> void {
  1389. if (!id.has_value()) {
  1390. out() << "<not constant>";
  1391. return;
  1392. }
  1393. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1394. FormatName(inst_id);
  1395. // For an attached constant, also list the unattached constant.
  1396. if (id.is_symbolic() && sem_ir_->constant_values()
  1397. .GetSymbolicConstant(id)
  1398. .generic_id.has_value()) {
  1399. // TODO: Skip printing this if it's the same as `inst_id`.
  1400. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1401. out() << " (";
  1402. FormatName(unattached_inst_id);
  1403. out() << ")";
  1404. }
  1405. }
  1406. auto Formatter::FormatInstAsType(InstId id) -> void {
  1407. if (!id.has_value()) {
  1408. out() << "invalid";
  1409. return;
  1410. }
  1411. // Types are formatted in the `constants` scope because they typically refer
  1412. // to constants.
  1413. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1414. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1415. const_id.has_value()) {
  1416. FormatConstant(const_id);
  1417. } else {
  1418. // Type instruction didn't have a constant value. Fall back to printing
  1419. // the instruction name.
  1420. FormatArg(id);
  1421. }
  1422. }
  1423. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1424. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1425. if (!type_id.has_value()) {
  1426. out() << "invalid";
  1427. return;
  1428. }
  1429. // Types are formatted in the `constants` scope because they typically refer
  1430. // to constants.
  1431. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1432. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1433. }
  1434. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1435. CARBON_CHECK(id.has_value(),
  1436. "Callers are responsible for checking `id.has_value`");
  1437. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1438. CARBON_CHECK(import_ir.library_id().has_value());
  1439. auto package_id = import_ir.package_id();
  1440. llvm::StringRef package_name =
  1441. package_id.AsIdentifierId().has_value()
  1442. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1443. : package_id.AsSpecialName();
  1444. llvm::StringRef library_name =
  1445. (import_ir.library_id() != LibraryNameId::Default)
  1446. ? import_ir.string_literal_values().Get(
  1447. import_ir.library_id().AsStringLiteralValueId())
  1448. : "default";
  1449. return llvm::formatv("{0}//{1}", package_name, library_name);
  1450. }
  1451. } // namespace Carbon::SemIR
  1452. // NOLINTEND(misc-no-recursion)