formatter.cpp 41 KB

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