formatter.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700
  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/fixed_size_value_store.h"
  12. #include "toolchain/base/kind_switch.h"
  13. #include "toolchain/base/shared_value_stores.h"
  14. #include "toolchain/lex/tokenized_buffer.h"
  15. #include "toolchain/parse/tree.h"
  16. #include "toolchain/parse/tree_and_subtrees.h"
  17. #include "toolchain/sem_ir/builtin_function_kind.h"
  18. #include "toolchain/sem_ir/constant.h"
  19. #include "toolchain/sem_ir/entity_with_params_base.h"
  20. #include "toolchain/sem_ir/expr_info.h"
  21. #include "toolchain/sem_ir/function.h"
  22. #include "toolchain/sem_ir/ids.h"
  23. #include "toolchain/sem_ir/name_scope.h"
  24. #include "toolchain/sem_ir/typed_insts.h"
  25. #include "toolchain/sem_ir/vtable.h"
  26. // TODO: Consider addressing recursion here, although it's not critical because
  27. // the formatter isn't required to work on arbitrary code. Still, it may help
  28. // in the future to debug complex code.
  29. // NOLINTBEGIN(misc-no-recursion)
  30. namespace Carbon::SemIR {
  31. Formatter::Formatter(
  32. const File* sem_ir, int total_ir_count,
  33. Parse::GetTreeAndSubtreesFn get_tree_and_subtrees,
  34. const FixedSizeValueStore<CheckIRId, bool>* include_ir_in_dumps,
  35. bool use_dump_sem_ir_ranges)
  36. : sem_ir_(sem_ir),
  37. inst_namer_(sem_ir_, total_ir_count),
  38. get_tree_and_subtrees_(get_tree_and_subtrees),
  39. include_ir_in_dumps_(include_ir_in_dumps),
  40. use_dump_sem_ir_ranges_(use_dump_sem_ir_ranges),
  41. // Create a placeholder visible chunk and assign it to all instructions
  42. // that don't have a chunk of their own.
  43. tentative_inst_chunks_(sem_ir_->insts(), AddChunkNoFlush(true)) {
  44. if (use_dump_sem_ir_ranges_) {
  45. ComputeNodeParents();
  46. }
  47. // Create empty placeholder chunks for instructions that we output lazily.
  48. for (auto inst_id : llvm::concat<const InstId>(
  49. sem_ir_->constants().array_ref(),
  50. sem_ir_->inst_blocks().Get(InstBlockId::Imports))) {
  51. tentative_inst_chunks_.Set(inst_id, AddChunkNoFlush(false));
  52. }
  53. // Create a real chunk for the start of the output.
  54. AddChunkNoFlush(true);
  55. }
  56. auto Formatter::Format() -> void {
  57. out_ << "--- " << sem_ir_->filename() << "\n";
  58. FormatTopLevelScopeIfUsed(InstNamer::ScopeId::Constants,
  59. sem_ir_->constants().array_ref(),
  60. /*use_tentative_output_scopes=*/true);
  61. FormatTopLevelScopeIfUsed(InstNamer::ScopeId::Imports,
  62. sem_ir_->inst_blocks().Get(InstBlockId::Imports),
  63. /*use_tentative_output_scopes=*/true);
  64. FormatTopLevelScopeIfUsed(
  65. InstNamer::ScopeId::File,
  66. sem_ir_->inst_blocks().GetOrEmpty(sem_ir_->top_inst_block_id()),
  67. /*use_tentative_output_scopes=*/false);
  68. for (const auto& [id, interface] : sem_ir_->interfaces().enumerate()) {
  69. FormatInterface(id, interface);
  70. }
  71. for (const auto& [id, constraint] :
  72. sem_ir_->named_constraints().enumerate()) {
  73. FormatNamedConstraint(id, constraint);
  74. }
  75. for (const auto& [id, require] : sem_ir_->require_impls().enumerate()) {
  76. FormatRequireImpls(id, require);
  77. }
  78. for (const auto& [id, assoc_const] :
  79. sem_ir_->associated_constants().enumerate()) {
  80. FormatAssociatedConstant(id, assoc_const);
  81. }
  82. for (const auto& [id, impl] : sem_ir_->impls().enumerate()) {
  83. FormatImpl(id, impl);
  84. }
  85. for (const auto& [id, class_info] : sem_ir_->classes().enumerate()) {
  86. FormatClass(id, class_info);
  87. }
  88. for (const auto& [id, vtable] : sem_ir_->vtables().enumerate()) {
  89. FormatVtable(id, vtable);
  90. }
  91. for (const auto& [id, function] : sem_ir_->functions().enumerate()) {
  92. FormatFunction(id, function);
  93. }
  94. for (const auto& [id, specific] : sem_ir_->specifics().enumerate()) {
  95. FormatSpecific(id, specific);
  96. }
  97. out_ << "\n";
  98. }
  99. auto Formatter::ComputeNodeParents() -> void {
  100. CARBON_CHECK(!node_parents_);
  101. node_parents_ = NodeParentStore::MakeWithExplicitSize(
  102. sem_ir_->parse_tree().size(), Parse::NodeId::None);
  103. for (auto n : sem_ir_->parse_tree().postorder()) {
  104. for (auto child : get_tree_and_subtrees_().children(n)) {
  105. node_parents_->Set(child, n);
  106. }
  107. }
  108. }
  109. auto Formatter::Write(llvm::raw_ostream& out) -> void {
  110. FlushChunk();
  111. for (const auto& chunk : output_chunks_) {
  112. if (chunk.include_in_output) {
  113. out << chunk.chunk;
  114. }
  115. }
  116. }
  117. auto Formatter::FlushChunk() -> void {
  118. CARBON_CHECK(output_chunks_.back().chunk.empty());
  119. output_chunks_.back().chunk = std::move(buffer_);
  120. buffer_.clear();
  121. }
  122. auto Formatter::AddChunkNoFlush(bool include_in_output) -> size_t {
  123. CARBON_CHECK(buffer_.empty());
  124. output_chunks_.push_back({.include_in_output = include_in_output});
  125. return output_chunks_.size() - 1;
  126. }
  127. auto Formatter::AddChunk(bool include_in_output) -> size_t {
  128. FlushChunk();
  129. return AddChunkNoFlush(include_in_output);
  130. }
  131. auto Formatter::IncludeChunkInOutput(size_t chunk) -> void {
  132. if (chunk == output_chunks_.size() - 1) {
  133. return;
  134. }
  135. if (auto& current_chunk = output_chunks_.back();
  136. !current_chunk.include_in_output) {
  137. current_chunk.dependencies.push_back(chunk);
  138. return;
  139. }
  140. llvm::SmallVector<size_t> to_add = {chunk};
  141. while (!to_add.empty()) {
  142. auto& chunk = output_chunks_[to_add.pop_back_val()];
  143. if (chunk.include_in_output) {
  144. continue;
  145. }
  146. chunk.include_in_output = true;
  147. to_add.append(chunk.dependencies);
  148. chunk.dependencies.clear();
  149. }
  150. }
  151. auto Formatter::ShouldIncludeInstByIR(InstId inst_id) -> bool {
  152. const auto* import_ir = GetCanonicalFileAndInstId(sem_ir_, inst_id).first;
  153. return include_ir_in_dumps_->Get(import_ir->check_ir_id());
  154. }
  155. // Returns true for a `DefinitionStart` node.
  156. static auto IsDefinitionStart(Parse::NodeKind node_kind) -> bool {
  157. switch (node_kind) {
  158. case Parse::NodeKind::BuiltinFunctionDefinitionStart:
  159. case Parse::NodeKind::ChoiceDefinitionStart:
  160. case Parse::NodeKind::ClassDefinitionStart:
  161. case Parse::NodeKind::FunctionDefinitionStart:
  162. case Parse::NodeKind::ImplDefinitionStart:
  163. case Parse::NodeKind::InterfaceDefinitionStart:
  164. case Parse::NodeKind::NamedConstraintDefinitionStart:
  165. return true;
  166. default:
  167. return false;
  168. }
  169. }
  170. auto Formatter::ShouldFormatEntity(InstId decl_id) -> bool {
  171. if (!decl_id.has_value()) {
  172. return true;
  173. }
  174. if (!ShouldIncludeInstByIR(decl_id)) {
  175. return false;
  176. }
  177. if (!use_dump_sem_ir_ranges_) {
  178. return true;
  179. }
  180. // When there are dump ranges, ignore imported instructions.
  181. auto loc_id = sem_ir_->insts().GetCanonicalLocId(decl_id);
  182. if (loc_id.kind() != LocId::Kind::NodeId) {
  183. return false;
  184. }
  185. const auto& tree_and_subtrees = get_tree_and_subtrees_();
  186. // This takes the earliest token from either the node or its first postorder
  187. // child. The first postorder child isn't necessarily the earliest token in
  188. // the subtree (for example, it can miss modifiers), but finding the earliest
  189. // token requires walking *all* children, whereas this approach is
  190. // constant-time.
  191. auto begin_node_id = *tree_and_subtrees.postorder(loc_id.node_id()).begin();
  192. // Non-defining declarations will be associated with a `Decl` node.
  193. // Definitions will have a `DefinitionStart` for which we can use the parent
  194. // to find the `Definition`, giving a range that includes the definition's
  195. // body.
  196. auto end_node_id = loc_id.node_id();
  197. if (IsDefinitionStart(sem_ir_->parse_tree().node_kind(end_node_id))) {
  198. end_node_id = node_parents_->Get(end_node_id);
  199. }
  200. Lex::InclusiveTokenRange range = {
  201. .begin = sem_ir_->parse_tree().node_token(begin_node_id),
  202. .end = sem_ir_->parse_tree().node_token(end_node_id)};
  203. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(range);
  204. }
  205. auto Formatter::ShouldFormatEntity(const EntityWithParamsBase& entity) -> bool {
  206. return ShouldFormatEntity(entity.latest_decl_id());
  207. }
  208. auto Formatter::ShouldFormatInst(InstId inst_id) -> bool {
  209. if (!use_dump_sem_ir_ranges_) {
  210. return true;
  211. }
  212. // When there are dump ranges, ignore imported instructions.
  213. auto loc_id = sem_ir_->insts().GetCanonicalLocId(inst_id);
  214. if (loc_id.kind() != LocId::Kind::NodeId) {
  215. return false;
  216. }
  217. auto token = sem_ir_->parse_tree().node_token(loc_id.node_id());
  218. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(
  219. Lex::InclusiveTokenRange{.begin = token, .end = token});
  220. }
  221. auto Formatter::OpenBrace() -> void {
  222. // Put the constant value of an instruction before any braced block, rather
  223. // than at the end.
  224. FormatPendingConstantValue(AddSpace::After);
  225. // Put the imported-from library name before the definition of the entity.
  226. FormatPendingImportedFrom(AddSpace::After);
  227. out_ << '{';
  228. indent_ += 2;
  229. after_open_brace_ = true;
  230. }
  231. auto Formatter::CloseBrace() -> void {
  232. indent_ -= 2;
  233. if (!after_open_brace_) {
  234. Indent();
  235. }
  236. out_ << '}';
  237. after_open_brace_ = false;
  238. }
  239. auto Formatter::Semicolon() -> void {
  240. FormatPendingImportedFrom(AddSpace::Before);
  241. out_ << ';';
  242. }
  243. auto Formatter::Indent(int offset) -> void {
  244. if (after_open_brace_) {
  245. out_ << '\n';
  246. after_open_brace_ = false;
  247. }
  248. out_.indent(indent_ + offset);
  249. }
  250. auto Formatter::IndentLabel() -> void {
  251. CARBON_CHECK(indent_ >= 2);
  252. if (!after_open_brace_) {
  253. out_ << '\n';
  254. }
  255. Indent(-2);
  256. }
  257. auto Formatter::FormatTopLevelScopeIfUsed(InstNamer::ScopeId scope_id,
  258. llvm::ArrayRef<InstId> block,
  259. bool use_tentative_output_scopes)
  260. -> void {
  261. if (!use_tentative_output_scopes && use_dump_sem_ir_ranges_) {
  262. // Don't format the scope if no instructions are in a dump range.
  263. block = block.drop_while(
  264. [&](InstId inst_id) { return !ShouldFormatInst(inst_id); });
  265. }
  266. if (block.empty()) {
  267. return;
  268. }
  269. llvm::SaveAndRestore scope(scope_, scope_id);
  270. // Note, we don't use OpenBrace() / CloseBrace() here because we always want
  271. // a newline to avoid misformatting if the first instruction is omitted.
  272. out_ << "\n" << inst_namer_.GetScopeName(scope_id) << " {\n";
  273. indent_ += 2;
  274. for (const InstId inst_id : block) {
  275. // Format instructions when needed, but do nothing for elided entries;
  276. // unlike normal code blocks, scopes are non-sequential so skipped
  277. // instructions are assumed to be uninteresting.
  278. if (use_tentative_output_scopes) {
  279. // This is for constants and imports. These use tentative logic to
  280. // determine whether an instruction is printed.
  281. TentativeOutputScope scope(*this, tentative_inst_chunks_.Get(inst_id));
  282. FormatInst(inst_id);
  283. } else if (ShouldFormatInst(inst_id)) {
  284. // This is for the file scope. It uses only the range-based filtering.
  285. FormatInst(inst_id);
  286. }
  287. }
  288. out_ << "}\n";
  289. indent_ -= 2;
  290. }
  291. auto Formatter::FormatClass(ClassId id, const Class& class_info) -> void {
  292. if (!ShouldFormatEntity(class_info)) {
  293. return;
  294. }
  295. PrepareToFormatDecl(class_info.first_owning_decl_id);
  296. FormatEntityStart("class", class_info, id);
  297. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  298. if (class_info.scope_id.has_value()) {
  299. out_ << ' ';
  300. OpenBrace();
  301. FormatCodeBlock(class_info.body_block_id);
  302. Indent();
  303. out_ << "complete_type_witness = ";
  304. FormatName(class_info.complete_type_witness_id);
  305. out_ << "\n";
  306. if (class_info.vtable_decl_id.has_value()) {
  307. Indent();
  308. out_ << "vtable_decl = ";
  309. FormatName(class_info.vtable_decl_id);
  310. out_ << "\n";
  311. }
  312. FormatNameScope(class_info.scope_id, "!members:\n");
  313. CloseBrace();
  314. } else {
  315. Semicolon();
  316. }
  317. out_ << '\n';
  318. FormatEntityEnd(class_info.generic_id);
  319. }
  320. auto Formatter::FormatVtable(VtableId id, const Vtable& vtable_info) -> void {
  321. out_ << '\n';
  322. Indent();
  323. out_ << "vtable ";
  324. FormatName(id);
  325. out_ << ' ';
  326. OpenBrace();
  327. for (auto function_id :
  328. sem_ir_->inst_blocks().Get(vtable_info.virtual_functions_id)) {
  329. Indent();
  330. FormatArg(function_id);
  331. out_ << '\n';
  332. }
  333. CloseBrace();
  334. out_ << '\n';
  335. }
  336. auto Formatter::FormatInterface(InterfaceId id, const Interface& interface_info)
  337. -> void {
  338. if (!ShouldFormatEntity(interface_info)) {
  339. return;
  340. }
  341. PrepareToFormatDecl(interface_info.first_owning_decl_id);
  342. FormatEntityStart("interface", interface_info, id);
  343. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  344. if (interface_info.scope_id.has_value()) {
  345. out_ << ' ';
  346. OpenBrace();
  347. FormatCodeBlock(interface_info.body_block_id);
  348. // Always include the !members label because we always list the witness in
  349. // this section.
  350. IndentLabel();
  351. out_ << "!members:\n";
  352. FormatNameScope(interface_info.scope_id);
  353. Indent();
  354. out_ << "witness = ";
  355. FormatArg(interface_info.associated_entities_id);
  356. out_ << "\n";
  357. FormatRequireImplsBlock(interface_info.require_impls_block_id);
  358. CloseBrace();
  359. } else {
  360. Semicolon();
  361. }
  362. out_ << '\n';
  363. FormatEntityEnd(interface_info.generic_id);
  364. }
  365. auto Formatter::FormatNamedConstraint(NamedConstraintId id,
  366. const NamedConstraint& constraint_info)
  367. -> void {
  368. if (!ShouldFormatEntity(constraint_info)) {
  369. return;
  370. }
  371. PrepareToFormatDecl(constraint_info.first_owning_decl_id);
  372. FormatEntityStart("constraint", constraint_info, id);
  373. llvm::SaveAndRestore constraint_scope(scope_, inst_namer_.GetScopeFor(id));
  374. if (constraint_info.scope_id.has_value()) {
  375. out_ << ' ';
  376. OpenBrace();
  377. FormatCodeBlock(constraint_info.body_block_id);
  378. // Always include the !members label because we always list the witness in
  379. // this section.
  380. IndentLabel();
  381. out_ << "!members:\n";
  382. FormatNameScope(constraint_info.scope_id);
  383. FormatRequireImplsBlock(constraint_info.require_impls_block_id);
  384. CloseBrace();
  385. } else {
  386. Semicolon();
  387. }
  388. out_ << '\n';
  389. FormatEntityEnd(constraint_info.generic_id);
  390. }
  391. auto Formatter::FormatRequireImpls(RequireImplsId /*id*/,
  392. const RequireImpls& require) -> void {
  393. if (!ShouldFormatEntity(require.decl_id)) {
  394. return;
  395. }
  396. PrepareToFormatDecl(require.decl_id);
  397. FormatGenericStart("require", require.generic_id);
  398. FormatGenericEnd();
  399. }
  400. auto Formatter::FormatAssociatedConstant(AssociatedConstantId id,
  401. const AssociatedConstant& assoc_const)
  402. -> void {
  403. if (!ShouldFormatEntity(assoc_const.decl_id)) {
  404. return;
  405. }
  406. PrepareToFormatDecl(assoc_const.decl_id);
  407. FormatEntityStart("assoc_const", assoc_const.generic_id, id);
  408. llvm::SaveAndRestore assoc_const_scope(scope_, inst_namer_.GetScopeFor(id));
  409. out_ << " ";
  410. FormatName(assoc_const.name_id);
  411. out_ << ":! ";
  412. FormatTypeOfInst(assoc_const.decl_id);
  413. if (assoc_const.default_value_id.has_value()) {
  414. out_ << " = ";
  415. FormatArg(assoc_const.default_value_id);
  416. }
  417. out_ << ";\n";
  418. FormatEntityEnd(assoc_const.generic_id);
  419. }
  420. auto Formatter::FormatImpl(ImplId id, const Impl& impl_info) -> void {
  421. if (!ShouldFormatEntity(impl_info)) {
  422. return;
  423. }
  424. PrepareToFormatDecl(impl_info.first_owning_decl_id);
  425. FormatEntityStart("impl", impl_info, id);
  426. llvm::SaveAndRestore impl_scope(scope_, inst_namer_.GetScopeFor(id));
  427. out_ << ": ";
  428. FormatName(impl_info.self_id);
  429. out_ << " as ";
  430. FormatName(impl_info.constraint_id);
  431. if (impl_info.is_complete()) {
  432. out_ << ' ';
  433. OpenBrace();
  434. FormatCodeBlock(impl_info.body_block_id);
  435. FormatCodeBlock(impl_info.witness_block_id);
  436. // Print the !members label even if the name scope is empty because we
  437. // always list the witness in this section.
  438. IndentLabel();
  439. out_ << "!members:\n";
  440. if (impl_info.scope_id.has_value()) {
  441. FormatNameScope(impl_info.scope_id);
  442. }
  443. Indent();
  444. out_ << "witness = ";
  445. FormatArg(impl_info.witness_id);
  446. out_ << "\n";
  447. CloseBrace();
  448. } else {
  449. Semicolon();
  450. }
  451. out_ << '\n';
  452. FormatEntityEnd(impl_info.generic_id);
  453. }
  454. auto Formatter::FormatFunction(FunctionId id, const Function& fn) -> void {
  455. if (!ShouldFormatEntity(fn)) {
  456. return;
  457. }
  458. std::string function_start;
  459. switch (fn.virtual_modifier) {
  460. case FunctionFields::VirtualModifier::Virtual:
  461. function_start += "virtual ";
  462. break;
  463. case FunctionFields::VirtualModifier::Abstract:
  464. function_start += "abstract ";
  465. break;
  466. case FunctionFields::VirtualModifier::Override:
  467. function_start += "override ";
  468. break;
  469. case FunctionFields::VirtualModifier::None:
  470. break;
  471. }
  472. if (fn.is_extern) {
  473. function_start += "extern ";
  474. }
  475. function_start += "fn";
  476. PrepareToFormatDecl(fn.first_owning_decl_id);
  477. FormatEntityStart(function_start, fn, id);
  478. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  479. FormatParamList(fn.call_params_id, fn.GetDeclaredReturnForm(*sem_ir_));
  480. if (fn.builtin_function_kind() != BuiltinFunctionKind::None) {
  481. out_ << " = \""
  482. << FormatEscaped(fn.builtin_function_kind().name(),
  483. /*use_hex_escapes=*/true)
  484. << "\"";
  485. }
  486. if (fn.thunk_decl_id().has_value()) {
  487. out_ << " [thunk ";
  488. FormatArg(fn.thunk_decl_id());
  489. out_ << "]";
  490. }
  491. if (!fn.body_block_ids.empty()) {
  492. out_ << ' ';
  493. OpenBrace();
  494. for (auto block_id : fn.body_block_ids) {
  495. IndentLabel();
  496. FormatLabel(block_id);
  497. out_ << ":\n";
  498. FormatCodeBlock(block_id);
  499. }
  500. CloseBrace();
  501. } else {
  502. Semicolon();
  503. }
  504. out_ << '\n';
  505. FormatEntityEnd(fn.generic_id);
  506. }
  507. auto Formatter::FormatSpecificRegion(const Generic& generic,
  508. const Specific& specific,
  509. GenericInstIndex::Region region,
  510. llvm::StringRef region_name) -> void {
  511. if (!specific.GetValueBlock(region).has_value()) {
  512. return;
  513. }
  514. if (!region_name.empty()) {
  515. IndentLabel();
  516. out_ << "!" << region_name << ":\n";
  517. }
  518. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  519. sem_ir_->inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  520. sem_ir_->inst_blocks().GetOrEmpty(specific.GetValueBlock(region)))) {
  521. Indent();
  522. if (generic_inst_id) {
  523. FormatName(*generic_inst_id);
  524. } else {
  525. out_ << "<missing>";
  526. }
  527. out_ << " => ";
  528. if (specific_inst_id) {
  529. FormatName(*specific_inst_id);
  530. } else {
  531. out_ << "<missing>";
  532. }
  533. out_ << "\n";
  534. }
  535. }
  536. auto Formatter::FormatSpecific(SpecificId id, const Specific& specific)
  537. -> void {
  538. const auto& generic = sem_ir_->generics().Get(specific.generic_id);
  539. if (!ShouldFormatEntity(generic.decl_id)) {
  540. // Omit specifics if we also omitted the generic.
  541. return;
  542. }
  543. if (specific.IsUnresolved()) {
  544. // Omit specifics that were never resolved. Such specifics exist only to
  545. // track the way the arguments were spelled, and that information is
  546. // conveyed entirely by the name of the specific. These specifics may also
  547. // not be referenced by any SemIR that we format, so including them adds
  548. // clutter and possibly emits references to instructions we didn't name.
  549. return;
  550. }
  551. llvm::SaveAndRestore generic_scope(
  552. scope_, inst_namer_.GetScopeFor(specific.generic_id));
  553. out_ << "\n";
  554. out_ << "specific ";
  555. FormatName(id);
  556. out_ << " ";
  557. OpenBrace();
  558. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Declaration,
  559. "");
  560. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Definition,
  561. "definition");
  562. CloseBrace();
  563. out_ << "\n";
  564. }
  565. auto Formatter::PrepareToFormatDecl(InstId first_owning_decl_id) -> void {
  566. // If this decl was imported from a different IR, annotate the name of
  567. // that IR in the output before the `{` or `;`.
  568. if (first_owning_decl_id.has_value()) {
  569. auto import_ir_inst_id =
  570. sem_ir_->insts().GetImportSource(first_owning_decl_id);
  571. if (import_ir_inst_id.has_value()) {
  572. auto import_ir_id =
  573. sem_ir_->import_ir_insts().Get(import_ir_inst_id).ir_id();
  574. if (const auto* import_file =
  575. sem_ir_->import_irs().Get(import_ir_id).sem_ir) {
  576. pending_imported_from_ = import_file->filename();
  577. }
  578. }
  579. }
  580. }
  581. auto Formatter::FormatGenericStart(llvm::StringRef entity_kind,
  582. GenericId generic_id) -> void {
  583. const auto& generic = sem_ir_->generics().Get(generic_id);
  584. out_ << "\n";
  585. Indent();
  586. out_ << "generic " << entity_kind << " ";
  587. FormatName(generic_id);
  588. llvm::SaveAndRestore generic_scope(scope_,
  589. inst_namer_.GetScopeFor(generic_id));
  590. FormatParamList(generic.bindings_id);
  591. out_ << " ";
  592. OpenBrace();
  593. FormatCodeBlock(generic.decl_block_id);
  594. if (generic.definition_block_id.has_value()) {
  595. IndentLabel();
  596. out_ << "!definition:\n";
  597. FormatCodeBlock(generic.definition_block_id);
  598. }
  599. }
  600. auto Formatter::FormatEntityEnd(GenericId generic_id) -> void {
  601. if (generic_id.has_value()) {
  602. FormatGenericEnd();
  603. }
  604. }
  605. auto Formatter::FormatGenericEnd() -> void {
  606. CloseBrace();
  607. out_ << '\n';
  608. }
  609. auto Formatter::FormatParamList(InstBlockId params_id,
  610. SemIR::InstId return_form_id) -> void {
  611. if (!params_id.has_value()) {
  612. // TODO: This happens for imported functions, for which we don't currently
  613. // import the call parameters list.
  614. return;
  615. }
  616. int return_param_index = -1;
  617. if (return_form_id.has_value()) {
  618. if (auto init_form = sem_ir_->insts().TryGetAs<InitForm>(return_form_id)) {
  619. return_param_index = init_form->index.index;
  620. }
  621. }
  622. auto params = sem_ir_->inst_blocks().Get(params_id);
  623. out_ << "(";
  624. llvm::ListSeparator sep;
  625. for (auto [i, param_id] : llvm::enumerate(params)) {
  626. if (static_cast<int>(i) == return_param_index) {
  627. continue;
  628. }
  629. out_ << sep;
  630. if (!param_id.has_value()) {
  631. out_ << "invalid";
  632. continue;
  633. }
  634. CARBON_CHECK(!sem_ir_->insts().Is<OutParam>(param_id));
  635. FormatName(param_id);
  636. out_ << ": ";
  637. FormatTypeOfInst(param_id);
  638. }
  639. out_ << ")";
  640. if (return_form_id.has_value()) {
  641. out_ << " -> ";
  642. auto return_form = sem_ir_->insts().Get(return_form_id);
  643. CARBON_KIND_SWITCH(return_form) {
  644. case CARBON_KIND(InitForm init_form): {
  645. auto param_id = params[init_form.index.index];
  646. out_ << "out ";
  647. FormatName(param_id);
  648. out_ << ": ";
  649. FormatTypeOfInst(param_id);
  650. break;
  651. }
  652. case CARBON_KIND(RefForm ref_form): {
  653. out_ << "ref ";
  654. FormatInstAsType(ref_form.type_component_inst_id);
  655. break;
  656. }
  657. case CARBON_KIND(ErrorInst _): {
  658. FormatInstAsType(return_form_id);
  659. break;
  660. }
  661. default:
  662. CARBON_FATAL("Unexpected inst kind: {0}", return_form);
  663. }
  664. }
  665. }
  666. auto Formatter::FormatCodeBlock(InstBlockId block_id) -> void {
  667. bool elided = false;
  668. for (const InstId inst_id : sem_ir_->inst_blocks().GetOrEmpty(block_id)) {
  669. if (ShouldFormatInst(inst_id)) {
  670. FormatInst(inst_id);
  671. elided = false;
  672. } else if (!elided) {
  673. // When formatting a block, leave a hint that instructions were elided.
  674. Indent();
  675. out_ << "<elided>\n";
  676. elided = true;
  677. }
  678. }
  679. }
  680. auto Formatter::FormatTrailingBlock(InstBlockId block_id) -> void {
  681. out_ << ' ';
  682. OpenBrace();
  683. FormatCodeBlock(block_id);
  684. CloseBrace();
  685. }
  686. auto Formatter::FormatNameScope(NameScopeId id, llvm::StringRef label) -> void {
  687. const auto& scope = sem_ir_->name_scopes().Get(id);
  688. if (scope.entries().empty() && scope.extended_scopes().empty() &&
  689. scope.import_ir_scopes().empty() && !scope.is_cpp_scope() &&
  690. !scope.has_error()) {
  691. // Name scope is empty.
  692. return;
  693. }
  694. if (!label.empty()) {
  695. IndentLabel();
  696. out_ << label;
  697. }
  698. for (auto [name_id, result] : scope.entries()) {
  699. Indent();
  700. out_ << ".";
  701. FormatName(name_id);
  702. switch (result.access_kind()) {
  703. case AccessKind::Public:
  704. break;
  705. case AccessKind::Protected:
  706. out_ << " [protected]";
  707. break;
  708. case AccessKind::Private:
  709. out_ << " [private]";
  710. break;
  711. }
  712. out_ << " = ";
  713. if (result.is_poisoned()) {
  714. out_ << "<poisoned>";
  715. } else {
  716. FormatName(result.is_found() ? result.target_inst_id() : InstId::None);
  717. }
  718. out_ << "\n";
  719. }
  720. for (auto extended_scope_id : scope.extended_scopes()) {
  721. Indent();
  722. out_ << "extend ";
  723. FormatName(extended_scope_id);
  724. out_ << "\n";
  725. }
  726. // This is used to cluster all "Core//prelude/..." imports, but not
  727. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  728. // add or remove an unused prelude file, but is intended to still show the
  729. // existence of indirect imports.
  730. bool has_prelude_components = false;
  731. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  732. auto label = GetImportIRLabel(import_ir_id);
  733. if (label.starts_with("Core//prelude/")) {
  734. if (has_prelude_components) {
  735. // Only print the existence once.
  736. continue;
  737. } else {
  738. has_prelude_components = true;
  739. label = "Core//prelude/...";
  740. }
  741. }
  742. Indent();
  743. out_ << "import " << label << "\n";
  744. }
  745. if (scope.is_cpp_scope()) {
  746. Indent();
  747. out_ << "import Cpp//...\n";
  748. }
  749. if (scope.has_error()) {
  750. Indent();
  751. out_ << "has_error\n";
  752. }
  753. }
  754. auto Formatter::FormatInst(InstId inst_id) -> void {
  755. if (!inst_id.has_value()) {
  756. Indent();
  757. out_ << "none\n";
  758. return;
  759. }
  760. if (!in_terminator_sequence_) {
  761. Indent();
  762. }
  763. auto inst = sem_ir_->insts().GetWithAttachedType(inst_id);
  764. CARBON_KIND_SWITCH(inst) {
  765. case CARBON_KIND(Branch branch): {
  766. out_ << Branch::Kind.ir_name() << " ";
  767. FormatLabel(branch.target_id);
  768. out_ << "\n";
  769. in_terminator_sequence_ = false;
  770. return;
  771. }
  772. case CARBON_KIND(BranchIf branch_if): {
  773. out_ << "if ";
  774. FormatName(branch_if.cond_id);
  775. out_ << " " << Branch::Kind.ir_name() << " ";
  776. FormatLabel(branch_if.target_id);
  777. out_ << " else ";
  778. in_terminator_sequence_ = true;
  779. return;
  780. }
  781. case CARBON_KIND(BranchWithArg branch_with_arg): {
  782. out_ << BranchWithArg::Kind.ir_name() << " ";
  783. FormatLabel(branch_with_arg.target_id);
  784. out_ << "(";
  785. FormatName(branch_with_arg.arg_id);
  786. out_ << ")\n";
  787. in_terminator_sequence_ = false;
  788. return;
  789. }
  790. default: {
  791. FormatInstLhs(inst_id, inst);
  792. out_ << inst.kind().ir_name();
  793. // Add constants for everything except `ImportRefUnloaded`.
  794. if (!inst.Is<ImportRefUnloaded>()) {
  795. pending_constant_value_ =
  796. sem_ir_->constant_values().GetAttached(inst_id);
  797. pending_constant_value_is_self_ =
  798. sem_ir_->constant_values().GetInstIdIfValid(
  799. pending_constant_value_) == inst_id;
  800. }
  801. FormatInstRhs(inst);
  802. // This usually prints the constant, but when `FormatInstRhs` prints it
  803. // first (or for `ImportRefUnloaded`), this does nothing.
  804. FormatPendingConstantValue(AddSpace::Before);
  805. out_ << "\n";
  806. return;
  807. }
  808. }
  809. }
  810. auto Formatter::FormatPendingImportedFrom(AddSpace space_where) -> void {
  811. if (pending_imported_from_.empty()) {
  812. return;
  813. }
  814. if (space_where == AddSpace::Before) {
  815. out_ << ' ';
  816. }
  817. out_ << "[from \"" << FormatEscaped(pending_imported_from_) << "\"]";
  818. if (space_where == AddSpace::After) {
  819. out_ << ' ';
  820. }
  821. pending_imported_from_ = llvm::StringRef();
  822. }
  823. auto Formatter::FormatPendingConstantValue(AddSpace space_where) -> void {
  824. if (pending_constant_value_ == ConstantId::NotConstant) {
  825. return;
  826. }
  827. if (space_where == AddSpace::Before) {
  828. out_ << ' ';
  829. }
  830. out_ << '[';
  831. if (pending_constant_value_.has_value()) {
  832. switch (sem_ir_->constant_values().GetDependence(pending_constant_value_)) {
  833. case ConstantDependence::None:
  834. out_ << "concrete";
  835. break;
  836. case ConstantDependence::PeriodSelf:
  837. out_ << "symbolic_self";
  838. break;
  839. // TODO: Consider renaming this. This will cause a lot of SemIR churn.
  840. case ConstantDependence::Checked:
  841. out_ << "symbolic";
  842. break;
  843. case ConstantDependence::Template:
  844. out_ << "template";
  845. break;
  846. }
  847. if (!pending_constant_value_is_self_) {
  848. out_ << " = ";
  849. FormatConstant(pending_constant_value_);
  850. }
  851. } else {
  852. out_ << pending_constant_value_;
  853. }
  854. out_ << ']';
  855. if (space_where == AddSpace::After) {
  856. out_ << ' ';
  857. }
  858. pending_constant_value_ = ConstantId::NotConstant;
  859. }
  860. auto Formatter::FormatInstLhs(InstId inst_id, Inst inst) -> void {
  861. // Every typed instruction is named, and there are some untyped instructions
  862. // that have names (such as `ImportRefUnloaded`). When there's a typed
  863. // instruction with no name, it means an instruction is incorrectly not named
  864. // -- but should be printed as such.
  865. bool has_name = inst_namer_.has_name(inst_id);
  866. if (!has_name && !inst.kind().has_type()) {
  867. return;
  868. }
  869. FormatName(inst_id);
  870. if (inst.kind().has_type()) {
  871. out_ << ": ";
  872. switch (GetExprCategory(*sem_ir_, inst_id)) {
  873. case ExprCategory::NotExpr:
  874. case ExprCategory::Error:
  875. case ExprCategory::Value:
  876. case ExprCategory::Pattern:
  877. case ExprCategory::Mixed:
  878. case ExprCategory::RefTagged:
  879. FormatTypeOfInst(inst_id);
  880. break;
  881. case ExprCategory::DurableRef:
  882. case ExprCategory::EphemeralRef:
  883. out_ << "ref ";
  884. FormatTypeOfInst(inst_id);
  885. break;
  886. case ExprCategory::Initializing: {
  887. out_ << "init ";
  888. FormatTypeOfInst(inst_id);
  889. auto init_target_id = FindReturnSlotArgForInitializer(
  890. *sem_ir_, inst_id, /*allow_transitive=*/false);
  891. FormatReturnSlotArg(init_target_id);
  892. break;
  893. }
  894. }
  895. }
  896. out_ << " = ";
  897. }
  898. auto Formatter::FormatInstArgAndKind(Inst::ArgAndKind arg_and_kind) -> void {
  899. GetFormatArgFn(arg_and_kind.kind())(*this, arg_and_kind.value());
  900. }
  901. auto Formatter::FormatInstRhs(Inst inst) -> void {
  902. CARBON_KIND_SWITCH(inst) {
  903. case InstKind::ArrayInit:
  904. case InstKind::StructInit:
  905. case InstKind::TupleInit: {
  906. auto init = inst.As<AnyAggregateInit>();
  907. FormatArgs(init.elements_id);
  908. return;
  909. }
  910. case InstKind::ImportRefLoaded:
  911. case InstKind::ImportRefUnloaded:
  912. FormatImportRefRhs(inst.As<AnyImportRef>());
  913. return;
  914. case InstKind::OutParam:
  915. case InstKind::RefParam:
  916. case InstKind::ValueParam: {
  917. auto param = inst.As<AnyParam>();
  918. FormatArgs(param.index);
  919. // Omit pretty_name because it's an implementation detail of
  920. // pretty-printing.
  921. return;
  922. }
  923. case CARBON_KIND(AssociatedConstantDecl decl): {
  924. FormatArgs(decl.assoc_const_id);
  925. llvm::SaveAndRestore scope(scope_,
  926. inst_namer_.GetScopeFor(decl.assoc_const_id));
  927. FormatTrailingBlock(decl.decl_block_id);
  928. return;
  929. }
  930. case CARBON_KIND(SymbolicBinding bind): {
  931. // A SymbolicBinding with no value is a purely symbolic binding, such as
  932. // the `Self` in an interface. Don't print out `none` for the value.
  933. if (bind.value_id.has_value()) {
  934. FormatArgs(bind.entity_name_id, bind.value_id);
  935. } else {
  936. FormatArgs(bind.entity_name_id);
  937. }
  938. return;
  939. }
  940. case CARBON_KIND(BlockArg block): {
  941. out_ << " ";
  942. FormatLabel(block.block_id);
  943. return;
  944. }
  945. case CARBON_KIND(Call call): {
  946. FormatCallRhs(call);
  947. return;
  948. }
  949. case CARBON_KIND(ClassDecl decl): {
  950. FormatDeclRhs(decl.class_id,
  951. sem_ir_->classes().Get(decl.class_id).pattern_block_id,
  952. decl.decl_block_id);
  953. return;
  954. }
  955. case CARBON_KIND(CppTemplateNameType type): {
  956. // Omit the Clang declaration. We don't have a good way to format it, and
  957. // the entity name should suffice to identify the template.
  958. FormatArgs(type.name_id);
  959. return;
  960. }
  961. case CARBON_KIND(CustomLayoutType type): {
  962. out_ << " {";
  963. auto layout = sem_ir_->custom_layouts().Get(type.layout_id);
  964. out_ << "size=" << layout[CustomLayoutId::SizeIndex]
  965. << ", align=" << layout[CustomLayoutId::AlignIndex];
  966. for (auto [field, offset] : llvm::zip_equal(
  967. sem_ir_->struct_type_fields().Get(type.fields_id),
  968. layout.drop_front(CustomLayoutId::FirstFieldIndex))) {
  969. out_ << ", .";
  970. FormatName(field.name_id);
  971. out_ << "@" << offset << ": ";
  972. FormatInstAsType(field.type_inst_id);
  973. }
  974. out_ << "}";
  975. return;
  976. }
  977. case CARBON_KIND(FloatValue value): {
  978. llvm::SmallVector<char, 16> buffer;
  979. sem_ir_->floats().Get(value.float_id).toString(buffer);
  980. out_ << " " << buffer;
  981. return;
  982. }
  983. case CARBON_KIND(FunctionDecl decl): {
  984. FormatDeclRhs(decl.function_id,
  985. sem_ir_->functions().Get(decl.function_id).pattern_block_id,
  986. decl.decl_block_id);
  987. return;
  988. }
  989. case InstKind::ImportCppDecl: {
  990. FormatImportCppDeclRhs();
  991. return;
  992. }
  993. case CARBON_KIND(ImplDecl decl): {
  994. FormatDeclRhs(decl.impl_id,
  995. sem_ir_->impls().Get(decl.impl_id).pattern_block_id,
  996. decl.decl_block_id);
  997. return;
  998. }
  999. case CARBON_KIND(InitializeFrom init): {
  1000. FormatArgs(init.src_id);
  1001. return;
  1002. }
  1003. case CARBON_KIND(InstValue inst): {
  1004. out_ << ' ';
  1005. OpenBrace();
  1006. // TODO: Should we use a more compact representation in the case where the
  1007. // inst is a SpliceBlock?
  1008. FormatInst(inst.inst_id);
  1009. CloseBrace();
  1010. return;
  1011. }
  1012. case CARBON_KIND(InterfaceDecl decl): {
  1013. FormatDeclRhs(
  1014. decl.interface_id,
  1015. sem_ir_->interfaces().Get(decl.interface_id).pattern_block_id,
  1016. decl.decl_block_id);
  1017. return;
  1018. }
  1019. case CARBON_KIND(IntValue value): {
  1020. out_ << " ";
  1021. sem_ir_->ints()
  1022. .Get(value.int_id)
  1023. .print(out_, sem_ir_->types().IsSignedInt(value.type_id));
  1024. return;
  1025. }
  1026. case CARBON_KIND(NameBindingDecl name): {
  1027. FormatTrailingBlock(name.pattern_block_id);
  1028. return;
  1029. }
  1030. case CARBON_KIND(NamedConstraintDecl decl): {
  1031. FormatDeclRhs(decl.named_constraint_id,
  1032. sem_ir_->named_constraints()
  1033. .Get(decl.named_constraint_id)
  1034. .pattern_block_id,
  1035. decl.decl_block_id);
  1036. return;
  1037. }
  1038. case CARBON_KIND(Namespace ns): {
  1039. if (ns.import_id.has_value()) {
  1040. FormatArgs(ns.import_id, ns.name_scope_id);
  1041. } else {
  1042. FormatArgs(ns.name_scope_id);
  1043. }
  1044. return;
  1045. }
  1046. case CARBON_KIND(RequireImplsDecl decl): {
  1047. FormatArgs(decl.require_impls_id);
  1048. llvm::SaveAndRestore scope(
  1049. scope_, inst_namer_.GetScopeFor(decl.require_impls_id));
  1050. FormatRequireImpls(decl.require_impls_id);
  1051. FormatTrailingBlock(decl.decl_block_id);
  1052. return;
  1053. }
  1054. case CARBON_KIND(ReturnExpr ret): {
  1055. FormatArgs(ret.expr_id);
  1056. if (ret.dest_id.has_value()) {
  1057. FormatReturnSlotArg(ret.dest_id);
  1058. }
  1059. return;
  1060. }
  1061. case CARBON_KIND(ReturnSlot ret): {
  1062. // Omit inst.type_inst_id because it's not semantically significant.
  1063. FormatArgs(ret.storage_id);
  1064. return;
  1065. }
  1066. case InstKind::ReturnSlotPattern:
  1067. // No-op because type_id is the only semantically significant field,
  1068. // and it's handled separately.
  1069. return;
  1070. case CARBON_KIND(SpliceBlock splice): {
  1071. FormatArgs(splice.result_id);
  1072. FormatTrailingBlock(splice.block_id);
  1073. return;
  1074. }
  1075. case CARBON_KIND(StructType struct_type): {
  1076. out_ << " {";
  1077. llvm::ListSeparator sep;
  1078. for (auto field :
  1079. sem_ir_->struct_type_fields().Get(struct_type.fields_id)) {
  1080. out_ << sep << ".";
  1081. FormatName(field.name_id);
  1082. out_ << ": ";
  1083. FormatInstAsType(field.type_inst_id);
  1084. }
  1085. out_ << "}";
  1086. return;
  1087. }
  1088. case CARBON_KIND(WhereExpr where): {
  1089. FormatArgs(where.period_self_id);
  1090. FormatTrailingBlock(where.requirements_id);
  1091. return;
  1092. }
  1093. case CARBON_KIND(InPlaceInit in_place): {
  1094. // Omit dest_id if it will be part of the expression form.
  1095. //
  1096. // TODO: should it always be part of the expression form? If so, fix
  1097. // FindReturnSlotArgForInitializer to always return it, and then
  1098. // FormatInstRhsDefault will do the right thing.
  1099. if (SemIR::InitRepr::ForType(*sem_ir_, in_place.type_id)
  1100. .MightBeInPlace()) {
  1101. FormatArgs(in_place.src_id);
  1102. } else {
  1103. FormatArgs(in_place.src_id, in_place.dest_id);
  1104. }
  1105. return;
  1106. }
  1107. default:
  1108. FormatInstRhsDefault(inst);
  1109. return;
  1110. }
  1111. }
  1112. auto Formatter::FormatInstRhsDefault(Inst inst) -> void {
  1113. auto arg0 = inst.arg0_and_kind();
  1114. if (arg0.kind() == IdKind::None) {
  1115. return;
  1116. }
  1117. out_ << " ";
  1118. FormatInstArgAndKind(arg0);
  1119. auto arg1 = inst.arg1_and_kind();
  1120. if (arg1.kind() == IdKind::None) {
  1121. return;
  1122. }
  1123. // Several instructions have a second operand that's a specific ID. We
  1124. // don't include it in the argument list if there is no corresponding
  1125. // specific, that is, when we're not in a generic context.
  1126. if (auto arg1_specific_id = arg1.TryAs<SpecificId>();
  1127. arg1_specific_id && !arg1_specific_id->has_value()) {
  1128. return;
  1129. }
  1130. // Similarly, instructions that have a `DestInstId` as the second operand
  1131. // typically use it for the output argument, so we omit it because it should
  1132. // already be part of the inst's formatted form expression.
  1133. if (arg1.kind() == IdKind::For<DestInstId>) {
  1134. return;
  1135. }
  1136. out_ << ", ";
  1137. FormatInstArgAndKind(arg1);
  1138. }
  1139. auto Formatter::FormatCallRhs(Call inst) -> void {
  1140. out_ << " ";
  1141. FormatArg(inst.callee_id);
  1142. if (!inst.args_id.has_value()) {
  1143. out_ << "(<none>)";
  1144. return;
  1145. }
  1146. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  1147. // If there's a return argument, don't print it here, because it's printed on
  1148. // the LHS.
  1149. auto callee_function = SemIR::GetCalleeAsFunction(*sem_ir_, inst.callee_id);
  1150. auto function = sem_ir_->functions().Get(callee_function.function_id);
  1151. auto return_form_id = function.GetDeclaredReturnForm(
  1152. *sem_ir_, callee_function.resolved_specific_id);
  1153. int return_arg_index = -1;
  1154. if (return_form_id.has_value()) {
  1155. if (auto init_form =
  1156. sem_ir_->insts().TryGetAs<SemIR::InitForm>(return_form_id)) {
  1157. auto type_id = sem_ir_->types().GetTypeIdForTypeInstId(
  1158. init_form->type_component_inst_id);
  1159. if (SemIR::InitRepr::ForType(*sem_ir_, type_id).MightBeInPlace()) {
  1160. return_arg_index = init_form->index.index;
  1161. }
  1162. }
  1163. }
  1164. llvm::ListSeparator sep;
  1165. out_ << '(';
  1166. for (auto [i, inst_id] : llvm::enumerate(args)) {
  1167. if (static_cast<int>(i) == return_arg_index) {
  1168. continue;
  1169. }
  1170. out_ << sep;
  1171. FormatArg(inst_id);
  1172. }
  1173. out_ << ')';
  1174. }
  1175. auto Formatter::FormatImportCppDeclRhs() -> void {
  1176. out_ << " ";
  1177. OpenBrace();
  1178. for (const Parse::Tree::PackagingNames& import :
  1179. sem_ir_->parse_tree().imports()) {
  1180. if (import.package_id != PackageNameId::Cpp) {
  1181. continue;
  1182. }
  1183. Indent();
  1184. out_ << "import Cpp";
  1185. if (import.library_id.has_value()) {
  1186. out_ << " \""
  1187. << FormatEscaped(
  1188. sem_ir_->string_literal_values().Get(import.library_id))
  1189. << "\"";
  1190. } else if (import.inline_body_id.has_value()) {
  1191. out_ << " inline";
  1192. }
  1193. out_ << "\n";
  1194. }
  1195. CloseBrace();
  1196. }
  1197. auto Formatter::FormatImportRefRhs(AnyImportRef inst) -> void {
  1198. out_ << " ";
  1199. auto import_ir_inst = sem_ir_->import_ir_insts().Get(inst.import_ir_inst_id);
  1200. FormatArg(import_ir_inst.ir_id());
  1201. out_ << ", ";
  1202. if (inst.entity_name_id.has_value()) {
  1203. // Prefer to show the entity name when possible.
  1204. FormatArg(inst.entity_name_id);
  1205. } else {
  1206. // Show a name based on the location when possible, or the numeric
  1207. // instruction as a last resort.
  1208. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  1209. auto loc_id =
  1210. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  1211. switch (loc_id.kind()) {
  1212. case LocId::Kind::None: {
  1213. out_ << import_ir_inst.inst_id() << " [no loc]";
  1214. break;
  1215. }
  1216. case LocId::Kind::ImportIRInstId: {
  1217. // TODO: Probably don't want to format each indirection, but maybe
  1218. // reuse GetCanonicalImportIRInst?
  1219. out_ << import_ir_inst.inst_id() << " [indirect]";
  1220. break;
  1221. }
  1222. case LocId::Kind::NodeId: {
  1223. // Formats a NodeId from the import.
  1224. const auto& tree = import_ir.sem_ir->parse_tree();
  1225. auto token = tree.node_token(loc_id.node_id());
  1226. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1227. << tree.tokens().GetColumnNumber(token);
  1228. break;
  1229. }
  1230. case LocId::Kind::InstId:
  1231. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1232. }
  1233. }
  1234. out_ << ", "
  1235. << (inst.kind == InstKind::ImportRefLoaded ? "loaded" : "unloaded");
  1236. }
  1237. auto Formatter::FormatRequireImpls(RequireImplsId id) -> void {
  1238. out_ << ' ';
  1239. const auto& require = sem_ir_->require_impls().Get(id);
  1240. OpenBrace();
  1241. Indent();
  1242. out_ << "require ";
  1243. FormatArg(require.self_id);
  1244. out_ << " impls ";
  1245. FormatArg(require.facet_type_inst_id);
  1246. out_ << "\n";
  1247. CloseBrace();
  1248. }
  1249. auto Formatter::FormatRequireImplsBlock(RequireImplsBlockId block_id) -> void {
  1250. IndentLabel();
  1251. out_ << "!requires:\n";
  1252. if (!block_id.has_value()) {
  1253. return;
  1254. }
  1255. for (auto require_impls_id : sem_ir_->require_impls_blocks().Get(block_id)) {
  1256. Indent();
  1257. FormatArg(require_impls_id);
  1258. FormatRequireImpls(require_impls_id);
  1259. out_ << "\n";
  1260. }
  1261. }
  1262. auto Formatter::FormatArg(EntityNameId id) -> void {
  1263. if (!id.has_value()) {
  1264. out_ << "_";
  1265. return;
  1266. }
  1267. const auto& info = sem_ir_->entity_names().Get(id);
  1268. FormatName(info.name_id);
  1269. if (info.bind_index().has_value()) {
  1270. out_ << ", " << info.bind_index().index;
  1271. }
  1272. if (info.is_template) {
  1273. out_ << ", template";
  1274. }
  1275. }
  1276. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1277. const auto& info = sem_ir_->facet_types().Get(id);
  1278. // Nothing output to indicate that this is a facet type since this is only
  1279. // used as the argument to a `facet_type` instruction.
  1280. out_ << "<";
  1281. llvm::ListSeparator sep(" & ");
  1282. if (info.extend_constraints.empty() &&
  1283. info.extend_named_constraints.empty()) {
  1284. out_ << "type";
  1285. } else {
  1286. for (auto extend : info.extend_constraints) {
  1287. out_ << sep;
  1288. FormatName(extend.interface_id);
  1289. if (extend.specific_id.has_value()) {
  1290. out_ << ", ";
  1291. FormatName(extend.specific_id);
  1292. }
  1293. }
  1294. for (auto extend : info.extend_named_constraints) {
  1295. out_ << sep;
  1296. FormatName(extend.named_constraint_id);
  1297. if (extend.specific_id.has_value()) {
  1298. out_ << ", ";
  1299. FormatName(extend.specific_id);
  1300. }
  1301. }
  1302. }
  1303. if (info.other_requirements || !info.self_impls_constraints.empty() ||
  1304. !info.rewrite_constraints.empty()) {
  1305. out_ << " where ";
  1306. llvm::ListSeparator and_sep(" and ");
  1307. if (!info.self_impls_constraints.empty() ||
  1308. !info.self_impls_named_constraints.empty()) {
  1309. out_ << and_sep << ".Self impls ";
  1310. llvm::ListSeparator amp_sep(" & ");
  1311. for (auto self_impls : info.self_impls_constraints) {
  1312. out_ << amp_sep;
  1313. FormatName(self_impls.interface_id);
  1314. if (self_impls.specific_id.has_value()) {
  1315. out_ << ", ";
  1316. FormatName(self_impls.specific_id);
  1317. }
  1318. }
  1319. for (auto self_impls : info.self_impls_named_constraints) {
  1320. out_ << amp_sep;
  1321. FormatName(self_impls.named_constraint_id);
  1322. if (self_impls.specific_id.has_value()) {
  1323. out_ << ", ";
  1324. FormatName(self_impls.specific_id);
  1325. }
  1326. }
  1327. }
  1328. for (auto rewrite : info.rewrite_constraints) {
  1329. out_ << and_sep;
  1330. FormatArg(rewrite.lhs_id);
  1331. out_ << " = ";
  1332. FormatArg(rewrite.rhs_id);
  1333. }
  1334. if (info.other_requirements) {
  1335. out_ << and_sep << "TODO";
  1336. }
  1337. }
  1338. out_ << ">";
  1339. }
  1340. auto Formatter::FormatArg(ImportIRId id) -> void {
  1341. if (id.has_value()) {
  1342. out_ << GetImportIRLabel(id);
  1343. } else {
  1344. out_ << id;
  1345. }
  1346. }
  1347. auto Formatter::FormatArg(IntId id) -> void {
  1348. // We don't know the signedness to use here. Default to unsigned.
  1349. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  1350. }
  1351. auto Formatter::FormatArg(NameScopeId id) -> void {
  1352. OpenBrace();
  1353. FormatNameScope(id);
  1354. CloseBrace();
  1355. }
  1356. auto Formatter::FormatArg(InstBlockId id) -> void {
  1357. if (!id.has_value()) {
  1358. out_ << "invalid";
  1359. return;
  1360. }
  1361. out_ << '(';
  1362. llvm::ListSeparator sep;
  1363. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1364. out_ << sep;
  1365. FormatArg(inst_id);
  1366. }
  1367. out_ << ')';
  1368. }
  1369. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1370. FormatArg(static_cast<InstBlockId>(id));
  1371. }
  1372. auto Formatter::FormatArg(RealId id) -> void {
  1373. // TODO: Format with a `.` when the exponent is near zero.
  1374. const auto& real = sem_ir_->reals().Get(id);
  1375. real.mantissa.print(out_, /*isSigned=*/false);
  1376. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1377. }
  1378. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1379. out_ << '"'
  1380. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1381. /*use_hex_escapes=*/true)
  1382. << '"';
  1383. }
  1384. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1385. if (dest_id.has_value()) {
  1386. out_ << " to ";
  1387. FormatArg(dest_id);
  1388. }
  1389. }
  1390. auto Formatter::FormatName(NameId id) -> void {
  1391. out_ << sem_ir_->names().GetFormatted(id);
  1392. }
  1393. auto Formatter::FormatName(InstId id) -> void {
  1394. if (id.has_value()) {
  1395. IncludeChunkInOutput(tentative_inst_chunks_.Get(id));
  1396. }
  1397. out_ << inst_namer_.GetNameFor(scope_, id);
  1398. }
  1399. auto Formatter::FormatName(SpecificId id) -> void {
  1400. const auto& specific = sem_ir_->specifics().Get(id);
  1401. FormatName(specific.generic_id);
  1402. FormatArg(specific.args_id);
  1403. }
  1404. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1405. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1406. FormatName(interface.interface_id);
  1407. if (interface.specific_id.has_value()) {
  1408. out_ << ", ";
  1409. FormatArg(interface.specific_id);
  1410. }
  1411. }
  1412. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1413. out_ << inst_namer_.GetLabelFor(scope_, id);
  1414. }
  1415. auto Formatter::FormatConstant(ConstantId id) -> void {
  1416. if (!id.has_value()) {
  1417. out_ << "<not constant>";
  1418. return;
  1419. }
  1420. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1421. FormatName(inst_id);
  1422. // For an attached constant, also list the unattached constant.
  1423. if (id.is_symbolic() && sem_ir_->constant_values()
  1424. .GetSymbolicConstant(id)
  1425. .generic_id.has_value()) {
  1426. // TODO: Skip printing this if it's the same as `inst_id`.
  1427. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1428. out_ << " (";
  1429. FormatName(unattached_inst_id);
  1430. out_ << ")";
  1431. }
  1432. }
  1433. auto Formatter::FormatInstAsType(InstId id) -> void {
  1434. if (!id.has_value()) {
  1435. out_ << "invalid";
  1436. return;
  1437. }
  1438. // Types are formatted in the `constants` scope because they typically refer
  1439. // to constants.
  1440. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1441. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1442. const_id.has_value()) {
  1443. FormatConstant(const_id);
  1444. } else {
  1445. // Type instruction didn't have a constant value. Fall back to printing
  1446. // the instruction name.
  1447. FormatArg(id);
  1448. }
  1449. }
  1450. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1451. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1452. if (!type_id.has_value()) {
  1453. out_ << "invalid";
  1454. return;
  1455. }
  1456. // Types are formatted in the `constants` scope because they typically refer
  1457. // to constants.
  1458. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1459. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1460. }
  1461. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1462. CARBON_CHECK(id.has_value(),
  1463. "Callers are responsible for checking `id.has_value`");
  1464. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1465. CARBON_CHECK(import_ir.library_id().has_value());
  1466. auto package_id = import_ir.package_id();
  1467. llvm::StringRef package_name =
  1468. package_id.AsIdentifierId().has_value()
  1469. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1470. : package_id.AsSpecialName();
  1471. llvm::StringRef library_name =
  1472. (import_ir.library_id() != LibraryNameId::Default)
  1473. ? import_ir.string_literal_values().Get(
  1474. import_ir.library_id().AsStringLiteralValueId())
  1475. : "default";
  1476. return llvm::formatv("{0}//{1}", package_name, library_name);
  1477. }
  1478. } // namespace Carbon::SemIR
  1479. // NOLINTEND(misc-no-recursion)