formatter.cpp 40 KB

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