formatter.cpp 38 KB

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