formatter.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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 "common/ostream.h"
  6. #include "llvm/ADT/Sequence.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "llvm/Support/SaveAndRestore.h"
  9. #include "toolchain/base/kind_switch.h"
  10. #include "toolchain/base/shared_value_stores.h"
  11. #include "toolchain/lex/tokenized_buffer.h"
  12. #include "toolchain/parse/tree.h"
  13. #include "toolchain/sem_ir/builtin_function_kind.h"
  14. #include "toolchain/sem_ir/entity_with_params_base.h"
  15. #include "toolchain/sem_ir/function.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/inst_namer.h"
  18. #include "toolchain/sem_ir/name_scope.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::SemIR {
  21. // Formatter for printing textual Semantics IR.
  22. class FormatterImpl {
  23. public:
  24. explicit FormatterImpl(const File* sem_ir, InstNamer* inst_namer,
  25. Formatter::ShouldFormatEntityFn should_format_entity,
  26. int indent)
  27. : sem_ir_(sem_ir),
  28. inst_namer_(inst_namer),
  29. should_format_entity_(should_format_entity),
  30. indent_(indent) {
  31. // Create the first chunk and assign it to all instructions that don't have
  32. // a chunk of their own.
  33. auto first_chunk = AddChunkNoFlush(true);
  34. tentative_inst_chunks_.resize(sem_ir_->insts().size(), first_chunk);
  35. }
  36. // Prints the SemIR.
  37. //
  38. // Constants are printed first and may be referenced by later sections,
  39. // including file-scoped instructions. The file scope may contain entity
  40. // declarations which are defined later, such as classes.
  41. auto Format() -> void {
  42. out_ << "--- " << sem_ir_->filename() << "\n\n";
  43. FormatScopeIfUsed(InstNamer::ScopeId::Constants,
  44. sem_ir_->constants().array_ref());
  45. FormatScopeIfUsed(InstNamer::ScopeId::ImportRefs,
  46. sem_ir_->inst_blocks().Get(InstBlockId::ImportRefs));
  47. out_ << inst_namer_->GetScopeName(InstNamer::ScopeId::File) << " ";
  48. OpenBrace();
  49. // TODO: Handle the case where there are multiple top-level instruction
  50. // blocks. For example, there may be branching in the initializer of a
  51. // global or a type expression.
  52. if (auto block_id = sem_ir_->top_inst_block_id(); block_id.is_valid()) {
  53. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::File);
  54. FormatCodeBlock(block_id);
  55. }
  56. CloseBrace();
  57. out_ << '\n';
  58. for (int i : llvm::seq(sem_ir_->interfaces().size())) {
  59. FormatInterface(InterfaceId(i));
  60. }
  61. for (int i : llvm::seq(sem_ir_->impls().size())) {
  62. FormatImpl(ImplId(i));
  63. }
  64. for (int i : llvm::seq(sem_ir_->classes().size())) {
  65. FormatClass(ClassId(i));
  66. }
  67. for (int i : llvm::seq(sem_ir_->functions().size())) {
  68. FormatFunction(FunctionId(i));
  69. }
  70. for (int i : llvm::seq(sem_ir_->specifics().size())) {
  71. FormatSpecific(SpecificId(i));
  72. }
  73. // End-of-file newline.
  74. out_ << "\n";
  75. }
  76. // Write buffered output to the given stream.
  77. auto Write(llvm::raw_ostream& out) -> void {
  78. FlushChunk();
  79. for (const auto& chunk : output_chunks_) {
  80. if (chunk.include_in_output) {
  81. out << chunk.chunk;
  82. }
  83. }
  84. }
  85. private:
  86. enum class AddSpace : bool { Before, After };
  87. // A chunk of the buffered output. Chunks of the output, such as constant
  88. // values, are buffered until we reach the end of formatting so that we can
  89. // decide whether to include them based on whether they are referenced.
  90. struct OutputChunk {
  91. // Whether this chunk is known to be included in the output.
  92. bool include_in_output;
  93. // The textual contents of this chunk.
  94. std::string chunk = std::string();
  95. // Chunks that should be included in the output if this one is.
  96. llvm::SmallVector<size_t> dependencies = {};
  97. };
  98. // A scope in which output should be buffered because we don't yet know
  99. // whether to include it in the final formatted SemIR.
  100. struct TentativeOutputScope {
  101. explicit TentativeOutputScope(FormatterImpl& f) : formatter(f) {
  102. index = formatter.AddChunk(false);
  103. }
  104. ~TentativeOutputScope() {
  105. auto next_index = formatter.AddChunk(true);
  106. CARBON_CHECK(next_index == index + 1, "Nested TentativeOutputScope");
  107. }
  108. FormatterImpl& formatter;
  109. size_t index;
  110. };
  111. // Flushes the buffered output to the current chunk.
  112. auto FlushChunk() -> void {
  113. CARBON_CHECK(output_chunks_.back().chunk.empty());
  114. output_chunks_.back().chunk = std::move(buffer_);
  115. buffer_.clear();
  116. }
  117. // Adds a new chunk to the output. Does not flush existing output, so should
  118. // only be called if there is no buffered output.
  119. auto AddChunkNoFlush(bool include_in_output) -> size_t {
  120. CARBON_CHECK(buffer_.empty());
  121. output_chunks_.push_back({.include_in_output = include_in_output});
  122. return output_chunks_.size() - 1;
  123. }
  124. // Flushes the current chunk and add a new chunk to the output.
  125. auto AddChunk(bool include_in_output) -> size_t {
  126. FlushChunk();
  127. return AddChunkNoFlush(include_in_output);
  128. }
  129. // Marks the given chunk as being included in the output if the current chunk
  130. // is.
  131. auto IncludeChunkInOutput(size_t chunk) -> void {
  132. if (chunk == output_chunks_.size() - 1) {
  133. return;
  134. }
  135. if (auto& current_chunk = output_chunks_.back();
  136. !current_chunk.include_in_output) {
  137. current_chunk.dependencies.push_back(chunk);
  138. return;
  139. }
  140. llvm::SmallVector<size_t> to_add = {chunk};
  141. while (!to_add.empty()) {
  142. auto& chunk = output_chunks_[to_add.pop_back_val()];
  143. if (chunk.include_in_output) {
  144. continue;
  145. }
  146. chunk.include_in_output = true;
  147. to_add.append(chunk.dependencies);
  148. chunk.dependencies.clear();
  149. }
  150. }
  151. // Determines whether the specified entity should be included in the formatted
  152. // output.
  153. auto ShouldFormatEntity(const EntityWithParamsBase& entity) -> bool {
  154. if (!entity.latest_decl_id().is_valid()) {
  155. return true;
  156. }
  157. return should_format_entity_(entity.latest_decl_id());
  158. }
  159. // Begins a braced block. Writes an open brace, and prepares to insert a
  160. // newline after it if the braced block is non-empty.
  161. auto OpenBrace() -> void {
  162. // Put the constant value of an instruction before any braced block, rather
  163. // than at the end.
  164. FormatPendingConstantValue(AddSpace::After);
  165. // Put the imported-from library name before the definition of the entity.
  166. FormatPendingImportedFrom(AddSpace::After);
  167. out_ << '{';
  168. indent_ += 2;
  169. after_open_brace_ = true;
  170. }
  171. // Ends a braced block by writing a close brace.
  172. auto CloseBrace() -> void {
  173. indent_ -= 2;
  174. if (!after_open_brace_) {
  175. Indent();
  176. }
  177. out_ << '}';
  178. after_open_brace_ = false;
  179. }
  180. auto Semicolon() -> void {
  181. FormatPendingImportedFrom(AddSpace::Before);
  182. out_ << ';';
  183. }
  184. // Adds beginning-of-line indentation. If we're at the start of a braced
  185. // block, first starts a new line.
  186. auto Indent(int offset = 0) -> void {
  187. if (after_open_brace_) {
  188. out_ << '\n';
  189. after_open_brace_ = false;
  190. }
  191. out_.indent(indent_ + offset);
  192. }
  193. // Adds beginning-of-label indentation. This is one level less than normal
  194. // indentation. Labels also get a preceding blank line unless they're at the
  195. // start of a block.
  196. auto IndentLabel() -> void {
  197. CARBON_CHECK(indent_ >= 2);
  198. if (!after_open_brace_) {
  199. out_ << '\n';
  200. }
  201. Indent(-2);
  202. }
  203. // Formats a top-level scope, and any of the instructions in that scope that
  204. // are used.
  205. auto FormatScopeIfUsed(InstNamer::ScopeId scope_id,
  206. llvm::ArrayRef<InstId> block) -> void {
  207. if (block.empty()) {
  208. return;
  209. }
  210. llvm::SaveAndRestore scope(scope_, scope_id);
  211. // Note, we don't use OpenBrace() / CloseBrace() here because we always want
  212. // a newline to avoid misformatting if the first instruction is omitted.
  213. out_ << inst_namer_->GetScopeName(scope_id) << " {\n";
  214. indent_ += 2;
  215. for (const InstId inst_id : block) {
  216. TentativeOutputScope scope(*this);
  217. tentative_inst_chunks_[inst_id.index] = scope.index;
  218. FormatInst(inst_id);
  219. }
  220. out_ << "}\n\n";
  221. indent_ -= 2;
  222. }
  223. // Formats a full class.
  224. auto FormatClass(ClassId id) -> void {
  225. const Class& class_info = sem_ir_->classes().Get(id);
  226. if (!ShouldFormatEntity(class_info)) {
  227. return;
  228. }
  229. FormatEntityStart("class", class_info, id);
  230. llvm::SaveAndRestore class_scope(scope_, inst_namer_->GetScopeFor(id));
  231. if (class_info.scope_id.is_valid()) {
  232. out_ << ' ';
  233. OpenBrace();
  234. FormatCodeBlock(class_info.body_block_id);
  235. FormatNameScope(class_info.scope_id, "!members:\n");
  236. Indent();
  237. out_ << "complete_type_witness = ";
  238. FormatName(class_info.complete_type_witness_id);
  239. out_ << "\n";
  240. CloseBrace();
  241. } else {
  242. Semicolon();
  243. }
  244. out_ << '\n';
  245. FormatEntityEnd(class_info.generic_id);
  246. }
  247. // Formats a full interface.
  248. auto FormatInterface(InterfaceId id) -> void {
  249. const Interface& interface_info = sem_ir_->interfaces().Get(id);
  250. if (!ShouldFormatEntity(interface_info)) {
  251. return;
  252. }
  253. FormatEntityStart("interface", interface_info, id);
  254. llvm::SaveAndRestore interface_scope(scope_, inst_namer_->GetScopeFor(id));
  255. if (interface_info.scope_id.is_valid()) {
  256. out_ << ' ';
  257. OpenBrace();
  258. FormatCodeBlock(interface_info.body_block_id);
  259. // Always include the !members label because we always list the witness in
  260. // this section.
  261. IndentLabel();
  262. out_ << "!members:\n";
  263. FormatNameScope(interface_info.scope_id);
  264. Indent();
  265. out_ << "witness = ";
  266. FormatArg(interface_info.associated_entities_id);
  267. out_ << "\n";
  268. CloseBrace();
  269. } else {
  270. Semicolon();
  271. }
  272. out_ << '\n';
  273. FormatEntityEnd(interface_info.generic_id);
  274. }
  275. // Formats a full impl.
  276. auto FormatImpl(ImplId id) -> void {
  277. const Impl& impl_info = sem_ir_->impls().Get(id);
  278. if (!ShouldFormatEntity(impl_info)) {
  279. return;
  280. }
  281. FormatEntityStart("impl", impl_info, id);
  282. llvm::SaveAndRestore impl_scope(scope_, inst_namer_->GetScopeFor(id));
  283. out_ << ": ";
  284. FormatName(impl_info.self_id);
  285. out_ << " as ";
  286. FormatName(impl_info.constraint_id);
  287. if (impl_info.is_defined()) {
  288. out_ << ' ';
  289. OpenBrace();
  290. FormatCodeBlock(impl_info.body_block_id);
  291. // Print the !members label even if the name scope is empty because we
  292. // always list the witness in this section.
  293. IndentLabel();
  294. out_ << "!members:\n";
  295. if (impl_info.scope_id.is_valid()) {
  296. FormatNameScope(impl_info.scope_id);
  297. }
  298. Indent();
  299. out_ << "witness = ";
  300. FormatArg(impl_info.witness_id);
  301. out_ << "\n";
  302. CloseBrace();
  303. } else {
  304. Semicolon();
  305. }
  306. out_ << '\n';
  307. FormatEntityEnd(impl_info.generic_id);
  308. }
  309. // Formats a full function.
  310. auto FormatFunction(FunctionId id) -> void {
  311. const Function& fn = sem_ir_->functions().Get(id);
  312. if (!ShouldFormatEntity(fn)) {
  313. return;
  314. }
  315. std::string function_start;
  316. switch (fn.virtual_modifier) {
  317. case FunctionFields::VirtualModifier::Virtual:
  318. function_start += "virtual ";
  319. break;
  320. case FunctionFields::VirtualModifier::Abstract:
  321. function_start += "abstract ";
  322. break;
  323. case FunctionFields::VirtualModifier::Impl:
  324. function_start += "impl ";
  325. break;
  326. case FunctionFields::VirtualModifier::None:
  327. break;
  328. }
  329. if (fn.is_extern) {
  330. function_start += "extern ";
  331. }
  332. function_start += "fn";
  333. FormatEntityStart(function_start, fn, id);
  334. llvm::SaveAndRestore function_scope(scope_, inst_namer_->GetScopeFor(id));
  335. FormatParamList(fn.implicit_param_patterns_id, /*is_implicit=*/true);
  336. FormatParamList(fn.param_patterns_id, /*is_implicit=*/false);
  337. if (fn.return_slot_pattern_id.is_valid()) {
  338. out_ << " -> ";
  339. auto return_info = ReturnTypeInfo::ForFunction(*sem_ir_, fn);
  340. if (!fn.body_block_ids.empty() && return_info.is_valid() &&
  341. return_info.has_return_slot()) {
  342. FormatName(fn.return_slot_pattern_id);
  343. out_ << ": ";
  344. }
  345. FormatType(sem_ir_->insts().Get(fn.return_slot_pattern_id).type_id());
  346. }
  347. if (fn.builtin_function_kind != BuiltinFunctionKind::None) {
  348. out_ << " = \"";
  349. out_.write_escaped(fn.builtin_function_kind.name(),
  350. /*UseHexEscapes=*/true);
  351. out_ << "\"";
  352. }
  353. if (!fn.body_block_ids.empty()) {
  354. out_ << ' ';
  355. OpenBrace();
  356. for (auto block_id : fn.body_block_ids) {
  357. IndentLabel();
  358. FormatLabel(block_id);
  359. out_ << ":\n";
  360. FormatCodeBlock(block_id);
  361. }
  362. CloseBrace();
  363. } else {
  364. Semicolon();
  365. }
  366. out_ << '\n';
  367. FormatEntityEnd(fn.generic_id);
  368. }
  369. // Helper for FormatSpecific to print regions.
  370. auto FormatSpecificRegion(const Generic& generic, const Specific& specific,
  371. GenericInstIndex::Region region,
  372. llvm::StringRef region_name) -> void {
  373. if (!specific.GetValueBlock(region).is_valid()) {
  374. return;
  375. }
  376. if (!region_name.empty()) {
  377. IndentLabel();
  378. out_ << "!" << region_name << ":\n";
  379. }
  380. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  381. sem_ir_->inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  382. sem_ir_->inst_blocks().GetOrEmpty(
  383. specific.GetValueBlock(region)))) {
  384. Indent();
  385. if (generic_inst_id) {
  386. FormatName(*generic_inst_id);
  387. } else {
  388. out_ << "<missing>";
  389. }
  390. out_ << " => ";
  391. if (specific_inst_id) {
  392. FormatName(*specific_inst_id);
  393. } else {
  394. out_ << "<missing>";
  395. }
  396. out_ << "\n";
  397. }
  398. }
  399. // Formats a full specific.
  400. auto FormatSpecific(SpecificId id) -> void {
  401. const auto& specific = sem_ir_->specifics().Get(id);
  402. const auto& generic = sem_ir_->generics().Get(specific.generic_id);
  403. if (!should_format_entity_(generic.decl_id)) {
  404. // Omit specifics if we also omitted the generic.
  405. return;
  406. }
  407. llvm::SaveAndRestore generic_scope(
  408. scope_, inst_namer_->GetScopeFor(specific.generic_id));
  409. out_ << "\n";
  410. out_ << "specific ";
  411. FormatName(id);
  412. out_ << " ";
  413. OpenBrace();
  414. FormatSpecificRegion(generic, specific,
  415. GenericInstIndex::Region::Declaration, "");
  416. FormatSpecificRegion(generic, specific,
  417. GenericInstIndex::Region::Definition, "definition");
  418. CloseBrace();
  419. out_ << "\n";
  420. }
  421. // Handles generic-specific setup for FormatEntityStart.
  422. auto FormatGenericStart(llvm::StringRef entity_kind, GenericId generic_id)
  423. -> void {
  424. const auto& generic = sem_ir_->generics().Get(generic_id);
  425. out_ << "\n";
  426. Indent();
  427. out_ << "generic " << entity_kind << " ";
  428. FormatName(generic_id);
  429. llvm::SaveAndRestore generic_scope(scope_,
  430. inst_namer_->GetScopeFor(generic_id));
  431. FormatParamList(generic.bindings_id, /*is_implicit=*/false);
  432. out_ << " ";
  433. OpenBrace();
  434. FormatCodeBlock(generic.decl_block_id);
  435. if (generic.definition_block_id.is_valid()) {
  436. IndentLabel();
  437. out_ << "!definition:\n";
  438. FormatCodeBlock(generic.definition_block_id);
  439. }
  440. }
  441. // Provides common formatting for entities, paired with FormatEntityEnd.
  442. template <typename IdT>
  443. auto FormatEntityStart(llvm::StringRef entity_kind,
  444. const EntityWithParamsBase& entity, IdT entity_id)
  445. -> void {
  446. // If this entity was imported from a different IR, annotate the name of
  447. // that IR in the output before the `{` or `;`.
  448. if (entity.first_owning_decl_id.is_valid()) {
  449. auto loc_id = sem_ir_->insts().GetLocId(entity.first_owning_decl_id);
  450. if (loc_id.is_import_ir_inst_id()) {
  451. auto import_ir_id =
  452. sem_ir_->import_ir_insts().Get(loc_id.import_ir_inst_id()).ir_id;
  453. const auto* import_file =
  454. sem_ir_->import_irs().Get(import_ir_id).sem_ir;
  455. pending_imported_from_ = import_file->filename();
  456. }
  457. }
  458. auto generic_id = entity.generic_id;
  459. if (generic_id.is_valid()) {
  460. FormatGenericStart(entity_kind, generic_id);
  461. }
  462. out_ << "\n";
  463. Indent();
  464. out_ << entity_kind;
  465. // If there's a generic, it will have attached the name. Otherwise, add the
  466. // name here.
  467. if (!generic_id.is_valid()) {
  468. out_ << " ";
  469. FormatName(entity_id);
  470. }
  471. }
  472. // Provides common formatting for entities, paired with FormatEntityStart.
  473. auto FormatEntityEnd(GenericId generic_id) -> void {
  474. if (generic_id.is_valid()) {
  475. CloseBrace();
  476. out_ << '\n';
  477. }
  478. }
  479. // Formats parameters, eliding them completely if they're empty. Wraps in
  480. // parentheses or square brackets based on whether these are implicit
  481. // parameters.
  482. auto FormatParamList(InstBlockId param_patterns_id, bool is_implicit)
  483. -> void {
  484. if (!param_patterns_id.is_valid()) {
  485. return;
  486. }
  487. out_ << (is_implicit ? "[" : "(");
  488. llvm::ListSeparator sep;
  489. for (InstId param_id : sem_ir_->inst_blocks().Get(param_patterns_id)) {
  490. out_ << sep;
  491. if (!param_id.is_valid()) {
  492. out_ << "invalid";
  493. continue;
  494. }
  495. if (auto addr = sem_ir_->insts().TryGetAs<SemIR::AddrPattern>(param_id)) {
  496. out_ << "addr ";
  497. param_id = addr->inner_id;
  498. }
  499. FormatName(param_id);
  500. out_ << ": ";
  501. FormatType(sem_ir_->insts().Get(param_id).type_id());
  502. }
  503. out_ << (is_implicit ? "]" : ")");
  504. }
  505. // Prints instructions for a code block.
  506. auto FormatCodeBlock(InstBlockId block_id) -> void {
  507. for (const InstId inst_id : sem_ir_->inst_blocks().GetOrEmpty(block_id)) {
  508. FormatInst(inst_id);
  509. }
  510. }
  511. // Prints a code block with braces, intended to be used trailing after other
  512. // content on the same line. If non-empty, instructions are on separate lines.
  513. auto FormatTrailingBlock(InstBlockId block_id) -> void {
  514. out_ << ' ';
  515. OpenBrace();
  516. FormatCodeBlock(block_id);
  517. CloseBrace();
  518. }
  519. // Prints the contents of a name scope, with an optional label.
  520. auto FormatNameScope(NameScopeId id, llvm::StringRef label = "") -> void {
  521. const auto& scope = sem_ir_->name_scopes().Get(id);
  522. if (scope.entries().empty() && scope.extended_scopes().empty() &&
  523. scope.import_ir_scopes().empty() && !scope.has_error()) {
  524. // Name scope is empty.
  525. return;
  526. }
  527. if (!label.empty()) {
  528. IndentLabel();
  529. out_ << label;
  530. }
  531. for (auto [name_id, inst_id, access_kind] : scope.entries()) {
  532. if (inst_id.is_poisoned()) {
  533. // TODO: Add poisoned names.
  534. continue;
  535. }
  536. Indent();
  537. out_ << ".";
  538. FormatName(name_id);
  539. switch (access_kind) {
  540. case SemIR::AccessKind::Public:
  541. break;
  542. case SemIR::AccessKind::Protected:
  543. out_ << " [protected]";
  544. break;
  545. case SemIR::AccessKind::Private:
  546. out_ << " [private]";
  547. break;
  548. }
  549. out_ << " = ";
  550. FormatName(inst_id);
  551. out_ << "\n";
  552. }
  553. for (auto extended_scope_id : scope.extended_scopes()) {
  554. Indent();
  555. out_ << "extend ";
  556. FormatName(extended_scope_id);
  557. out_ << "\n";
  558. }
  559. // This is used to cluster all "Core//prelude/..." imports, but not
  560. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  561. // add or remove an unused prelude file, but is intended to still show the
  562. // existence of indirect imports.
  563. bool has_prelude_components = false;
  564. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  565. auto label = GetImportIRLabel(import_ir_id);
  566. if (label.starts_with("Core//prelude/")) {
  567. if (has_prelude_components) {
  568. // Only print the existence once.
  569. continue;
  570. } else {
  571. has_prelude_components = true;
  572. label = "Core//prelude/...";
  573. }
  574. }
  575. Indent();
  576. out_ << "import " << label << "\n";
  577. }
  578. if (scope.has_error()) {
  579. Indent();
  580. out_ << "has_error\n";
  581. }
  582. }
  583. // Prints a single instruction.
  584. auto FormatInst(InstId inst_id) -> void {
  585. if (!inst_id.is_valid()) {
  586. Indent();
  587. out_ << "invalid\n";
  588. return;
  589. }
  590. FormatInst(inst_id, sem_ir_->insts().Get(inst_id));
  591. }
  592. auto FormatInst(InstId inst_id, Inst inst) -> void {
  593. CARBON_KIND_SWITCH(inst) {
  594. #define CARBON_SEM_IR_INST_KIND(InstT) \
  595. case CARBON_KIND(InstT typed_inst): { \
  596. FormatInst(inst_id, typed_inst); \
  597. break; \
  598. }
  599. #include "toolchain/sem_ir/inst_kind.def"
  600. }
  601. }
  602. template <typename InstT>
  603. auto FormatInst(InstId inst_id, InstT inst) -> void {
  604. Indent();
  605. FormatInstLHS(inst_id, inst);
  606. out_ << InstT::Kind.ir_name();
  607. pending_constant_value_ = sem_ir_->constant_values().Get(inst_id);
  608. pending_constant_value_is_self_ =
  609. sem_ir_->constant_values().GetInstIdIfValid(pending_constant_value_) ==
  610. inst_id;
  611. FormatInstRHS(inst);
  612. FormatPendingConstantValue(AddSpace::Before);
  613. out_ << "\n";
  614. }
  615. // Don't print a constant for ImportRefUnloaded.
  616. auto FormatInst(InstId inst_id, ImportRefUnloaded inst) -> void {
  617. Indent();
  618. FormatInstLHS(inst_id, inst);
  619. out_ << ImportRefUnloaded::Kind.ir_name();
  620. FormatInstRHS(inst);
  621. out_ << "\n";
  622. }
  623. // If there is a pending library name that the current instruction was
  624. // imported from, print it now and clear it out.
  625. auto FormatPendingImportedFrom(AddSpace space_where) -> void {
  626. if (pending_imported_from_.empty()) {
  627. return;
  628. }
  629. if (space_where == AddSpace::Before) {
  630. out_ << ' ';
  631. }
  632. out_ << "[from \"";
  633. out_.write_escaped(pending_imported_from_);
  634. out_ << "\"]";
  635. if (space_where == AddSpace::After) {
  636. out_ << ' ';
  637. }
  638. pending_imported_from_ = llvm::StringRef();
  639. }
  640. // If there is a pending constant value attached to the current instruction,
  641. // print it now and clear it out. The constant value gets printed before the
  642. // first braced block argument, or at the end of the instruction if there are
  643. // no such arguments.
  644. auto FormatPendingConstantValue(AddSpace space_where) -> void {
  645. if (pending_constant_value_ == ConstantId::NotConstant) {
  646. return;
  647. }
  648. if (space_where == AddSpace::Before) {
  649. out_ << ' ';
  650. }
  651. out_ << '[';
  652. if (pending_constant_value_.is_valid()) {
  653. out_ << (pending_constant_value_.is_symbolic() ? "symbolic" : "template");
  654. if (!pending_constant_value_is_self_) {
  655. out_ << " = ";
  656. FormatConstant(pending_constant_value_);
  657. }
  658. } else {
  659. out_ << pending_constant_value_;
  660. }
  661. out_ << ']';
  662. if (space_where == AddSpace::After) {
  663. out_ << ' ';
  664. }
  665. pending_constant_value_ = ConstantId::NotConstant;
  666. }
  667. auto FormatInstLHS(InstId inst_id, Inst inst) -> void {
  668. switch (inst.kind().value_kind()) {
  669. case InstValueKind::Typed:
  670. FormatName(inst_id);
  671. out_ << ": ";
  672. switch (GetExprCategory(*sem_ir_, inst_id)) {
  673. case ExprCategory::NotExpr:
  674. case ExprCategory::Error:
  675. case ExprCategory::Value:
  676. case ExprCategory::Mixed:
  677. break;
  678. case ExprCategory::DurableRef:
  679. case ExprCategory::EphemeralRef:
  680. out_ << "ref ";
  681. break;
  682. case ExprCategory::Initializing:
  683. out_ << "init ";
  684. break;
  685. }
  686. FormatType(inst.type_id());
  687. out_ << " = ";
  688. break;
  689. case InstValueKind::None:
  690. break;
  691. }
  692. }
  693. // Format ImportDecl with its name.
  694. auto FormatInstLHS(InstId inst_id, ImportDecl /*inst*/) -> void {
  695. FormatName(inst_id);
  696. out_ << " = ";
  697. }
  698. // Print ImportRefUnloaded with type-like semantics even though it lacks a
  699. // type_id.
  700. auto FormatInstLHS(InstId inst_id, ImportRefUnloaded /*inst*/) -> void {
  701. FormatName(inst_id);
  702. out_ << " = ";
  703. }
  704. template <typename InstT>
  705. auto FormatInstRHS(InstT inst) -> void {
  706. // By default, an instruction has a comma-separated argument list.
  707. using Info = Internal::InstLikeTypeInfo<InstT>;
  708. if constexpr (Info::NumArgs == 2) {
  709. // Several instructions have a second operand that's a specific ID. We
  710. // don't include it in the argument list if there is no corresponding
  711. // specific, that is, when we're not in a generic context.
  712. if constexpr (std::is_same_v<typename Info::template ArgType<1>,
  713. SemIR::SpecificId>) {
  714. if (!Info::template Get<1>(inst).is_valid()) {
  715. FormatArgs(Info::template Get<0>(inst));
  716. return;
  717. }
  718. }
  719. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  720. } else if constexpr (Info::NumArgs == 1) {
  721. FormatArgs(Info::template Get<0>(inst));
  722. } else {
  723. FormatArgs();
  724. }
  725. }
  726. auto FormatInstRHS(BindSymbolicName inst) -> void {
  727. // A BindSymbolicName with no value is a purely symbolic binding, such as
  728. // the `Self` in an interface. Don't print out `invalid` for the value.
  729. if (inst.value_id.is_valid()) {
  730. FormatArgs(inst.entity_name_id, inst.value_id);
  731. } else {
  732. FormatArgs(inst.entity_name_id);
  733. }
  734. }
  735. auto FormatInstRHS(BlockArg inst) -> void {
  736. out_ << " ";
  737. FormatLabel(inst.block_id);
  738. }
  739. auto FormatInstRHS(Namespace inst) -> void {
  740. if (inst.import_id.is_valid()) {
  741. FormatArgs(inst.import_id, inst.name_scope_id);
  742. } else {
  743. FormatArgs(inst.name_scope_id);
  744. }
  745. }
  746. auto FormatInst(InstId /*inst_id*/, BranchIf inst) -> void {
  747. if (!in_terminator_sequence_) {
  748. Indent();
  749. }
  750. out_ << "if ";
  751. FormatName(inst.cond_id);
  752. out_ << " " << Branch::Kind.ir_name() << " ";
  753. FormatLabel(inst.target_id);
  754. out_ << " else ";
  755. in_terminator_sequence_ = true;
  756. }
  757. auto FormatInst(InstId /*inst_id*/, BranchWithArg inst) -> void {
  758. if (!in_terminator_sequence_) {
  759. Indent();
  760. }
  761. out_ << BranchWithArg::Kind.ir_name() << " ";
  762. FormatLabel(inst.target_id);
  763. out_ << "(";
  764. FormatName(inst.arg_id);
  765. out_ << ")\n";
  766. in_terminator_sequence_ = false;
  767. }
  768. auto FormatInst(InstId /*inst_id*/, Branch inst) -> void {
  769. if (!in_terminator_sequence_) {
  770. Indent();
  771. }
  772. out_ << Branch::Kind.ir_name() << " ";
  773. FormatLabel(inst.target_id);
  774. out_ << "\n";
  775. in_terminator_sequence_ = false;
  776. }
  777. auto FormatInstRHS(Call inst) -> void {
  778. out_ << " ";
  779. FormatArg(inst.callee_id);
  780. if (!inst.args_id.is_valid()) {
  781. out_ << "(<invalid>)";
  782. return;
  783. }
  784. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  785. auto return_info = ReturnTypeInfo::ForType(*sem_ir_, inst.type_id);
  786. if (!return_info.is_valid()) {
  787. out_ << "(<invalid return info>)";
  788. return;
  789. }
  790. bool has_return_slot = return_info.has_return_slot();
  791. InstId return_slot_arg_id = InstId::Invalid;
  792. if (has_return_slot) {
  793. return_slot_arg_id = args.back();
  794. args = args.drop_back();
  795. }
  796. llvm::ListSeparator sep;
  797. out_ << '(';
  798. for (auto inst_id : args) {
  799. out_ << sep;
  800. FormatArg(inst_id);
  801. }
  802. out_ << ')';
  803. if (has_return_slot) {
  804. FormatReturnSlotArg(return_slot_arg_id);
  805. }
  806. }
  807. auto FormatInstRHS(ArrayInit inst) -> void {
  808. FormatArgs(inst.inits_id);
  809. FormatReturnSlotArg(inst.dest_id);
  810. }
  811. auto FormatInstRHS(InitializeFrom inst) -> void {
  812. FormatArgs(inst.src_id);
  813. FormatReturnSlotArg(inst.dest_id);
  814. }
  815. auto FormatInstRHS(ValueParam inst) -> void {
  816. FormatArgs(inst.runtime_index);
  817. // Omit pretty_name because it's an implementation detail of
  818. // pretty-printing.
  819. }
  820. auto FormatInstRHS(OutParam inst) -> void {
  821. FormatArgs(inst.runtime_index);
  822. // Omit pretty_name because it's an implementation detail of
  823. // pretty-printing.
  824. }
  825. auto FormatInstRHS(ReturnExpr ret) -> void {
  826. FormatArgs(ret.expr_id);
  827. if (ret.dest_id.is_valid()) {
  828. FormatReturnSlotArg(ret.dest_id);
  829. }
  830. }
  831. auto FormatInstRHS(ReturnSlot inst) -> void {
  832. // Omit inst.type_inst_id because it's not semantically significant.
  833. FormatArgs(inst.storage_id);
  834. }
  835. auto FormatInstRHS(ReturnSlotPattern /*inst*/) -> void {
  836. // No-op because type_id is the only semantically significant field,
  837. // and it's handled separately.
  838. }
  839. auto FormatInstRHS(StructInit init) -> void {
  840. FormatArgs(init.elements_id);
  841. FormatReturnSlotArg(init.dest_id);
  842. }
  843. auto FormatInstRHS(TupleInit init) -> void {
  844. FormatArgs(init.elements_id);
  845. FormatReturnSlotArg(init.dest_id);
  846. }
  847. auto FormatInstRHS(FunctionDecl inst) -> void {
  848. FormatArgs(inst.function_id);
  849. llvm::SaveAndRestore class_scope(
  850. scope_, inst_namer_->GetScopeFor(inst.function_id));
  851. FormatTrailingBlock(
  852. sem_ir_->functions().Get(inst.function_id).pattern_block_id);
  853. FormatTrailingBlock(inst.decl_block_id);
  854. }
  855. auto FormatInstRHS(ClassDecl inst) -> void {
  856. FormatArgs(inst.class_id);
  857. llvm::SaveAndRestore class_scope(scope_,
  858. inst_namer_->GetScopeFor(inst.class_id));
  859. FormatTrailingBlock(sem_ir_->classes().Get(inst.class_id).pattern_block_id);
  860. FormatTrailingBlock(inst.decl_block_id);
  861. }
  862. auto FormatInstRHS(ImplDecl inst) -> void {
  863. FormatArgs(inst.impl_id);
  864. llvm::SaveAndRestore class_scope(scope_,
  865. inst_namer_->GetScopeFor(inst.impl_id));
  866. FormatTrailingBlock(sem_ir_->impls().Get(inst.impl_id).pattern_block_id);
  867. FormatTrailingBlock(inst.decl_block_id);
  868. }
  869. auto FormatInstRHS(InterfaceDecl inst) -> void {
  870. FormatArgs(inst.interface_id);
  871. llvm::SaveAndRestore class_scope(
  872. scope_, inst_namer_->GetScopeFor(inst.interface_id));
  873. FormatTrailingBlock(
  874. sem_ir_->interfaces().Get(inst.interface_id).pattern_block_id);
  875. FormatTrailingBlock(inst.decl_block_id);
  876. }
  877. auto FormatInstRHS(IntValue inst) -> void {
  878. out_ << " ";
  879. sem_ir_->ints()
  880. .Get(inst.int_id)
  881. .print(out_, sem_ir_->types().IsSignedInt(inst.type_id));
  882. }
  883. auto FormatInstRHS(FloatLiteral inst) -> void {
  884. llvm::SmallVector<char, 16> buffer;
  885. sem_ir_->floats().Get(inst.float_id).toString(buffer);
  886. out_ << " " << buffer;
  887. }
  888. auto FormatImportRefRHS(ImportIRInstId import_ir_inst_id,
  889. EntityNameId entity_name_id,
  890. llvm::StringLiteral loaded_label) -> void {
  891. out_ << " ";
  892. auto import_ir_inst = sem_ir_->import_ir_insts().Get(import_ir_inst_id);
  893. FormatArg(import_ir_inst.ir_id);
  894. out_ << ", ";
  895. if (entity_name_id.is_valid()) {
  896. // Prefer to show the entity name when possible.
  897. FormatArg(entity_name_id);
  898. } else {
  899. // Show a name based on the location when possible, or the numeric
  900. // instruction as a last resort.
  901. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id);
  902. auto loc_id = import_ir.sem_ir->insts().GetLocId(import_ir_inst.inst_id);
  903. if (!loc_id.is_valid()) {
  904. out_ << import_ir_inst.inst_id << " [no loc]";
  905. } else if (loc_id.is_import_ir_inst_id()) {
  906. // TODO: Probably don't want to format each indirection, but maybe reuse
  907. // GetCanonicalImportIRInst?
  908. out_ << import_ir_inst.inst_id << " [indirect]";
  909. } else if (loc_id.is_node_id()) {
  910. // Formats a NodeId from the import.
  911. const auto& tree = import_ir.sem_ir->parse_tree();
  912. auto token = tree.node_token(loc_id.node_id());
  913. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  914. << tree.tokens().GetColumnNumber(token);
  915. } else {
  916. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  917. }
  918. }
  919. out_ << ", " << loaded_label;
  920. }
  921. auto FormatInstRHS(ImportRefLoaded inst) -> void {
  922. FormatImportRefRHS(inst.import_ir_inst_id, inst.entity_name_id, "loaded");
  923. }
  924. auto FormatInstRHS(ImportRefUnloaded inst) -> void {
  925. FormatImportRefRHS(inst.import_ir_inst_id, inst.entity_name_id, "unloaded");
  926. }
  927. auto FormatInstRHS(SpliceBlock inst) -> void {
  928. FormatArgs(inst.result_id);
  929. FormatTrailingBlock(inst.block_id);
  930. }
  931. auto FormatInstRHS(WhereExpr inst) -> void {
  932. FormatArgs(inst.period_self_id);
  933. FormatTrailingBlock(inst.requirements_id);
  934. }
  935. auto FormatInstRHS(StructType inst) -> void {
  936. out_ << " {";
  937. llvm::ListSeparator sep;
  938. for (auto field : sem_ir_->struct_type_fields().Get(inst.fields_id)) {
  939. out_ << sep << ".";
  940. FormatName(field.name_id);
  941. out_ << ": ";
  942. FormatType(field.type_id);
  943. }
  944. out_ << "}";
  945. }
  946. auto FormatArgs() -> void {}
  947. template <typename... Args>
  948. auto FormatArgs(Args... args) -> void {
  949. out_ << ' ';
  950. llvm::ListSeparator sep;
  951. ((out_ << sep, FormatArg(args)), ...);
  952. }
  953. // FormatArg variants handling printing instruction arguments. Several things
  954. // provide equivalent behavior with `FormatName`, so we provide that as the
  955. // default.
  956. template <typename IdT>
  957. auto FormatArg(IdT id) -> void {
  958. FormatName(id);
  959. }
  960. auto FormatArg(BoolValue v) -> void { out_ << v; }
  961. auto FormatArg(EntityNameId id) -> void {
  962. const auto& info = sem_ir_->entity_names().Get(id);
  963. FormatName(info.name_id);
  964. if (info.bind_index.is_valid()) {
  965. out_ << ", " << info.bind_index.index;
  966. }
  967. }
  968. auto FormatArg(FacetTypeId id) -> void {
  969. const auto& info = sem_ir_->facet_types().Get(id);
  970. // Nothing output to indicate that this is a facet type since this is only
  971. // used as the argument to a `facet_type` instruction.
  972. out_ << "<";
  973. llvm::ListSeparator sep(" & ");
  974. if (info.impls_constraints.empty()) {
  975. out_ << "type";
  976. } else {
  977. for (auto interface : info.impls_constraints) {
  978. out_ << sep;
  979. FormatName(interface.interface_id);
  980. if (interface.specific_id.is_valid()) {
  981. out_ << ", ";
  982. FormatName(interface.specific_id);
  983. }
  984. }
  985. }
  986. if (info.other_requirements || !info.rewrite_constraints.empty()) {
  987. // TODO: Include specifics.
  988. out_ << " where ";
  989. llvm::ListSeparator and_sep(" and ");
  990. for (auto rewrite : info.rewrite_constraints) {
  991. out_ << and_sep;
  992. FormatConstant(rewrite.lhs_const_id);
  993. out_ << " = ";
  994. FormatConstant(rewrite.rhs_const_id);
  995. }
  996. if (info.other_requirements) {
  997. out_ << and_sep << "TODO";
  998. }
  999. }
  1000. out_ << ">";
  1001. }
  1002. auto FormatArg(IntKind k) -> void { k.Print(out_); }
  1003. auto FormatArg(FloatKind k) -> void { k.Print(out_); }
  1004. auto FormatArg(ImportIRId id) -> void {
  1005. if (id.is_valid()) {
  1006. out_ << GetImportIRLabel(id);
  1007. } else {
  1008. out_ << id;
  1009. }
  1010. }
  1011. auto FormatArg(IntId id) -> void {
  1012. // We don't know the signedness to use here. Default to unsigned.
  1013. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  1014. }
  1015. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  1016. auto FormatArg(RuntimeParamIndex index) -> void { out_ << index; }
  1017. auto FormatArg(NameScopeId id) -> void {
  1018. OpenBrace();
  1019. FormatNameScope(id);
  1020. CloseBrace();
  1021. }
  1022. auto FormatArg(InstBlockId id) -> void {
  1023. if (!id.is_valid()) {
  1024. out_ << "invalid";
  1025. return;
  1026. }
  1027. out_ << '(';
  1028. llvm::ListSeparator sep;
  1029. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1030. out_ << sep;
  1031. FormatArg(inst_id);
  1032. }
  1033. out_ << ')';
  1034. }
  1035. auto FormatArg(RealId id) -> void {
  1036. // TODO: Format with a `.` when the exponent is near zero.
  1037. const auto& real = sem_ir_->reals().Get(id);
  1038. real.mantissa.print(out_, /*isSigned=*/false);
  1039. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1040. }
  1041. auto FormatArg(StringLiteralValueId id) -> void {
  1042. out_ << '"';
  1043. out_.write_escaped(sem_ir_->string_literal_values().Get(id),
  1044. /*UseHexEscapes=*/true);
  1045. out_ << '"';
  1046. }
  1047. auto FormatArg(TypeId id) -> void { FormatType(id); }
  1048. auto FormatArg(TypeBlockId id) -> void {
  1049. out_ << '(';
  1050. llvm::ListSeparator sep;
  1051. for (auto type_id : sem_ir_->type_blocks().Get(id)) {
  1052. out_ << sep;
  1053. FormatArg(type_id);
  1054. }
  1055. out_ << ')';
  1056. }
  1057. auto FormatReturnSlotArg(InstId dest_id) -> void {
  1058. out_ << " to ";
  1059. FormatArg(dest_id);
  1060. }
  1061. // `FormatName` is used when we need the name from an id. Most id types use
  1062. // equivalent name formatting from InstNamer, although there are a few special
  1063. // formats below.
  1064. template <typename IdT>
  1065. auto FormatName(IdT id) -> void {
  1066. out_ << inst_namer_->GetNameFor(id);
  1067. }
  1068. auto FormatName(NameId id) -> void {
  1069. out_ << sem_ir_->names().GetFormatted(id);
  1070. }
  1071. auto FormatName(InstId id) -> void {
  1072. if (id.is_valid()) {
  1073. IncludeChunkInOutput(tentative_inst_chunks_[id.index]);
  1074. }
  1075. out_ << inst_namer_->GetNameFor(scope_, id);
  1076. }
  1077. auto FormatName(AbsoluteInstId id) -> void {
  1078. FormatName(static_cast<InstId>(id));
  1079. }
  1080. auto FormatName(SpecificId id) -> void {
  1081. const auto& specific = sem_ir_->specifics().Get(id);
  1082. FormatName(specific.generic_id);
  1083. FormatArg(specific.args_id);
  1084. }
  1085. auto FormatLabel(InstBlockId id) -> void {
  1086. out_ << inst_namer_->GetLabelFor(scope_, id);
  1087. }
  1088. auto FormatConstant(ConstantId id) -> void {
  1089. if (!id.is_valid()) {
  1090. out_ << "<not constant>";
  1091. return;
  1092. }
  1093. // For a symbolic constant in a generic, list the constant value in the
  1094. // generic first, and the canonical constant second.
  1095. if (id.is_symbolic()) {
  1096. const auto& symbolic_constant =
  1097. sem_ir_->constant_values().GetSymbolicConstant(id);
  1098. if (symbolic_constant.generic_id.is_valid()) {
  1099. const auto& generic =
  1100. sem_ir_->generics().Get(symbolic_constant.generic_id);
  1101. FormatName(sem_ir_->inst_blocks().Get(generic.GetEvalBlock(
  1102. symbolic_constant.index
  1103. .region()))[symbolic_constant.index.index()]);
  1104. out_ << " (";
  1105. FormatName(sem_ir_->constant_values().GetInstId(id));
  1106. out_ << ")";
  1107. return;
  1108. }
  1109. }
  1110. FormatName(sem_ir_->constant_values().GetInstId(id));
  1111. }
  1112. auto FormatType(TypeId id) -> void {
  1113. if (!id.is_valid()) {
  1114. out_ << "invalid";
  1115. } else {
  1116. // Types are formatted in the `constants` scope because they only refer to
  1117. // constants.
  1118. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1119. FormatConstant(sem_ir_->types().GetConstantId(id));
  1120. }
  1121. }
  1122. // Returns the label for the indicated IR.
  1123. auto GetImportIRLabel(ImportIRId id) -> std::string {
  1124. CARBON_CHECK(id.is_valid(),
  1125. "GetImportIRLabel should only be called where we a valid ID.");
  1126. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1127. CARBON_CHECK(import_ir.library_id().is_valid());
  1128. llvm::StringRef package_name =
  1129. import_ir.package_id().is_valid()
  1130. ? import_ir.identifiers().Get(import_ir.package_id())
  1131. : "Main";
  1132. llvm::StringRef library_name =
  1133. (import_ir.library_id() != LibraryNameId::Default)
  1134. ? import_ir.string_literal_values().Get(
  1135. import_ir.library_id().AsStringLiteralValueId())
  1136. : "default";
  1137. return llvm::formatv("{0}//{1}", package_name, library_name);
  1138. }
  1139. const File* sem_ir_;
  1140. InstNamer* const inst_namer_;
  1141. Formatter::ShouldFormatEntityFn should_format_entity_;
  1142. // The output stream buffer.
  1143. std::string buffer_;
  1144. // The output stream.
  1145. llvm::raw_string_ostream out_ = llvm::raw_string_ostream(buffer_);
  1146. // Chunks of output text that we have created so far.
  1147. llvm::SmallVector<OutputChunk> output_chunks_;
  1148. // The current scope that we are formatting within. References to names in
  1149. // this scope will not have a `@scope.` prefix added.
  1150. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  1151. // Whether we are formatting in a terminator sequence, that is, a sequence of
  1152. // branches at the end of a block. The entirety of a terminator sequence is
  1153. // formatted on a single line, despite being multiple instructions.
  1154. bool in_terminator_sequence_ = false;
  1155. // The indent depth to use for new instructions.
  1156. int indent_;
  1157. // Whether we are currently formatting immediately after an open brace. If so,
  1158. // a newline will be inserted before the next line indent.
  1159. bool after_open_brace_ = false;
  1160. // The constant value of the current instruction, if it has one that has not
  1161. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  1162. // there is nothing to print.
  1163. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  1164. // Whether `pending_constant_value_`'s instruction is the same as the
  1165. // instruction currently being printed. If true, only the phase of the
  1166. // constant is printed, and the value is omitted.
  1167. bool pending_constant_value_is_self_ = false;
  1168. // The name of the IR file from which the current entity was imported, if it
  1169. // was imported and no file has been printed yet. This is printed before the
  1170. // first open brace or the semicolon in the entity declaration.
  1171. llvm::StringRef pending_imported_from_;
  1172. // Indexes of chunks of output that should be included when an instruction is
  1173. // referenced, indexed by the instruction's index. This is resized in advance
  1174. // to the correct size.
  1175. llvm::SmallVector<size_t, 0> tentative_inst_chunks_;
  1176. };
  1177. Formatter::Formatter(const File* sem_ir,
  1178. ShouldFormatEntityFn should_format_entity)
  1179. : sem_ir_(sem_ir),
  1180. should_format_entity_(should_format_entity),
  1181. inst_namer_(sem_ir) {}
  1182. Formatter::~Formatter() = default;
  1183. auto Formatter::Print(llvm::raw_ostream& out) -> void {
  1184. FormatterImpl formatter(sem_ir_, &inst_namer_, should_format_entity_,
  1185. /*indent=*/0);
  1186. formatter.Format();
  1187. formatter.Write(out);
  1188. }
  1189. } // namespace Carbon::SemIR