formatter.cpp 42 KB

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