formatter.cpp 41 KB

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