formatter.cpp 40 KB

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