formatter.cpp 47 KB

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