formatter.cpp 45 KB

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