formatter.cpp 41 KB

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