formatter.cpp 41 KB

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