formatter.cpp 44 KB

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