formatter.cpp 46 KB

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