formatter.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  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/kind_switch.h"
  12. #include "toolchain/base/shared_value_stores.h"
  13. #include "toolchain/lex/tokenized_buffer.h"
  14. #include "toolchain/parse/tree.h"
  15. #include "toolchain/parse/tree_and_subtrees.h"
  16. #include "toolchain/sem_ir/builtin_function_kind.h"
  17. #include "toolchain/sem_ir/constant.h"
  18. #include "toolchain/sem_ir/entity_with_params_base.h"
  19. #include "toolchain/sem_ir/expr_info.h"
  20. #include "toolchain/sem_ir/function.h"
  21. #include "toolchain/sem_ir/ids.h"
  22. #include "toolchain/sem_ir/name_scope.h"
  23. #include "toolchain/sem_ir/typed_insts.h"
  24. // TODO: Consider addressing recursion here, although it's not critical because
  25. // the formatter isn't required to work on arbitrary code. Still, it may help
  26. // in the future to debug complex code.
  27. // NOLINTBEGIN(misc-no-recursion)
  28. namespace Carbon::SemIR {
  29. Formatter::Formatter(const File* sem_ir,
  30. ShouldFormatEntityFn should_format_entity,
  31. Parse::GetTreeAndSubtreesFn get_tree_and_subtrees)
  32. : sem_ir_(sem_ir),
  33. inst_namer_(sem_ir_),
  34. should_format_entity_(should_format_entity),
  35. get_tree_and_subtrees_(get_tree_and_subtrees) {
  36. // Create a placeholder visible chunk and assign it to all instructions that
  37. // don't have a chunk of their own.
  38. auto first_chunk = AddChunkNoFlush(true);
  39. tentative_inst_chunks_.resize(sem_ir_->insts().size(), first_chunk);
  40. if (sem_ir_->parse_tree().tokens().has_dump_sem_ir_ranges()) {
  41. ComputeNodeParents();
  42. }
  43. // Create empty placeholder chunks for instructions that we output lazily.
  44. for (auto lazy_insts :
  45. {sem_ir_->constants().array_ref(),
  46. sem_ir_->inst_blocks().Get(InstBlockId::ImportRefs)}) {
  47. for (auto inst_id : lazy_insts) {
  48. tentative_inst_chunks_[inst_id.index] = AddChunkNoFlush(false);
  49. }
  50. }
  51. // Create a real chunk for the start of the output.
  52. AddChunkNoFlush(true);
  53. }
  54. auto Formatter::Format() -> void {
  55. out_ << "--- " << sem_ir_->filename() << "\n\n";
  56. FormatScopeIfUsed(InstNamer::ScopeId::Constants,
  57. sem_ir_->constants().array_ref());
  58. FormatScopeIfUsed(InstNamer::ScopeId::ImportRefs,
  59. sem_ir_->inst_blocks().Get(InstBlockId::ImportRefs));
  60. out_ << inst_namer_.GetScopeName(InstNamer::ScopeId::File) << " ";
  61. OpenBrace();
  62. // TODO: Handle the case where there are multiple top-level instruction
  63. // blocks. For example, there may be branching in the initializer of a
  64. // global or a type expression.
  65. if (auto block_id = sem_ir_->top_inst_block_id(); block_id.has_value()) {
  66. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::File);
  67. FormatCodeBlock(block_id);
  68. }
  69. CloseBrace();
  70. out_ << '\n';
  71. for (auto [id, _] : sem_ir_->interfaces().enumerate()) {
  72. FormatInterface(id);
  73. }
  74. for (auto [id, _] : sem_ir_->associated_constants().enumerate()) {
  75. FormatAssociatedConstant(id);
  76. }
  77. for (auto [id, _] : sem_ir_->impls().enumerate()) {
  78. FormatImpl(id);
  79. }
  80. for (auto [id, _] : sem_ir_->classes().enumerate()) {
  81. FormatClass(id);
  82. }
  83. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  84. FormatFunction(id);
  85. }
  86. for (auto [id, _] : sem_ir_->specifics().enumerate()) {
  87. FormatSpecific(id);
  88. }
  89. // End-of-file newline.
  90. out_ << "\n";
  91. }
  92. auto Formatter::ComputeNodeParents() -> void {
  93. CARBON_CHECK(node_parents_.empty());
  94. node_parents_.resize(sem_ir_->parse_tree().size(), Parse::NodeId::None);
  95. for (auto n : sem_ir_->parse_tree().postorder()) {
  96. for (auto child : get_tree_and_subtrees_().children(n)) {
  97. node_parents_[child.index] = n;
  98. }
  99. }
  100. }
  101. auto Formatter::Write(llvm::raw_ostream& out) -> void {
  102. FlushChunk();
  103. for (const auto& chunk : output_chunks_) {
  104. if (chunk.include_in_output) {
  105. out << chunk.chunk;
  106. }
  107. }
  108. }
  109. auto Formatter::FlushChunk() -> void {
  110. CARBON_CHECK(output_chunks_.back().chunk.empty());
  111. output_chunks_.back().chunk = std::move(buffer_);
  112. buffer_.clear();
  113. }
  114. auto Formatter::AddChunkNoFlush(bool include_in_output) -> size_t {
  115. CARBON_CHECK(buffer_.empty());
  116. output_chunks_.push_back({.include_in_output = include_in_output});
  117. return output_chunks_.size() - 1;
  118. }
  119. auto Formatter::AddChunk(bool include_in_output) -> size_t {
  120. FlushChunk();
  121. return AddChunkNoFlush(include_in_output);
  122. }
  123. auto Formatter::IncludeChunkInOutput(size_t chunk) -> void {
  124. if (chunk == output_chunks_.size() - 1) {
  125. return;
  126. }
  127. if (auto& current_chunk = output_chunks_.back();
  128. !current_chunk.include_in_output) {
  129. current_chunk.dependencies.push_back(chunk);
  130. return;
  131. }
  132. llvm::SmallVector<size_t> to_add = {chunk};
  133. while (!to_add.empty()) {
  134. auto& chunk = output_chunks_[to_add.pop_back_val()];
  135. if (chunk.include_in_output) {
  136. continue;
  137. }
  138. chunk.include_in_output = true;
  139. to_add.append(chunk.dependencies);
  140. chunk.dependencies.clear();
  141. }
  142. }
  143. auto Formatter::ShouldFormatEntity(InstId decl_id, bool is_definition_start)
  144. -> bool {
  145. if (!decl_id.has_value()) {
  146. return true;
  147. }
  148. if (!should_format_entity_(decl_id)) {
  149. return false;
  150. }
  151. if (!sem_ir_->parse_tree().tokens().has_dump_sem_ir_ranges()) {
  152. return true;
  153. }
  154. // When there are dump ranges, ignore imported instructions.
  155. auto loc_id = sem_ir_->insts().GetCanonicalLocId(decl_id);
  156. if (loc_id.kind() != LocId::Kind::NodeId) {
  157. return false;
  158. }
  159. const auto& tree_and_subtrees = get_tree_and_subtrees_();
  160. // This takes the earliest token from either the node or its first postorder
  161. // child. The first postorder child isn't necessarily the earliest token in
  162. // the subtree (for example, it can miss modifiers), but finding the earliest
  163. // token requires walking *all* children, whereas this approach is
  164. // constant-time.
  165. auto begin_node_id = *tree_and_subtrees.postorder(loc_id.node_id()).begin();
  166. // Non-defining declarations will be associated with a `Decl` node.
  167. // Definitions will have a `DefinitionStart` for which we can use the parent
  168. // to find the `Definition`, giving a range that includes the definition's
  169. // body.
  170. auto end_node_id = loc_id.node_id();
  171. if (is_definition_start) {
  172. end_node_id = node_parents_[end_node_id.index];
  173. }
  174. Lex::InclusiveTokenRange range = {
  175. .begin = sem_ir_->parse_tree().node_token(begin_node_id),
  176. .end = sem_ir_->parse_tree().node_token(end_node_id)};
  177. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(range);
  178. }
  179. auto Formatter::ShouldFormatEntity(const EntityWithParamsBase& entity) -> bool {
  180. return ShouldFormatEntity(entity.latest_decl_id(),
  181. entity.definition_id.has_value());
  182. }
  183. auto Formatter::ShouldFormatInst(InstId inst_id) -> bool {
  184. if (!sem_ir_->parse_tree().tokens().has_dump_sem_ir_ranges()) {
  185. return true;
  186. }
  187. // When there are dump ranges, ignore imported instructions.
  188. auto loc_id = sem_ir_->insts().GetCanonicalLocId(inst_id);
  189. if (loc_id.kind() != LocId::Kind::NodeId) {
  190. return false;
  191. }
  192. auto token = sem_ir_->parse_tree().node_token(loc_id.node_id());
  193. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(
  194. Lex::InclusiveTokenRange{.begin = token, .end = token});
  195. }
  196. auto Formatter::OpenBrace() -> void {
  197. // Put the constant value of an instruction before any braced block, rather
  198. // than at the end.
  199. FormatPendingConstantValue(AddSpace::After);
  200. // Put the imported-from library name before the definition of the entity.
  201. FormatPendingImportedFrom(AddSpace::After);
  202. out_ << '{';
  203. indent_ += 2;
  204. after_open_brace_ = true;
  205. }
  206. auto Formatter::CloseBrace() -> void {
  207. indent_ -= 2;
  208. if (!after_open_brace_) {
  209. Indent();
  210. }
  211. out_ << '}';
  212. after_open_brace_ = false;
  213. }
  214. auto Formatter::Semicolon() -> void {
  215. FormatPendingImportedFrom(AddSpace::Before);
  216. out_ << ';';
  217. }
  218. auto Formatter::Indent(int offset) -> void {
  219. if (after_open_brace_) {
  220. out_ << '\n';
  221. after_open_brace_ = false;
  222. }
  223. out_.indent(indent_ + offset);
  224. }
  225. auto Formatter::IndentLabel() -> void {
  226. CARBON_CHECK(indent_ >= 2);
  227. if (!after_open_brace_) {
  228. out_ << '\n';
  229. }
  230. Indent(-2);
  231. }
  232. auto Formatter::FormatScopeIfUsed(InstNamer::ScopeId scope_id,
  233. llvm::ArrayRef<InstId> block) -> void {
  234. if (block.empty()) {
  235. return;
  236. }
  237. llvm::SaveAndRestore scope(scope_, scope_id);
  238. // Note, we don't use OpenBrace() / CloseBrace() here because we always want
  239. // a newline to avoid misformatting if the first instruction is omitted.
  240. out_ << inst_namer_.GetScopeName(scope_id) << " {\n";
  241. indent_ += 2;
  242. for (const InstId inst_id : block) {
  243. TentativeOutputScope scope(*this, tentative_inst_chunks_[inst_id.index]);
  244. FormatInst(inst_id);
  245. }
  246. out_ << "}\n\n";
  247. indent_ -= 2;
  248. }
  249. auto Formatter::FormatClass(ClassId id) -> void {
  250. const Class& class_info = sem_ir_->classes().Get(id);
  251. if (!ShouldFormatEntity(class_info)) {
  252. return;
  253. }
  254. FormatEntityStart("class", class_info, id);
  255. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  256. if (class_info.scope_id.has_value()) {
  257. out_ << ' ';
  258. OpenBrace();
  259. FormatCodeBlock(class_info.body_block_id);
  260. Indent();
  261. out_ << "complete_type_witness = ";
  262. FormatName(class_info.complete_type_witness_id);
  263. out_ << "\n";
  264. FormatNameScope(class_info.scope_id, "!members:\n");
  265. CloseBrace();
  266. } else {
  267. Semicolon();
  268. }
  269. out_ << '\n';
  270. FormatEntityEnd(class_info.generic_id);
  271. }
  272. auto Formatter::FormatInterface(InterfaceId id) -> void {
  273. const Interface& interface_info = sem_ir_->interfaces().Get(id);
  274. if (!ShouldFormatEntity(interface_info)) {
  275. return;
  276. }
  277. FormatEntityStart("interface", interface_info, id);
  278. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  279. if (interface_info.scope_id.has_value()) {
  280. out_ << ' ';
  281. OpenBrace();
  282. FormatCodeBlock(interface_info.body_block_id);
  283. // Always include the !members label because we always list the witness in
  284. // this section.
  285. IndentLabel();
  286. out_ << "!members:\n";
  287. FormatNameScope(interface_info.scope_id);
  288. Indent();
  289. out_ << "witness = ";
  290. FormatArg(interface_info.associated_entities_id);
  291. out_ << "\n";
  292. CloseBrace();
  293. } else {
  294. Semicolon();
  295. }
  296. out_ << '\n';
  297. FormatEntityEnd(interface_info.generic_id);
  298. }
  299. auto Formatter::FormatAssociatedConstant(AssociatedConstantId id) -> void {
  300. const AssociatedConstant& assoc_const =
  301. sem_ir_->associated_constants().Get(id);
  302. if (!ShouldFormatEntity(assoc_const.decl_id,
  303. /*is_definition_start=*/false)) {
  304. return;
  305. }
  306. FormatEntityStart("assoc_const", assoc_const.decl_id, assoc_const.generic_id,
  307. id);
  308. llvm::SaveAndRestore assoc_const_scope(scope_, inst_namer_.GetScopeFor(id));
  309. out_ << " ";
  310. FormatName(assoc_const.name_id);
  311. out_ << ":! ";
  312. FormatTypeOfInst(assoc_const.decl_id);
  313. if (assoc_const.default_value_id.has_value()) {
  314. out_ << " = ";
  315. FormatArg(assoc_const.default_value_id);
  316. }
  317. out_ << ";\n";
  318. FormatEntityEnd(assoc_const.generic_id);
  319. }
  320. auto Formatter::FormatImpl(ImplId id) -> void {
  321. const Impl& impl_info = sem_ir_->impls().Get(id);
  322. if (!ShouldFormatEntity(impl_info)) {
  323. return;
  324. }
  325. FormatEntityStart("impl", impl_info, id);
  326. llvm::SaveAndRestore impl_scope(scope_, inst_namer_.GetScopeFor(id));
  327. out_ << ": ";
  328. FormatName(impl_info.self_id);
  329. out_ << " as ";
  330. FormatName(impl_info.constraint_id);
  331. if (impl_info.is_complete()) {
  332. out_ << ' ';
  333. OpenBrace();
  334. FormatCodeBlock(impl_info.body_block_id);
  335. // Print the !members label even if the name scope is empty because we
  336. // always list the witness in this section.
  337. IndentLabel();
  338. out_ << "!members:\n";
  339. if (impl_info.scope_id.has_value()) {
  340. FormatNameScope(impl_info.scope_id);
  341. }
  342. Indent();
  343. out_ << "witness = ";
  344. FormatArg(impl_info.witness_id);
  345. out_ << "\n";
  346. CloseBrace();
  347. } else {
  348. Semicolon();
  349. }
  350. out_ << '\n';
  351. FormatEntityEnd(impl_info.generic_id);
  352. }
  353. auto Formatter::FormatFunction(FunctionId id) -> void {
  354. const Function& fn = sem_ir_->functions().Get(id);
  355. if (!ShouldFormatEntity(fn)) {
  356. return;
  357. }
  358. std::string function_start;
  359. switch (fn.virtual_modifier) {
  360. case FunctionFields::VirtualModifier::Virtual:
  361. function_start += "virtual ";
  362. break;
  363. case FunctionFields::VirtualModifier::Abstract:
  364. function_start += "abstract ";
  365. break;
  366. case FunctionFields::VirtualModifier::Impl:
  367. function_start += "impl ";
  368. break;
  369. case FunctionFields::VirtualModifier::None:
  370. break;
  371. }
  372. if (fn.is_extern) {
  373. function_start += "extern ";
  374. }
  375. function_start += "fn";
  376. FormatEntityStart(function_start, fn, id);
  377. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  378. auto return_type_info = ReturnTypeInfo::ForFunction(*sem_ir_, fn);
  379. FormatParamList(fn.call_params_id, return_type_info.is_valid() &&
  380. return_type_info.has_return_slot());
  381. if (fn.builtin_function_kind != BuiltinFunctionKind::None) {
  382. out_ << " = \""
  383. << FormatEscaped(fn.builtin_function_kind.name(),
  384. /*use_hex_escapes=*/true)
  385. << "\"";
  386. }
  387. if (!fn.body_block_ids.empty()) {
  388. out_ << ' ';
  389. OpenBrace();
  390. for (auto block_id : fn.body_block_ids) {
  391. IndentLabel();
  392. FormatLabel(block_id);
  393. out_ << ":\n";
  394. FormatCodeBlock(block_id);
  395. }
  396. CloseBrace();
  397. } else {
  398. Semicolon();
  399. }
  400. out_ << '\n';
  401. FormatEntityEnd(fn.generic_id);
  402. }
  403. auto Formatter::FormatSpecificRegion(const Generic& generic,
  404. const Specific& specific,
  405. GenericInstIndex::Region region,
  406. llvm::StringRef region_name) -> void {
  407. if (!specific.GetValueBlock(region).has_value()) {
  408. return;
  409. }
  410. if (!region_name.empty()) {
  411. IndentLabel();
  412. out_ << "!" << region_name << ":\n";
  413. }
  414. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  415. sem_ir_->inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  416. sem_ir_->inst_blocks().GetOrEmpty(specific.GetValueBlock(region)))) {
  417. Indent();
  418. if (generic_inst_id) {
  419. FormatName(*generic_inst_id);
  420. } else {
  421. out_ << "<missing>";
  422. }
  423. out_ << " => ";
  424. if (specific_inst_id) {
  425. FormatName(*specific_inst_id);
  426. } else {
  427. out_ << "<missing>";
  428. }
  429. out_ << "\n";
  430. }
  431. }
  432. auto Formatter::FormatSpecific(SpecificId id) -> void {
  433. const auto& specific = sem_ir_->specifics().Get(id);
  434. const auto& generic = sem_ir_->generics().Get(specific.generic_id);
  435. if (!should_format_entity_(generic.decl_id)) {
  436. // Omit specifics if we also omitted the generic.
  437. return;
  438. }
  439. if (specific.IsUnresolved()) {
  440. // Omit specifics that were never resolved. Such specifics exist only to
  441. // track the way the arguments were spelled, and that information is
  442. // conveyed entirely by the name of the specific. These specifics may also
  443. // not be referenced by any SemIR that we format, so including them adds
  444. // clutter and possibly emits references to instructions we didn't name.
  445. return;
  446. }
  447. llvm::SaveAndRestore generic_scope(
  448. scope_, inst_namer_.GetScopeFor(specific.generic_id));
  449. out_ << "\n";
  450. out_ << "specific ";
  451. FormatName(id);
  452. out_ << " ";
  453. OpenBrace();
  454. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Declaration,
  455. "");
  456. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Definition,
  457. "definition");
  458. CloseBrace();
  459. out_ << "\n";
  460. }
  461. auto Formatter::FormatGenericStart(llvm::StringRef entity_kind,
  462. GenericId generic_id) -> void {
  463. const auto& generic = sem_ir_->generics().Get(generic_id);
  464. out_ << "\n";
  465. Indent();
  466. out_ << "generic " << entity_kind << " ";
  467. FormatName(generic_id);
  468. llvm::SaveAndRestore generic_scope(scope_,
  469. inst_namer_.GetScopeFor(generic_id));
  470. FormatParamList(generic.bindings_id);
  471. out_ << " ";
  472. OpenBrace();
  473. FormatCodeBlock(generic.decl_block_id);
  474. if (generic.definition_block_id.has_value()) {
  475. IndentLabel();
  476. out_ << "!definition:\n";
  477. FormatCodeBlock(generic.definition_block_id);
  478. }
  479. }
  480. auto Formatter::FormatEntityEnd(GenericId generic_id) -> void {
  481. if (generic_id.has_value()) {
  482. CloseBrace();
  483. out_ << '\n';
  484. }
  485. }
  486. auto Formatter::FormatParamList(InstBlockId params_id, bool has_return_slot)
  487. -> void {
  488. if (!params_id.has_value()) {
  489. // TODO: This happens for imported functions, for which we don't currently
  490. // import the call parameters list.
  491. return;
  492. }
  493. llvm::StringLiteral close = ")";
  494. out_ << "(";
  495. llvm::ListSeparator sep;
  496. for (InstId param_id : sem_ir_->inst_blocks().Get(params_id)) {
  497. auto is_out_param = sem_ir_->insts().Is<OutParam>(param_id);
  498. if (is_out_param) {
  499. // TODO: An input parameter following an output parameter is formatted a
  500. // bit strangely. For example, alternating input and output parameters
  501. // produces:
  502. //
  503. // fn @F(%in1: %t) -> %out1: %t, %in2: %t -> %out2: %t
  504. //
  505. // This doesn't actually happen right now, though.
  506. out_ << std::exchange(close, llvm::StringLiteral(""));
  507. out_ << " -> ";
  508. } else {
  509. out_ << sep;
  510. }
  511. if (!param_id.has_value()) {
  512. out_ << "invalid";
  513. continue;
  514. }
  515. // Don't include the name of the return slot parameter if the function
  516. // doesn't have a return slot; the name won't be used for anything in that
  517. // case.
  518. // TODO: Should the call parameter even exist in that case? There isn't a
  519. // corresponding argument in a `call` instruction.
  520. if (!is_out_param || has_return_slot) {
  521. FormatName(param_id);
  522. out_ << ": ";
  523. }
  524. FormatTypeOfInst(param_id);
  525. }
  526. out_ << close;
  527. }
  528. auto Formatter::FormatCodeBlock(InstBlockId block_id) -> void {
  529. for (const InstId inst_id : sem_ir_->inst_blocks().GetOrEmpty(block_id)) {
  530. FormatInst(inst_id);
  531. }
  532. }
  533. auto Formatter::FormatTrailingBlock(InstBlockId block_id) -> void {
  534. out_ << ' ';
  535. OpenBrace();
  536. FormatCodeBlock(block_id);
  537. CloseBrace();
  538. }
  539. auto Formatter::FormatNameScope(NameScopeId id, llvm::StringRef label) -> void {
  540. const auto& scope = sem_ir_->name_scopes().Get(id);
  541. if (scope.entries().empty() && scope.extended_scopes().empty() &&
  542. scope.import_ir_scopes().empty() && !scope.is_cpp_scope() &&
  543. !scope.has_error()) {
  544. // Name scope is empty.
  545. return;
  546. }
  547. if (!label.empty()) {
  548. IndentLabel();
  549. out_ << label;
  550. }
  551. for (auto [name_id, result] : scope.entries()) {
  552. Indent();
  553. out_ << ".";
  554. FormatName(name_id);
  555. switch (result.access_kind()) {
  556. case AccessKind::Public:
  557. break;
  558. case AccessKind::Protected:
  559. out_ << " [protected]";
  560. break;
  561. case AccessKind::Private:
  562. out_ << " [private]";
  563. break;
  564. }
  565. out_ << " = ";
  566. if (result.is_poisoned()) {
  567. out_ << "<poisoned>";
  568. } else {
  569. FormatName(result.is_found() ? result.target_inst_id() : InstId::None);
  570. }
  571. out_ << "\n";
  572. }
  573. for (auto extended_scope_id : scope.extended_scopes()) {
  574. Indent();
  575. out_ << "extend ";
  576. FormatName(extended_scope_id);
  577. out_ << "\n";
  578. }
  579. // This is used to cluster all "Core//prelude/..." imports, but not
  580. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  581. // add or remove an unused prelude file, but is intended to still show the
  582. // existence of indirect imports.
  583. bool has_prelude_components = false;
  584. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  585. auto label = GetImportIRLabel(import_ir_id);
  586. if (label.starts_with("Core//prelude/")) {
  587. if (has_prelude_components) {
  588. // Only print the existence once.
  589. continue;
  590. } else {
  591. has_prelude_components = true;
  592. label = "Core//prelude/...";
  593. }
  594. }
  595. Indent();
  596. out_ << "import " << label << "\n";
  597. }
  598. if (scope.is_cpp_scope()) {
  599. Indent();
  600. out_ << "import Cpp//...\n";
  601. }
  602. if (scope.has_error()) {
  603. Indent();
  604. out_ << "has_error\n";
  605. }
  606. }
  607. auto Formatter::FormatInst(InstId inst_id, Inst inst) -> void {
  608. CARBON_KIND_SWITCH(inst) {
  609. #define CARBON_SEM_IR_INST_KIND(InstT) \
  610. case CARBON_KIND(InstT typed_inst): { \
  611. FormatInst(inst_id, typed_inst); \
  612. break; \
  613. }
  614. #include "toolchain/sem_ir/inst_kind.def"
  615. }
  616. }
  617. auto Formatter::FormatInst(InstId inst_id, ImportRefUnloaded inst) -> void {
  618. Indent();
  619. FormatInstLhs(inst_id, inst);
  620. out_ << ImportRefUnloaded::Kind.ir_name();
  621. FormatInstRhs(inst);
  622. out_ << "\n";
  623. }
  624. auto Formatter::FormatInst(InstId inst_id) -> void {
  625. if (!ShouldFormatInst(inst_id)) {
  626. return;
  627. }
  628. if (!inst_id.has_value()) {
  629. Indent();
  630. out_ << "none\n";
  631. return;
  632. }
  633. FormatInst(inst_id, sem_ir_->insts().GetWithAttachedType(inst_id));
  634. }
  635. auto Formatter::FormatPendingImportedFrom(AddSpace space_where) -> void {
  636. if (pending_imported_from_.empty()) {
  637. return;
  638. }
  639. if (space_where == AddSpace::Before) {
  640. out_ << ' ';
  641. }
  642. out_ << "[from \"" << FormatEscaped(pending_imported_from_) << "\"]";
  643. if (space_where == AddSpace::After) {
  644. out_ << ' ';
  645. }
  646. pending_imported_from_ = llvm::StringRef();
  647. }
  648. auto Formatter::FormatPendingConstantValue(AddSpace space_where) -> void {
  649. if (pending_constant_value_ == ConstantId::NotConstant) {
  650. return;
  651. }
  652. if (space_where == AddSpace::Before) {
  653. out_ << ' ';
  654. }
  655. out_ << '[';
  656. if (pending_constant_value_.has_value()) {
  657. switch (sem_ir_->constant_values().GetDependence(pending_constant_value_)) {
  658. case ConstantDependence::None:
  659. out_ << "concrete";
  660. break;
  661. case ConstantDependence::PeriodSelf:
  662. out_ << "symbolic_self";
  663. break;
  664. // TODO: Consider renaming this. This will cause a lot of SemIR churn.
  665. case ConstantDependence::Checked:
  666. out_ << "symbolic";
  667. break;
  668. case ConstantDependence::Template:
  669. out_ << "template";
  670. break;
  671. }
  672. if (!pending_constant_value_is_self_) {
  673. out_ << " = ";
  674. FormatConstant(pending_constant_value_);
  675. }
  676. } else {
  677. out_ << pending_constant_value_;
  678. }
  679. out_ << ']';
  680. if (space_where == AddSpace::After) {
  681. out_ << ' ';
  682. }
  683. pending_constant_value_ = ConstantId::NotConstant;
  684. }
  685. auto Formatter::FormatInstLhs(InstId inst_id, Inst inst) -> void {
  686. switch (inst.kind().value_kind()) {
  687. case InstValueKind::Typed:
  688. FormatName(inst_id);
  689. out_ << ": ";
  690. switch (GetExprCategory(*sem_ir_, inst_id)) {
  691. case ExprCategory::NotExpr:
  692. case ExprCategory::Error:
  693. case ExprCategory::Value:
  694. case ExprCategory::Mixed:
  695. break;
  696. case ExprCategory::DurableRef:
  697. case ExprCategory::EphemeralRef:
  698. out_ << "ref ";
  699. break;
  700. case ExprCategory::Initializing:
  701. out_ << "init ";
  702. break;
  703. }
  704. FormatTypeOfInst(inst_id);
  705. out_ << " = ";
  706. break;
  707. case InstValueKind::None:
  708. break;
  709. }
  710. }
  711. auto Formatter::FormatInstLhs(InstId inst_id, ImportCppDecl /*inst*/) -> void {
  712. FormatName(inst_id);
  713. out_ << " = ";
  714. }
  715. auto Formatter::FormatInstLhs(InstId inst_id, ImportDecl /*inst*/) -> void {
  716. FormatName(inst_id);
  717. out_ << " = ";
  718. }
  719. auto Formatter::FormatInstLhs(InstId inst_id, ImportRefUnloaded /*inst*/)
  720. -> void {
  721. FormatName(inst_id);
  722. out_ << " = ";
  723. }
  724. auto Formatter::FormatInstLhs(InstId inst_id, ImplWitnessTable /*inst*/)
  725. -> void {
  726. FormatName(inst_id);
  727. out_ << " = ";
  728. }
  729. auto Formatter::FormatInstRhs(BindSymbolicName inst) -> void {
  730. // A BindSymbolicName with no value is a purely symbolic binding, such as
  731. // the `Self` in an interface. Don't print out `none` for the value.
  732. if (inst.value_id.has_value()) {
  733. FormatArgs(inst.entity_name_id, inst.value_id);
  734. } else {
  735. FormatArgs(inst.entity_name_id);
  736. }
  737. }
  738. auto Formatter::FormatInstRhs(BlockArg inst) -> void {
  739. out_ << " ";
  740. FormatLabel(inst.block_id);
  741. }
  742. auto Formatter::FormatInstRhs(Namespace inst) -> void {
  743. if (inst.import_id.has_value()) {
  744. FormatArgs(inst.import_id, inst.name_scope_id);
  745. } else {
  746. FormatArgs(inst.name_scope_id);
  747. }
  748. }
  749. auto Formatter::FormatInst(InstId /*inst_id*/, BranchIf inst) -> void {
  750. if (!in_terminator_sequence_) {
  751. Indent();
  752. }
  753. out_ << "if ";
  754. FormatName(inst.cond_id);
  755. out_ << " " << Branch::Kind.ir_name() << " ";
  756. FormatLabel(inst.target_id);
  757. out_ << " else ";
  758. in_terminator_sequence_ = true;
  759. }
  760. auto Formatter::FormatInst(InstId /*inst_id*/, BranchWithArg inst) -> void {
  761. if (!in_terminator_sequence_) {
  762. Indent();
  763. }
  764. out_ << BranchWithArg::Kind.ir_name() << " ";
  765. FormatLabel(inst.target_id);
  766. out_ << "(";
  767. FormatName(inst.arg_id);
  768. out_ << ")\n";
  769. in_terminator_sequence_ = false;
  770. }
  771. auto Formatter::FormatInst(InstId /*inst_id*/, Branch inst) -> void {
  772. if (!in_terminator_sequence_) {
  773. Indent();
  774. }
  775. out_ << Branch::Kind.ir_name() << " ";
  776. FormatLabel(inst.target_id);
  777. out_ << "\n";
  778. in_terminator_sequence_ = false;
  779. }
  780. auto Formatter::FormatInstRhs(Call inst) -> void {
  781. out_ << " ";
  782. FormatArg(inst.callee_id);
  783. if (!inst.args_id.has_value()) {
  784. out_ << "(<none>)";
  785. return;
  786. }
  787. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  788. auto return_info = ReturnTypeInfo::ForType(*sem_ir_, inst.type_id);
  789. if (!return_info.is_valid()) {
  790. out_ << "(<invalid return info>)";
  791. return;
  792. }
  793. bool has_return_slot = return_info.has_return_slot();
  794. InstId return_slot_arg_id = InstId::None;
  795. if (has_return_slot) {
  796. return_slot_arg_id = args.back();
  797. args = args.drop_back();
  798. }
  799. llvm::ListSeparator sep;
  800. out_ << '(';
  801. for (auto inst_id : args) {
  802. out_ << sep;
  803. FormatArg(inst_id);
  804. }
  805. out_ << ')';
  806. if (has_return_slot) {
  807. FormatReturnSlotArg(return_slot_arg_id);
  808. }
  809. }
  810. auto Formatter::FormatInstRhs(ArrayInit inst) -> void {
  811. FormatArgs(inst.inits_id);
  812. FormatReturnSlotArg(inst.dest_id);
  813. }
  814. auto Formatter::Formatter::FormatInstRhs(InitializeFrom inst) -> void {
  815. FormatArgs(inst.src_id);
  816. FormatReturnSlotArg(inst.dest_id);
  817. }
  818. auto Formatter::FormatInstRhs(ValueParam inst) -> void {
  819. FormatArgs(inst.index);
  820. // Omit pretty_name because it's an implementation detail of
  821. // pretty-printing.
  822. }
  823. auto Formatter::FormatInstRhs(RefParam inst) -> void {
  824. FormatArgs(inst.index);
  825. // Omit pretty_name because it's an implementation detail of
  826. // pretty-printing.
  827. }
  828. auto Formatter::FormatInstRhs(OutParam inst) -> void {
  829. FormatArgs(inst.index);
  830. // Omit pretty_name because it's an implementation detail of
  831. // pretty-printing.
  832. }
  833. auto Formatter::FormatInstRhs(ReturnExpr ret) -> void {
  834. FormatArgs(ret.expr_id);
  835. if (ret.dest_id.has_value()) {
  836. FormatReturnSlotArg(ret.dest_id);
  837. }
  838. }
  839. auto Formatter::FormatInstRhs(ReturnSlot inst) -> void {
  840. // Omit inst.type_inst_id because it's not semantically significant.
  841. FormatArgs(inst.storage_id);
  842. }
  843. auto Formatter::FormatInstRhs(ReturnSlotPattern /*inst*/) -> void {
  844. // No-op because type_id is the only semantically significant field,
  845. // and it's handled separately.
  846. }
  847. auto Formatter::FormatInstRhs(StructInit init) -> void {
  848. FormatArgs(init.elements_id);
  849. FormatReturnSlotArg(init.dest_id);
  850. }
  851. auto Formatter::FormatInstRhs(TupleInit init) -> void {
  852. FormatArgs(init.elements_id);
  853. FormatReturnSlotArg(init.dest_id);
  854. }
  855. auto Formatter::FormatInstRhs(FunctionDecl inst) -> void {
  856. FormatArgs(inst.function_id);
  857. llvm::SaveAndRestore class_scope(scope_,
  858. inst_namer_.GetScopeFor(inst.function_id));
  859. FormatTrailingBlock(
  860. sem_ir_->functions().Get(inst.function_id).pattern_block_id);
  861. FormatTrailingBlock(inst.decl_block_id);
  862. }
  863. auto Formatter::FormatInstRhs(ClassDecl inst) -> void {
  864. FormatArgs(inst.class_id);
  865. llvm::SaveAndRestore class_scope(scope_,
  866. inst_namer_.GetScopeFor(inst.class_id));
  867. FormatTrailingBlock(sem_ir_->classes().Get(inst.class_id).pattern_block_id);
  868. FormatTrailingBlock(inst.decl_block_id);
  869. }
  870. auto Formatter::FormatInstRhs(ImplDecl inst) -> void {
  871. FormatArgs(inst.impl_id);
  872. llvm::SaveAndRestore class_scope(scope_,
  873. inst_namer_.GetScopeFor(inst.impl_id));
  874. FormatTrailingBlock(sem_ir_->impls().Get(inst.impl_id).pattern_block_id);
  875. FormatTrailingBlock(inst.decl_block_id);
  876. }
  877. auto Formatter::FormatInstRhs(InterfaceDecl inst) -> void {
  878. FormatArgs(inst.interface_id);
  879. llvm::SaveAndRestore class_scope(scope_,
  880. inst_namer_.GetScopeFor(inst.interface_id));
  881. FormatTrailingBlock(
  882. sem_ir_->interfaces().Get(inst.interface_id).pattern_block_id);
  883. FormatTrailingBlock(inst.decl_block_id);
  884. }
  885. auto Formatter::FormatInstRhs(AssociatedConstantDecl inst) -> void {
  886. FormatArgs(inst.assoc_const_id);
  887. llvm::SaveAndRestore assoc_const_scope(
  888. scope_, inst_namer_.GetScopeFor(inst.assoc_const_id));
  889. FormatTrailingBlock(inst.decl_block_id);
  890. }
  891. auto Formatter::FormatInstRhs(IntValue inst) -> void {
  892. out_ << " ";
  893. sem_ir_->ints()
  894. .Get(inst.int_id)
  895. .print(out_, sem_ir_->types().IsSignedInt(inst.type_id));
  896. }
  897. auto Formatter::FormatInstRhs(FloatLiteral inst) -> void {
  898. llvm::SmallVector<char, 16> buffer;
  899. sem_ir_->floats().Get(inst.float_id).toString(buffer);
  900. out_ << " " << buffer;
  901. }
  902. auto Formatter::FormatInstRhs(ImportCppDecl /*inst*/) -> void {
  903. out_ << " ";
  904. OpenBrace();
  905. for (ImportCpp import_cpp : sem_ir_->import_cpps().array_ref()) {
  906. Indent();
  907. out_ << "import Cpp \""
  908. << FormatEscaped(
  909. sem_ir_->string_literal_values().Get(import_cpp.library_id))
  910. << "\"\n";
  911. }
  912. CloseBrace();
  913. }
  914. auto Formatter::FormatImportRefRhs(ImportIRInstId import_ir_inst_id,
  915. EntityNameId entity_name_id,
  916. llvm::StringLiteral loaded_label) -> void {
  917. out_ << " ";
  918. auto import_ir_inst = sem_ir_->import_ir_insts().Get(import_ir_inst_id);
  919. FormatArg(import_ir_inst.ir_id());
  920. out_ << ", ";
  921. if (entity_name_id.has_value()) {
  922. // Prefer to show the entity name when possible.
  923. FormatArg(entity_name_id);
  924. } else {
  925. // Show a name based on the location when possible, or the numeric
  926. // instruction as a last resort.
  927. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  928. auto loc_id =
  929. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  930. switch (loc_id.kind()) {
  931. case LocId::Kind::None: {
  932. out_ << import_ir_inst.inst_id() << " [no loc]";
  933. break;
  934. }
  935. case LocId::Kind::ImportIRInstId: {
  936. // TODO: Probably don't want to format each indirection, but maybe
  937. // reuse GetCanonicalImportIRInst?
  938. out_ << import_ir_inst.inst_id() << " [indirect]";
  939. break;
  940. }
  941. case LocId::Kind::NodeId: {
  942. // Formats a NodeId from the import.
  943. const auto& tree = import_ir.sem_ir->parse_tree();
  944. auto token = tree.node_token(loc_id.node_id());
  945. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  946. << tree.tokens().GetColumnNumber(token);
  947. break;
  948. }
  949. case LocId::Kind::InstId:
  950. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  951. }
  952. }
  953. out_ << ", " << loaded_label;
  954. }
  955. auto Formatter::FormatInstRhs(ImportRefLoaded inst) -> void {
  956. FormatImportRefRhs(inst.import_ir_inst_id, inst.entity_name_id, "loaded");
  957. }
  958. auto Formatter::FormatInstRhs(ImportRefUnloaded inst) -> void {
  959. FormatImportRefRhs(inst.import_ir_inst_id, inst.entity_name_id, "unloaded");
  960. }
  961. auto Formatter::FormatInstRhs(InstValue inst) -> void {
  962. out_ << ' ';
  963. OpenBrace();
  964. // TODO: Should we use a more compact representation in the case where the
  965. // inst is a SpliceBlock?
  966. FormatInst(inst.inst_id);
  967. CloseBrace();
  968. }
  969. auto Formatter::FormatInstRhs(NameBindingDecl inst) -> void {
  970. FormatTrailingBlock(inst.pattern_block_id);
  971. }
  972. auto Formatter::FormatInstRhs(SpliceBlock inst) -> void {
  973. FormatArgs(inst.result_id);
  974. FormatTrailingBlock(inst.block_id);
  975. }
  976. auto Formatter::FormatInstRhs(WhereExpr inst) -> void {
  977. FormatArgs(inst.period_self_id);
  978. FormatTrailingBlock(inst.requirements_id);
  979. }
  980. auto Formatter::FormatInstRhs(StructType inst) -> void {
  981. out_ << " {";
  982. llvm::ListSeparator sep;
  983. for (auto field : sem_ir_->struct_type_fields().Get(inst.fields_id)) {
  984. out_ << sep << ".";
  985. FormatName(field.name_id);
  986. out_ << ": ";
  987. FormatInstAsType(field.type_inst_id);
  988. }
  989. out_ << "}";
  990. }
  991. auto Formatter::FormatArg(EntityNameId id) -> void {
  992. if (!id.has_value()) {
  993. out_ << "_";
  994. return;
  995. }
  996. const auto& info = sem_ir_->entity_names().Get(id);
  997. FormatName(info.name_id);
  998. if (info.bind_index().has_value()) {
  999. out_ << ", " << info.bind_index().index;
  1000. }
  1001. if (info.is_template) {
  1002. out_ << ", template";
  1003. }
  1004. }
  1005. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1006. const auto& info = sem_ir_->facet_types().Get(id);
  1007. // Nothing output to indicate that this is a facet type since this is only
  1008. // used as the argument to a `facet_type` instruction.
  1009. out_ << "<";
  1010. llvm::ListSeparator sep(" & ");
  1011. if (info.extend_constraints.empty()) {
  1012. out_ << "type";
  1013. } else {
  1014. for (auto interface : info.extend_constraints) {
  1015. out_ << sep;
  1016. FormatName(interface.interface_id);
  1017. if (interface.specific_id.has_value()) {
  1018. out_ << ", ";
  1019. FormatName(interface.specific_id);
  1020. }
  1021. }
  1022. }
  1023. if (info.other_requirements || !info.self_impls_constraints.empty() ||
  1024. !info.rewrite_constraints.empty()) {
  1025. out_ << " where ";
  1026. llvm::ListSeparator and_sep(" and ");
  1027. if (!info.self_impls_constraints.empty()) {
  1028. out_ << and_sep << ".Self impls ";
  1029. llvm::ListSeparator amp_sep(" & ");
  1030. for (auto interface : info.self_impls_constraints) {
  1031. out_ << amp_sep;
  1032. FormatName(interface.interface_id);
  1033. if (interface.specific_id.has_value()) {
  1034. out_ << ", ";
  1035. FormatName(interface.specific_id);
  1036. }
  1037. }
  1038. }
  1039. for (auto rewrite : info.rewrite_constraints) {
  1040. out_ << and_sep;
  1041. FormatArg(rewrite.lhs_id);
  1042. out_ << " = ";
  1043. FormatArg(rewrite.rhs_id);
  1044. }
  1045. if (info.other_requirements) {
  1046. out_ << and_sep << "TODO";
  1047. }
  1048. }
  1049. out_ << ">";
  1050. }
  1051. auto Formatter::FormatArg(ImportIRId id) -> void {
  1052. if (id.has_value()) {
  1053. out_ << GetImportIRLabel(id);
  1054. } else {
  1055. out_ << id;
  1056. }
  1057. }
  1058. auto Formatter::FormatArg(IntId id) -> void {
  1059. // We don't know the signedness to use here. Default to unsigned.
  1060. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  1061. }
  1062. auto Formatter::FormatArg(NameScopeId id) -> void {
  1063. OpenBrace();
  1064. FormatNameScope(id);
  1065. CloseBrace();
  1066. }
  1067. auto Formatter::FormatArg(InstBlockId id) -> void {
  1068. if (!id.has_value()) {
  1069. out_ << "invalid";
  1070. return;
  1071. }
  1072. out_ << '(';
  1073. llvm::ListSeparator sep;
  1074. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1075. out_ << sep;
  1076. FormatArg(inst_id);
  1077. }
  1078. out_ << ')';
  1079. }
  1080. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1081. FormatArg(static_cast<InstBlockId>(id));
  1082. }
  1083. auto Formatter::FormatArg(RealId id) -> void {
  1084. // TODO: Format with a `.` when the exponent is near zero.
  1085. const auto& real = sem_ir_->reals().Get(id);
  1086. real.mantissa.print(out_, /*isSigned=*/false);
  1087. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1088. }
  1089. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1090. out_ << '"'
  1091. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1092. /*use_hex_escapes=*/true)
  1093. << '"';
  1094. }
  1095. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1096. out_ << " to ";
  1097. FormatArg(dest_id);
  1098. }
  1099. auto Formatter::FormatName(NameId id) -> void {
  1100. out_ << sem_ir_->names().GetFormatted(id);
  1101. }
  1102. auto Formatter::FormatName(InstId id) -> void {
  1103. if (id.has_value()) {
  1104. IncludeChunkInOutput(tentative_inst_chunks_[id.index]);
  1105. }
  1106. out_ << inst_namer_.GetNameFor(scope_, id);
  1107. }
  1108. auto Formatter::FormatName(SpecificId id) -> void {
  1109. const auto& specific = sem_ir_->specifics().Get(id);
  1110. FormatName(specific.generic_id);
  1111. FormatArg(specific.args_id);
  1112. }
  1113. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1114. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1115. FormatName(interface.interface_id);
  1116. if (interface.specific_id.has_value()) {
  1117. out_ << ", ";
  1118. FormatArg(interface.specific_id);
  1119. }
  1120. }
  1121. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1122. out_ << inst_namer_.GetLabelFor(scope_, id);
  1123. }
  1124. auto Formatter::FormatConstant(ConstantId id) -> void {
  1125. if (!id.has_value()) {
  1126. out_ << "<not constant>";
  1127. return;
  1128. }
  1129. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1130. FormatName(inst_id);
  1131. // For an attached constant, also list the unattached constant.
  1132. if (id.is_symbolic() && sem_ir_->constant_values()
  1133. .GetSymbolicConstant(id)
  1134. .generic_id.has_value()) {
  1135. // TODO: Skip printing this if it's the same as `inst_id`.
  1136. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1137. out_ << " (";
  1138. FormatName(unattached_inst_id);
  1139. out_ << ")";
  1140. }
  1141. }
  1142. auto Formatter::FormatInstAsType(InstId id) -> void {
  1143. if (!id.has_value()) {
  1144. out_ << "invalid";
  1145. return;
  1146. }
  1147. // Types are formatted in the `constants` scope because they typically refer
  1148. // to constants.
  1149. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1150. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1151. const_id.has_value()) {
  1152. FormatConstant(const_id);
  1153. } else {
  1154. // Type instruction didn't have a constant value. Fall back to printing
  1155. // the instruction name.
  1156. FormatArg(id);
  1157. }
  1158. }
  1159. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1160. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1161. if (!type_id.has_value()) {
  1162. out_ << "invalid";
  1163. return;
  1164. }
  1165. // Types are formatted in the `constants` scope because they typically refer
  1166. // to constants.
  1167. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1168. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1169. }
  1170. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1171. CARBON_CHECK(id.has_value(),
  1172. "Callers are responsible for checking `id.has_value`");
  1173. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1174. CARBON_CHECK(import_ir.library_id().has_value());
  1175. auto package_id = import_ir.package_id();
  1176. llvm::StringRef package_name =
  1177. package_id.AsIdentifierId().has_value()
  1178. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1179. : package_id.AsSpecialName();
  1180. llvm::StringRef library_name =
  1181. (import_ir.library_id() != LibraryNameId::Default)
  1182. ? import_ir.string_literal_values().Get(
  1183. import_ir.library_id().AsStringLiteralValueId())
  1184. : "default";
  1185. return llvm::formatv("{0}//{1}", package_name, library_name);
  1186. }
  1187. } // namespace Carbon::SemIR
  1188. // NOLINTEND(misc-no-recursion)