formatter.cpp 39 KB

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