formatter.cpp 48 KB

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