formatter.cpp 46 KB

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