formatter.cpp 40 KB

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