formatter.cpp 35 KB

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