formatter.cpp 39 KB

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