formatter.cpp 47 KB

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