formatter.cpp 41 KB

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