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