formatter.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  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.is_cpp_scope() &&
  564. !scope.has_error()) {
  565. // Name scope is empty.
  566. return;
  567. }
  568. if (!label.empty()) {
  569. IndentLabel();
  570. out_ << label;
  571. }
  572. for (auto [name_id, result] : scope.entries()) {
  573. Indent();
  574. out_ << ".";
  575. FormatName(name_id);
  576. switch (result.access_kind()) {
  577. case SemIR::AccessKind::Public:
  578. break;
  579. case SemIR::AccessKind::Protected:
  580. out_ << " [protected]";
  581. break;
  582. case SemIR::AccessKind::Private:
  583. out_ << " [private]";
  584. break;
  585. }
  586. out_ << " = ";
  587. if (result.is_poisoned()) {
  588. out_ << "<poisoned>";
  589. } else {
  590. FormatName(result.is_found() ? result.target_inst_id() : InstId::None);
  591. }
  592. out_ << "\n";
  593. }
  594. for (auto extended_scope_id : scope.extended_scopes()) {
  595. Indent();
  596. out_ << "extend ";
  597. FormatName(extended_scope_id);
  598. out_ << "\n";
  599. }
  600. // This is used to cluster all "Core//prelude/..." imports, but not
  601. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  602. // add or remove an unused prelude file, but is intended to still show the
  603. // existence of indirect imports.
  604. bool has_prelude_components = false;
  605. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  606. auto label = GetImportIRLabel(import_ir_id);
  607. if (label.starts_with("Core//prelude/")) {
  608. if (has_prelude_components) {
  609. // Only print the existence once.
  610. continue;
  611. } else {
  612. has_prelude_components = true;
  613. label = "Core//prelude/...";
  614. }
  615. }
  616. Indent();
  617. out_ << "import " << label << "\n";
  618. }
  619. if (scope.is_cpp_scope()) {
  620. Indent();
  621. out_ << "import Cpp//...\n";
  622. }
  623. if (scope.has_error()) {
  624. Indent();
  625. out_ << "has_error\n";
  626. }
  627. }
  628. // Prints a single instruction.
  629. auto FormatInst(InstId inst_id) -> void {
  630. if (!inst_id.has_value()) {
  631. Indent();
  632. out_ << "none\n";
  633. return;
  634. }
  635. FormatInst(inst_id, sem_ir_->insts().Get(inst_id));
  636. }
  637. auto FormatInst(InstId inst_id, Inst inst) -> void {
  638. CARBON_KIND_SWITCH(inst) {
  639. #define CARBON_SEM_IR_INST_KIND(InstT) \
  640. case CARBON_KIND(InstT typed_inst): { \
  641. FormatInst(inst_id, typed_inst); \
  642. break; \
  643. }
  644. #include "toolchain/sem_ir/inst_kind.def"
  645. }
  646. }
  647. template <typename InstT>
  648. auto FormatInst(InstId inst_id, InstT inst) -> void {
  649. Indent();
  650. FormatInstLhs(inst_id, inst);
  651. out_ << InstT::Kind.ir_name();
  652. pending_constant_value_ = sem_ir_->constant_values().Get(inst_id);
  653. pending_constant_value_is_self_ =
  654. sem_ir_->constant_values().GetInstIdIfValid(pending_constant_value_) ==
  655. inst_id;
  656. FormatInstRhs(inst);
  657. FormatPendingConstantValue(AddSpace::Before);
  658. out_ << "\n";
  659. }
  660. // Don't print a constant for ImportRefUnloaded.
  661. auto FormatInst(InstId inst_id, ImportRefUnloaded inst) -> void {
  662. Indent();
  663. FormatInstLhs(inst_id, inst);
  664. out_ << ImportRefUnloaded::Kind.ir_name();
  665. FormatInstRhs(inst);
  666. out_ << "\n";
  667. }
  668. // If there is a pending library name that the current instruction was
  669. // imported from, print it now and clear it out.
  670. auto FormatPendingImportedFrom(AddSpace space_where) -> void {
  671. if (pending_imported_from_.empty()) {
  672. return;
  673. }
  674. if (space_where == AddSpace::Before) {
  675. out_ << ' ';
  676. }
  677. out_ << "[from \"" << FormatEscaped(pending_imported_from_) << "\"]";
  678. if (space_where == AddSpace::After) {
  679. out_ << ' ';
  680. }
  681. pending_imported_from_ = llvm::StringRef();
  682. }
  683. // If there is a pending constant value attached to the current instruction,
  684. // print it now and clear it out. The constant value gets printed before the
  685. // first braced block argument, or at the end of the instruction if there are
  686. // no such arguments.
  687. auto FormatPendingConstantValue(AddSpace space_where) -> void {
  688. if (pending_constant_value_ == ConstantId::NotConstant) {
  689. return;
  690. }
  691. if (space_where == AddSpace::Before) {
  692. out_ << ' ';
  693. }
  694. out_ << '[';
  695. if (pending_constant_value_.has_value()) {
  696. switch (
  697. sem_ir_->constant_values().GetDependence(pending_constant_value_)) {
  698. case ConstantDependence::None:
  699. out_ << "concrete";
  700. break;
  701. case ConstantDependence::PeriodSelf:
  702. out_ << "symbolic_self";
  703. break;
  704. // TODO: Consider renaming this. This will cause a lot of SemIR churn.
  705. case ConstantDependence::Checked:
  706. out_ << "symbolic";
  707. break;
  708. case ConstantDependence::Template:
  709. out_ << "template";
  710. break;
  711. }
  712. if (!pending_constant_value_is_self_) {
  713. out_ << " = ";
  714. FormatConstant(pending_constant_value_);
  715. }
  716. } else {
  717. out_ << pending_constant_value_;
  718. }
  719. out_ << ']';
  720. if (space_where == AddSpace::After) {
  721. out_ << ' ';
  722. }
  723. pending_constant_value_ = ConstantId::NotConstant;
  724. }
  725. auto FormatInstLhs(InstId inst_id, Inst inst) -> void {
  726. switch (inst.kind().value_kind()) {
  727. case InstValueKind::Typed:
  728. FormatName(inst_id);
  729. out_ << ": ";
  730. switch (GetExprCategory(*sem_ir_, inst_id)) {
  731. case ExprCategory::NotExpr:
  732. case ExprCategory::Error:
  733. case ExprCategory::Value:
  734. case ExprCategory::Mixed:
  735. break;
  736. case ExprCategory::DurableRef:
  737. case ExprCategory::EphemeralRef:
  738. out_ << "ref ";
  739. break;
  740. case ExprCategory::Initializing:
  741. out_ << "init ";
  742. break;
  743. }
  744. FormatType(inst.type_id());
  745. out_ << " = ";
  746. break;
  747. case InstValueKind::None:
  748. break;
  749. }
  750. }
  751. // Format ImportCppDecl name.
  752. auto FormatInstLhs(InstId inst_id, ImportCppDecl /*inst*/) -> void {
  753. FormatName(inst_id);
  754. out_ << " = ";
  755. }
  756. // Format ImportDecl with its name.
  757. auto FormatInstLhs(InstId inst_id, ImportDecl /*inst*/) -> void {
  758. FormatName(inst_id);
  759. out_ << " = ";
  760. }
  761. // Print ImportRefUnloaded with type-like semantics even though it lacks a
  762. // type_id.
  763. auto FormatInstLhs(InstId inst_id, ImportRefUnloaded /*inst*/) -> void {
  764. FormatName(inst_id);
  765. out_ << " = ";
  766. }
  767. template <typename InstT>
  768. auto FormatInstRhs(InstT inst) -> void {
  769. // By default, an instruction has a comma-separated argument list.
  770. using Info = Internal::InstLikeTypeInfo<InstT>;
  771. if constexpr (Info::NumArgs == 2) {
  772. // Several instructions have a second operand that's a specific ID. We
  773. // don't include it in the argument list if there is no corresponding
  774. // specific, that is, when we're not in a generic context.
  775. if constexpr (std::is_same_v<typename Info::template ArgType<1>,
  776. SemIR::SpecificId>) {
  777. if (!Info::template Get<1>(inst).has_value()) {
  778. FormatArgs(Info::template Get<0>(inst));
  779. return;
  780. }
  781. }
  782. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  783. } else if constexpr (Info::NumArgs == 1) {
  784. FormatArgs(Info::template Get<0>(inst));
  785. } else {
  786. FormatArgs();
  787. }
  788. }
  789. auto FormatInstRhs(BindSymbolicName inst) -> void {
  790. // A BindSymbolicName with no value is a purely symbolic binding, such as
  791. // the `Self` in an interface. Don't print out `none` for the value.
  792. if (inst.value_id.has_value()) {
  793. FormatArgs(inst.entity_name_id, inst.value_id);
  794. } else {
  795. FormatArgs(inst.entity_name_id);
  796. }
  797. }
  798. auto FormatInstRhs(BlockArg inst) -> void {
  799. out_ << " ";
  800. FormatLabel(inst.block_id);
  801. }
  802. auto FormatInstRhs(Namespace inst) -> void {
  803. if (inst.import_id.has_value()) {
  804. FormatArgs(inst.import_id, inst.name_scope_id);
  805. } else {
  806. FormatArgs(inst.name_scope_id);
  807. }
  808. }
  809. auto FormatInst(InstId /*inst_id*/, BranchIf inst) -> void {
  810. if (!in_terminator_sequence_) {
  811. Indent();
  812. }
  813. out_ << "if ";
  814. FormatName(inst.cond_id);
  815. out_ << " " << Branch::Kind.ir_name() << " ";
  816. FormatLabel(inst.target_id);
  817. out_ << " else ";
  818. in_terminator_sequence_ = true;
  819. }
  820. auto FormatInst(InstId /*inst_id*/, BranchWithArg inst) -> void {
  821. if (!in_terminator_sequence_) {
  822. Indent();
  823. }
  824. out_ << BranchWithArg::Kind.ir_name() << " ";
  825. FormatLabel(inst.target_id);
  826. out_ << "(";
  827. FormatName(inst.arg_id);
  828. out_ << ")\n";
  829. in_terminator_sequence_ = false;
  830. }
  831. auto FormatInst(InstId /*inst_id*/, Branch inst) -> void {
  832. if (!in_terminator_sequence_) {
  833. Indent();
  834. }
  835. out_ << Branch::Kind.ir_name() << " ";
  836. FormatLabel(inst.target_id);
  837. out_ << "\n";
  838. in_terminator_sequence_ = false;
  839. }
  840. auto FormatInstRhs(Call inst) -> void {
  841. out_ << " ";
  842. FormatArg(inst.callee_id);
  843. if (!inst.args_id.has_value()) {
  844. out_ << "(<none>)";
  845. return;
  846. }
  847. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  848. auto return_info = ReturnTypeInfo::ForType(*sem_ir_, inst.type_id);
  849. if (!return_info.is_valid()) {
  850. out_ << "(<invalid return info>)";
  851. return;
  852. }
  853. bool has_return_slot = return_info.has_return_slot();
  854. InstId return_slot_arg_id = InstId::None;
  855. if (has_return_slot) {
  856. return_slot_arg_id = args.back();
  857. args = args.drop_back();
  858. }
  859. llvm::ListSeparator sep;
  860. out_ << '(';
  861. for (auto inst_id : args) {
  862. out_ << sep;
  863. FormatArg(inst_id);
  864. }
  865. out_ << ')';
  866. if (has_return_slot) {
  867. FormatReturnSlotArg(return_slot_arg_id);
  868. }
  869. }
  870. auto FormatInstRhs(ArrayInit inst) -> void {
  871. FormatArgs(inst.inits_id);
  872. FormatReturnSlotArg(inst.dest_id);
  873. }
  874. auto FormatInstRhs(InitializeFrom inst) -> void {
  875. FormatArgs(inst.src_id);
  876. FormatReturnSlotArg(inst.dest_id);
  877. }
  878. auto FormatInstRhs(ValueParam inst) -> void {
  879. FormatArgs(inst.index);
  880. // Omit pretty_name because it's an implementation detail of
  881. // pretty-printing.
  882. }
  883. auto FormatInstRhs(RefParam inst) -> void {
  884. FormatArgs(inst.index);
  885. // Omit pretty_name because it's an implementation detail of
  886. // pretty-printing.
  887. }
  888. auto FormatInstRhs(OutParam inst) -> void {
  889. FormatArgs(inst.index);
  890. // Omit pretty_name because it's an implementation detail of
  891. // pretty-printing.
  892. }
  893. auto FormatInstRhs(ReturnExpr ret) -> void {
  894. FormatArgs(ret.expr_id);
  895. if (ret.dest_id.has_value()) {
  896. FormatReturnSlotArg(ret.dest_id);
  897. }
  898. }
  899. auto FormatInstRhs(ReturnSlot inst) -> void {
  900. // Omit inst.type_inst_id because it's not semantically significant.
  901. FormatArgs(inst.storage_id);
  902. }
  903. auto FormatInstRhs(ReturnSlotPattern /*inst*/) -> void {
  904. // No-op because type_id is the only semantically significant field,
  905. // and it's handled separately.
  906. }
  907. auto FormatInstRhs(StructInit init) -> void {
  908. FormatArgs(init.elements_id);
  909. FormatReturnSlotArg(init.dest_id);
  910. }
  911. auto FormatInstRhs(TupleInit init) -> void {
  912. FormatArgs(init.elements_id);
  913. FormatReturnSlotArg(init.dest_id);
  914. }
  915. auto FormatInstRhs(FunctionDecl inst) -> void {
  916. FormatArgs(inst.function_id);
  917. llvm::SaveAndRestore class_scope(
  918. scope_, inst_namer_->GetScopeFor(inst.function_id));
  919. FormatTrailingBlock(
  920. sem_ir_->functions().Get(inst.function_id).pattern_block_id);
  921. FormatTrailingBlock(inst.decl_block_id);
  922. }
  923. auto FormatInstRhs(ClassDecl inst) -> void {
  924. FormatArgs(inst.class_id);
  925. llvm::SaveAndRestore class_scope(scope_,
  926. inst_namer_->GetScopeFor(inst.class_id));
  927. FormatTrailingBlock(sem_ir_->classes().Get(inst.class_id).pattern_block_id);
  928. FormatTrailingBlock(inst.decl_block_id);
  929. }
  930. auto FormatInstRhs(ImplDecl inst) -> void {
  931. FormatArgs(inst.impl_id);
  932. llvm::SaveAndRestore class_scope(scope_,
  933. inst_namer_->GetScopeFor(inst.impl_id));
  934. FormatTrailingBlock(sem_ir_->impls().Get(inst.impl_id).pattern_block_id);
  935. FormatTrailingBlock(inst.decl_block_id);
  936. }
  937. auto FormatInstRhs(InterfaceDecl inst) -> void {
  938. FormatArgs(inst.interface_id);
  939. llvm::SaveAndRestore class_scope(
  940. scope_, inst_namer_->GetScopeFor(inst.interface_id));
  941. FormatTrailingBlock(
  942. sem_ir_->interfaces().Get(inst.interface_id).pattern_block_id);
  943. FormatTrailingBlock(inst.decl_block_id);
  944. }
  945. auto FormatInstRhs(AssociatedConstantDecl inst) -> void {
  946. FormatArgs(inst.assoc_const_id);
  947. llvm::SaveAndRestore assoc_const_scope(
  948. scope_, inst_namer_->GetScopeFor(inst.assoc_const_id));
  949. FormatTrailingBlock(inst.decl_block_id);
  950. }
  951. auto FormatInstRhs(IntValue inst) -> void {
  952. out_ << " ";
  953. sem_ir_->ints()
  954. .Get(inst.int_id)
  955. .print(out_, sem_ir_->types().IsSignedInt(inst.type_id));
  956. }
  957. auto FormatInstRhs(FloatLiteral inst) -> void {
  958. llvm::SmallVector<char, 16> buffer;
  959. sem_ir_->floats().Get(inst.float_id).toString(buffer);
  960. out_ << " " << buffer;
  961. }
  962. // Format the metadata in File for `import Cpp`.
  963. auto FormatInstRhs(ImportCppDecl /*inst*/) -> void {
  964. out_ << " ";
  965. OpenBrace();
  966. for (ImportCpp import_cpp : sem_ir_->import_cpps().array_ref()) {
  967. Indent();
  968. out_ << "import Cpp \""
  969. << FormatEscaped(
  970. sem_ir_->string_literal_values().Get(import_cpp.library_id))
  971. << "\"\n";
  972. }
  973. CloseBrace();
  974. }
  975. auto FormatImportRefRhs(ImportIRInstId import_ir_inst_id,
  976. EntityNameId entity_name_id,
  977. llvm::StringLiteral loaded_label) -> void {
  978. out_ << " ";
  979. auto import_ir_inst = sem_ir_->import_ir_insts().Get(import_ir_inst_id);
  980. FormatArg(import_ir_inst.ir_id);
  981. out_ << ", ";
  982. if (entity_name_id.has_value()) {
  983. // Prefer to show the entity name when possible.
  984. FormatArg(entity_name_id);
  985. } else {
  986. // Show a name based on the location when possible, or the numeric
  987. // instruction as a last resort.
  988. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id);
  989. auto loc_id = import_ir.sem_ir->insts().GetLocId(import_ir_inst.inst_id);
  990. if (!loc_id.has_value()) {
  991. out_ << import_ir_inst.inst_id << " [no loc]";
  992. } else if (loc_id.is_import_ir_inst_id()) {
  993. // TODO: Probably don't want to format each indirection, but maybe reuse
  994. // GetCanonicalImportIRInst?
  995. out_ << import_ir_inst.inst_id << " [indirect]";
  996. } else if (loc_id.is_node_id()) {
  997. // Formats a NodeId from the import.
  998. const auto& tree = import_ir.sem_ir->parse_tree();
  999. auto token = tree.node_token(loc_id.node_id());
  1000. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1001. << tree.tokens().GetColumnNumber(token);
  1002. } else {
  1003. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1004. }
  1005. }
  1006. out_ << ", " << loaded_label;
  1007. }
  1008. auto FormatInstRhs(ImportRefLoaded inst) -> void {
  1009. FormatImportRefRhs(inst.import_ir_inst_id, inst.entity_name_id, "loaded");
  1010. }
  1011. auto FormatInstRhs(ImportRefUnloaded inst) -> void {
  1012. FormatImportRefRhs(inst.import_ir_inst_id, inst.entity_name_id, "unloaded");
  1013. }
  1014. auto FormatInstRhs(NameBindingDecl inst) -> void {
  1015. FormatTrailingBlock(inst.pattern_block_id);
  1016. }
  1017. auto FormatInstRhs(SpliceBlock inst) -> void {
  1018. FormatArgs(inst.result_id);
  1019. FormatTrailingBlock(inst.block_id);
  1020. }
  1021. auto FormatInstRhs(WhereExpr inst) -> void {
  1022. FormatArgs(inst.period_self_id);
  1023. FormatTrailingBlock(inst.requirements_id);
  1024. }
  1025. auto FormatInstRhs(StructType inst) -> void {
  1026. out_ << " {";
  1027. llvm::ListSeparator sep;
  1028. for (auto field : sem_ir_->struct_type_fields().Get(inst.fields_id)) {
  1029. out_ << sep << ".";
  1030. FormatName(field.name_id);
  1031. out_ << ": ";
  1032. FormatType(field.type_id);
  1033. }
  1034. out_ << "}";
  1035. }
  1036. auto FormatArgs() -> void {}
  1037. template <typename... Args>
  1038. auto FormatArgs(Args... args) -> void {
  1039. out_ << ' ';
  1040. llvm::ListSeparator sep;
  1041. ((out_ << sep, FormatArg(args)), ...);
  1042. }
  1043. // FormatArg variants handling printing instruction arguments. Several things
  1044. // provide equivalent behavior with `FormatName`, so we provide that as the
  1045. // default.
  1046. template <typename IdT>
  1047. auto FormatArg(IdT id) -> void {
  1048. FormatName(id);
  1049. }
  1050. auto FormatArg(BoolValue v) -> void { out_ << v; }
  1051. auto FormatArg(EntityNameId id) -> void {
  1052. const auto& info = sem_ir_->entity_names().Get(id);
  1053. FormatName(info.name_id);
  1054. if (info.bind_index().has_value()) {
  1055. out_ << ", " << info.bind_index().index;
  1056. }
  1057. if (info.is_template) {
  1058. out_ << ", template";
  1059. }
  1060. }
  1061. auto FormatArg(FacetTypeId id) -> void {
  1062. const auto& info = sem_ir_->facet_types().Get(id);
  1063. // Nothing output to indicate that this is a facet type since this is only
  1064. // used as the argument to a `facet_type` instruction.
  1065. out_ << "<";
  1066. llvm::ListSeparator sep(" & ");
  1067. if (info.impls_constraints.empty()) {
  1068. out_ << "type";
  1069. } else {
  1070. for (auto interface : info.impls_constraints) {
  1071. out_ << sep;
  1072. FormatName(interface.interface_id);
  1073. if (interface.specific_id.has_value()) {
  1074. out_ << ", ";
  1075. FormatName(interface.specific_id);
  1076. }
  1077. }
  1078. }
  1079. if (info.other_requirements || !info.rewrite_constraints.empty()) {
  1080. // TODO: Include specifics.
  1081. out_ << " where ";
  1082. llvm::ListSeparator and_sep(" and ");
  1083. for (auto rewrite : info.rewrite_constraints) {
  1084. out_ << and_sep;
  1085. FormatConstant(rewrite.lhs_const_id);
  1086. out_ << " = ";
  1087. FormatConstant(rewrite.rhs_const_id);
  1088. }
  1089. if (info.other_requirements) {
  1090. out_ << and_sep << "TODO";
  1091. }
  1092. }
  1093. out_ << ">";
  1094. }
  1095. auto FormatArg(IntKind k) -> void { k.Print(out_); }
  1096. auto FormatArg(FloatKind k) -> void { k.Print(out_); }
  1097. auto FormatArg(ImportIRId id) -> void {
  1098. if (id.has_value()) {
  1099. out_ << GetImportIRLabel(id);
  1100. } else {
  1101. out_ << id;
  1102. }
  1103. }
  1104. auto FormatArg(IntId id) -> void {
  1105. // We don't know the signedness to use here. Default to unsigned.
  1106. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  1107. }
  1108. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  1109. auto FormatArg(CallParamIndex index) -> void { out_ << index; }
  1110. auto FormatArg(NameScopeId id) -> void {
  1111. OpenBrace();
  1112. FormatNameScope(id);
  1113. CloseBrace();
  1114. }
  1115. auto FormatArg(InstBlockId id) -> void {
  1116. if (!id.has_value()) {
  1117. out_ << "invalid";
  1118. return;
  1119. }
  1120. out_ << '(';
  1121. llvm::ListSeparator sep;
  1122. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1123. out_ << sep;
  1124. FormatArg(inst_id);
  1125. }
  1126. out_ << ')';
  1127. }
  1128. auto FormatArg(AbsoluteInstBlockId id) -> void {
  1129. FormatArg(static_cast<InstBlockId>(id));
  1130. }
  1131. auto FormatArg(RealId id) -> void {
  1132. // TODO: Format with a `.` when the exponent is near zero.
  1133. const auto& real = sem_ir_->reals().Get(id);
  1134. real.mantissa.print(out_, /*isSigned=*/false);
  1135. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1136. }
  1137. auto FormatArg(StringLiteralValueId id) -> void {
  1138. out_ << '"'
  1139. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1140. /*use_hex_escapes=*/true)
  1141. << '"';
  1142. }
  1143. auto FormatArg(TypeId id) -> void { FormatType(id); }
  1144. auto FormatArg(TypeBlockId id) -> void {
  1145. out_ << '(';
  1146. llvm::ListSeparator sep;
  1147. for (auto type_id : sem_ir_->type_blocks().Get(id)) {
  1148. out_ << sep;
  1149. FormatArg(type_id);
  1150. }
  1151. out_ << ')';
  1152. }
  1153. auto FormatReturnSlotArg(InstId dest_id) -> void {
  1154. out_ << " to ";
  1155. FormatArg(dest_id);
  1156. }
  1157. // `FormatName` is used when we need the name from an id. Most id types use
  1158. // equivalent name formatting from InstNamer, although there are a few special
  1159. // formats below.
  1160. template <typename IdT>
  1161. auto FormatName(IdT id) -> void {
  1162. out_ << inst_namer_->GetNameFor(id);
  1163. }
  1164. auto FormatName(NameId id) -> void {
  1165. out_ << sem_ir_->names().GetFormatted(id);
  1166. }
  1167. auto FormatName(InstId id) -> void {
  1168. if (id.has_value()) {
  1169. IncludeChunkInOutput(tentative_inst_chunks_[id.index]);
  1170. }
  1171. out_ << inst_namer_->GetNameFor(scope_, id);
  1172. }
  1173. auto FormatName(AbsoluteInstId id) -> void {
  1174. FormatName(static_cast<InstId>(id));
  1175. }
  1176. auto FormatName(DestInstId id) -> void {
  1177. FormatName(static_cast<InstId>(id));
  1178. }
  1179. auto FormatName(SpecificId id) -> void {
  1180. const auto& specific = sem_ir_->specifics().Get(id);
  1181. FormatName(specific.generic_id);
  1182. FormatArg(specific.args_id);
  1183. }
  1184. auto FormatLabel(InstBlockId id) -> void {
  1185. out_ << inst_namer_->GetLabelFor(scope_, id);
  1186. }
  1187. auto FormatConstant(ConstantId id) -> void {
  1188. if (!id.has_value()) {
  1189. out_ << "<not constant>";
  1190. return;
  1191. }
  1192. // For a symbolic constant in a generic, list the constant value in the
  1193. // generic first, and the canonical constant second.
  1194. if (id.is_symbolic()) {
  1195. const auto& symbolic_constant =
  1196. sem_ir_->constant_values().GetSymbolicConstant(id);
  1197. if (symbolic_constant.generic_id.has_value()) {
  1198. const auto& generic =
  1199. sem_ir_->generics().Get(symbolic_constant.generic_id);
  1200. FormatName(sem_ir_->inst_blocks().Get(generic.GetEvalBlock(
  1201. symbolic_constant.index
  1202. .region()))[symbolic_constant.index.index()]);
  1203. out_ << " (";
  1204. FormatName(sem_ir_->constant_values().GetInstId(id));
  1205. out_ << ")";
  1206. return;
  1207. }
  1208. }
  1209. FormatName(sem_ir_->constant_values().GetInstId(id));
  1210. }
  1211. auto FormatType(TypeId id) -> void {
  1212. if (!id.has_value()) {
  1213. out_ << "invalid";
  1214. } else {
  1215. // Types are formatted in the `constants` scope because they only refer to
  1216. // constants.
  1217. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1218. FormatConstant(sem_ir_->types().GetConstantId(id));
  1219. }
  1220. }
  1221. // Returns the label for the indicated IR.
  1222. auto GetImportIRLabel(ImportIRId id) -> std::string {
  1223. CARBON_CHECK(id.has_value(),
  1224. "Callers are responsible for checking `id.has_value`");
  1225. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1226. CARBON_CHECK(import_ir.library_id().has_value());
  1227. auto package_id = import_ir.package_id();
  1228. llvm::StringRef package_name =
  1229. package_id.AsIdentifierId().has_value()
  1230. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1231. : package_id.AsSpecialName();
  1232. llvm::StringRef library_name =
  1233. (import_ir.library_id() != LibraryNameId::Default)
  1234. ? import_ir.string_literal_values().Get(
  1235. import_ir.library_id().AsStringLiteralValueId())
  1236. : "default";
  1237. return llvm::formatv("{0}//{1}", package_name, library_name);
  1238. }
  1239. const File* sem_ir_;
  1240. InstNamer* const inst_namer_;
  1241. Formatter::ShouldFormatEntityFn should_format_entity_;
  1242. // The output stream buffer.
  1243. std::string buffer_;
  1244. // The output stream.
  1245. llvm::raw_string_ostream out_ = llvm::raw_string_ostream(buffer_);
  1246. // Chunks of output text that we have created so far.
  1247. llvm::SmallVector<OutputChunk> output_chunks_;
  1248. // The current scope that we are formatting within. References to names in
  1249. // this scope will not have a `@scope.` prefix added.
  1250. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  1251. // Whether we are formatting in a terminator sequence, that is, a sequence of
  1252. // branches at the end of a block. The entirety of a terminator sequence is
  1253. // formatted on a single line, despite being multiple instructions.
  1254. bool in_terminator_sequence_ = false;
  1255. // The indent depth to use for new instructions.
  1256. int indent_;
  1257. // Whether we are currently formatting immediately after an open brace. If so,
  1258. // a newline will be inserted before the next line indent.
  1259. bool after_open_brace_ = false;
  1260. // The constant value of the current instruction, if it has one that has not
  1261. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  1262. // there is nothing to print.
  1263. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  1264. // Whether `pending_constant_value_`'s instruction is the same as the
  1265. // instruction currently being printed. If true, only the phase of the
  1266. // constant is printed, and the value is omitted.
  1267. bool pending_constant_value_is_self_ = false;
  1268. // The name of the IR file from which the current entity was imported, if it
  1269. // was imported and no file has been printed yet. This is printed before the
  1270. // first open brace or the semicolon in the entity declaration.
  1271. llvm::StringRef pending_imported_from_;
  1272. // Indexes of chunks of output that should be included when an instruction is
  1273. // referenced, indexed by the instruction's index. This is resized in advance
  1274. // to the correct size.
  1275. llvm::SmallVector<size_t, 0> tentative_inst_chunks_;
  1276. };
  1277. Formatter::Formatter(const File* sem_ir,
  1278. ShouldFormatEntityFn should_format_entity)
  1279. : sem_ir_(sem_ir),
  1280. should_format_entity_(should_format_entity),
  1281. inst_namer_(sem_ir) {}
  1282. Formatter::~Formatter() = default;
  1283. auto Formatter::Print(llvm::raw_ostream& out) -> void {
  1284. FormatterImpl formatter(sem_ir_, &inst_namer_, should_format_entity_,
  1285. /*indent=*/0);
  1286. formatter.Format();
  1287. formatter.Write(out);
  1288. }
  1289. } // namespace Carbon::SemIR
  1290. // NOLINTEND(misc-no-recursion)