formatter.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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, is_poisoned] : scope.entries()) {
  536. if (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(AbsoluteInstBlockId id) -> void {
  1040. FormatArg(static_cast<InstBlockId>(id));
  1041. }
  1042. auto FormatArg(RealId id) -> void {
  1043. // TODO: Format with a `.` when the exponent is near zero.
  1044. const auto& real = sem_ir_->reals().Get(id);
  1045. real.mantissa.print(out_, /*isSigned=*/false);
  1046. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1047. }
  1048. auto FormatArg(StringLiteralValueId id) -> void {
  1049. out_ << '"';
  1050. out_.write_escaped(sem_ir_->string_literal_values().Get(id),
  1051. /*UseHexEscapes=*/true);
  1052. out_ << '"';
  1053. }
  1054. auto FormatArg(TypeId id) -> void { FormatType(id); }
  1055. auto FormatArg(TypeBlockId id) -> void {
  1056. out_ << '(';
  1057. llvm::ListSeparator sep;
  1058. for (auto type_id : sem_ir_->type_blocks().Get(id)) {
  1059. out_ << sep;
  1060. FormatArg(type_id);
  1061. }
  1062. out_ << ')';
  1063. }
  1064. auto FormatReturnSlotArg(InstId dest_id) -> void {
  1065. out_ << " to ";
  1066. FormatArg(dest_id);
  1067. }
  1068. // `FormatName` is used when we need the name from an id. Most id types use
  1069. // equivalent name formatting from InstNamer, although there are a few special
  1070. // formats below.
  1071. template <typename IdT>
  1072. auto FormatName(IdT id) -> void {
  1073. out_ << inst_namer_->GetNameFor(id);
  1074. }
  1075. auto FormatName(NameId id) -> void {
  1076. out_ << sem_ir_->names().GetFormatted(id);
  1077. }
  1078. auto FormatName(InstId id) -> void {
  1079. if (id.is_valid()) {
  1080. IncludeChunkInOutput(tentative_inst_chunks_[id.index]);
  1081. }
  1082. out_ << inst_namer_->GetNameFor(scope_, id);
  1083. }
  1084. auto FormatName(AbsoluteInstId id) -> void {
  1085. FormatName(static_cast<InstId>(id));
  1086. }
  1087. auto FormatName(SpecificId id) -> void {
  1088. const auto& specific = sem_ir_->specifics().Get(id);
  1089. FormatName(specific.generic_id);
  1090. FormatArg(specific.args_id);
  1091. }
  1092. auto FormatLabel(InstBlockId id) -> void {
  1093. out_ << inst_namer_->GetLabelFor(scope_, id);
  1094. }
  1095. auto FormatConstant(ConstantId id) -> void {
  1096. if (!id.is_valid()) {
  1097. out_ << "<not constant>";
  1098. return;
  1099. }
  1100. // For a symbolic constant in a generic, list the constant value in the
  1101. // generic first, and the canonical constant second.
  1102. if (id.is_symbolic()) {
  1103. const auto& symbolic_constant =
  1104. sem_ir_->constant_values().GetSymbolicConstant(id);
  1105. if (symbolic_constant.generic_id.is_valid()) {
  1106. const auto& generic =
  1107. sem_ir_->generics().Get(symbolic_constant.generic_id);
  1108. FormatName(sem_ir_->inst_blocks().Get(generic.GetEvalBlock(
  1109. symbolic_constant.index
  1110. .region()))[symbolic_constant.index.index()]);
  1111. out_ << " (";
  1112. FormatName(sem_ir_->constant_values().GetInstId(id));
  1113. out_ << ")";
  1114. return;
  1115. }
  1116. }
  1117. FormatName(sem_ir_->constant_values().GetInstId(id));
  1118. }
  1119. auto FormatType(TypeId id) -> void {
  1120. if (!id.is_valid()) {
  1121. out_ << "invalid";
  1122. } else {
  1123. // Types are formatted in the `constants` scope because they only refer to
  1124. // constants.
  1125. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1126. FormatConstant(sem_ir_->types().GetConstantId(id));
  1127. }
  1128. }
  1129. // Returns the label for the indicated IR.
  1130. auto GetImportIRLabel(ImportIRId id) -> std::string {
  1131. CARBON_CHECK(id.is_valid(),
  1132. "GetImportIRLabel should only be called where we a valid ID.");
  1133. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1134. CARBON_CHECK(import_ir.library_id().is_valid());
  1135. llvm::StringRef package_name =
  1136. import_ir.package_id().is_valid()
  1137. ? import_ir.identifiers().Get(import_ir.package_id())
  1138. : "Main";
  1139. llvm::StringRef library_name =
  1140. (import_ir.library_id() != LibraryNameId::Default)
  1141. ? import_ir.string_literal_values().Get(
  1142. import_ir.library_id().AsStringLiteralValueId())
  1143. : "default";
  1144. return llvm::formatv("{0}//{1}", package_name, library_name);
  1145. }
  1146. const File* sem_ir_;
  1147. InstNamer* const inst_namer_;
  1148. Formatter::ShouldFormatEntityFn should_format_entity_;
  1149. // The output stream buffer.
  1150. std::string buffer_;
  1151. // The output stream.
  1152. llvm::raw_string_ostream out_ = llvm::raw_string_ostream(buffer_);
  1153. // Chunks of output text that we have created so far.
  1154. llvm::SmallVector<OutputChunk> output_chunks_;
  1155. // The current scope that we are formatting within. References to names in
  1156. // this scope will not have a `@scope.` prefix added.
  1157. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  1158. // Whether we are formatting in a terminator sequence, that is, a sequence of
  1159. // branches at the end of a block. The entirety of a terminator sequence is
  1160. // formatted on a single line, despite being multiple instructions.
  1161. bool in_terminator_sequence_ = false;
  1162. // The indent depth to use for new instructions.
  1163. int indent_;
  1164. // Whether we are currently formatting immediately after an open brace. If so,
  1165. // a newline will be inserted before the next line indent.
  1166. bool after_open_brace_ = false;
  1167. // The constant value of the current instruction, if it has one that has not
  1168. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  1169. // there is nothing to print.
  1170. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  1171. // Whether `pending_constant_value_`'s instruction is the same as the
  1172. // instruction currently being printed. If true, only the phase of the
  1173. // constant is printed, and the value is omitted.
  1174. bool pending_constant_value_is_self_ = false;
  1175. // The name of the IR file from which the current entity was imported, if it
  1176. // was imported and no file has been printed yet. This is printed before the
  1177. // first open brace or the semicolon in the entity declaration.
  1178. llvm::StringRef pending_imported_from_;
  1179. // Indexes of chunks of output that should be included when an instruction is
  1180. // referenced, indexed by the instruction's index. This is resized in advance
  1181. // to the correct size.
  1182. llvm::SmallVector<size_t, 0> tentative_inst_chunks_;
  1183. };
  1184. Formatter::Formatter(const File* sem_ir,
  1185. ShouldFormatEntityFn should_format_entity)
  1186. : sem_ir_(sem_ir),
  1187. should_format_entity_(should_format_entity),
  1188. inst_namer_(sem_ir) {}
  1189. Formatter::~Formatter() = default;
  1190. auto Formatter::Print(llvm::raw_ostream& out) -> void {
  1191. FormatterImpl formatter(sem_ir_, &inst_namer_, should_format_entity_,
  1192. /*indent=*/0);
  1193. formatter.Format();
  1194. formatter.Write(out);
  1195. }
  1196. } // namespace Carbon::SemIR
  1197. // NOLINTEND(misc-no-recursion)