formatter.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  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::InPlaceInitializing:
  887. case ExprCategory::ReprInitializing: {
  888. out_ << "init ";
  889. FormatTypeOfInst(inst_id);
  890. auto init_target_id = FindStorageArgForInitializer(
  891. *sem_ir_, inst_id, /*allow_transitive=*/false);
  892. FormatReturnSlotArg(init_target_id);
  893. break;
  894. }
  895. }
  896. }
  897. out_ << " = ";
  898. }
  899. auto Formatter::FormatInstArgAndKind(Inst::ArgAndKind arg_and_kind) -> void {
  900. GetFormatArgFn(arg_and_kind.kind())(*this, arg_and_kind.value());
  901. }
  902. auto Formatter::FormatInstRhs(Inst inst) -> void {
  903. CARBON_KIND_SWITCH(inst) {
  904. case InstKind::ArrayInit:
  905. case InstKind::StructInit:
  906. case InstKind::TupleInit: {
  907. auto init = inst.As<AnyAggregateInit>();
  908. FormatArgs(init.elements_id);
  909. return;
  910. }
  911. case InstKind::ImportRefLoaded:
  912. case InstKind::ImportRefUnloaded:
  913. FormatImportRefRhs(inst.As<AnyImportRef>());
  914. return;
  915. case InstKind::OutParam:
  916. case InstKind::RefParam:
  917. case InstKind::ValueParam: {
  918. auto param = inst.As<AnyParam>();
  919. FormatArgs(param.index);
  920. // Omit pretty_name because it's an implementation detail of
  921. // pretty-printing.
  922. return;
  923. }
  924. case CARBON_KIND(AssociatedConstantDecl decl): {
  925. FormatArgs(decl.assoc_const_id);
  926. llvm::SaveAndRestore scope(scope_,
  927. inst_namer_.GetScopeFor(decl.assoc_const_id));
  928. FormatTrailingBlock(decl.decl_block_id);
  929. return;
  930. }
  931. case CARBON_KIND(SymbolicBinding bind): {
  932. // A SymbolicBinding with no value is a purely symbolic binding, such as
  933. // the `Self` in an interface. Don't print out `none` for the value.
  934. if (bind.value_id.has_value()) {
  935. FormatArgs(bind.entity_name_id, bind.value_id);
  936. } else {
  937. FormatArgs(bind.entity_name_id);
  938. }
  939. return;
  940. }
  941. case CARBON_KIND(BlockArg block): {
  942. out_ << " ";
  943. FormatLabel(block.block_id);
  944. return;
  945. }
  946. case CARBON_KIND(Call call): {
  947. FormatCallRhs(call);
  948. return;
  949. }
  950. case CARBON_KIND(ClassDecl decl): {
  951. FormatDeclRhs(decl.class_id,
  952. sem_ir_->classes().Get(decl.class_id).pattern_block_id,
  953. decl.decl_block_id);
  954. return;
  955. }
  956. case CARBON_KIND(CppTemplateNameType type): {
  957. // Omit the Clang declaration. We don't have a good way to format it, and
  958. // the entity name should suffice to identify the template.
  959. FormatArgs(type.name_id);
  960. return;
  961. }
  962. case CARBON_KIND(CustomLayoutType type): {
  963. out_ << " {";
  964. auto layout = sem_ir_->custom_layouts().Get(type.layout_id);
  965. out_ << "size=" << layout[CustomLayoutId::SizeIndex]
  966. << ", align=" << layout[CustomLayoutId::AlignIndex];
  967. for (auto [field, offset] : llvm::zip_equal(
  968. sem_ir_->struct_type_fields().Get(type.fields_id),
  969. layout.drop_front(CustomLayoutId::FirstFieldIndex))) {
  970. out_ << ", .";
  971. FormatName(field.name_id);
  972. out_ << "@" << offset << ": ";
  973. FormatInstAsType(field.type_inst_id);
  974. }
  975. out_ << "}";
  976. return;
  977. }
  978. case CARBON_KIND(FloatValue value): {
  979. llvm::SmallVector<char, 16> buffer;
  980. sem_ir_->floats().Get(value.float_id).toString(buffer);
  981. out_ << " " << buffer;
  982. return;
  983. }
  984. case CARBON_KIND(FunctionDecl decl): {
  985. FormatDeclRhs(decl.function_id,
  986. sem_ir_->functions().Get(decl.function_id).pattern_block_id,
  987. decl.decl_block_id);
  988. return;
  989. }
  990. case InstKind::ImportCppDecl: {
  991. FormatImportCppDeclRhs();
  992. return;
  993. }
  994. case CARBON_KIND(ImplDecl decl): {
  995. FormatDeclRhs(decl.impl_id,
  996. sem_ir_->impls().Get(decl.impl_id).pattern_block_id,
  997. decl.decl_block_id);
  998. return;
  999. }
  1000. case CARBON_KIND(InPlaceInit init): {
  1001. FormatArgs(init.src_id);
  1002. return;
  1003. }
  1004. case CARBON_KIND(InstValue inst): {
  1005. out_ << ' ';
  1006. OpenBrace();
  1007. // TODO: Should we use a more compact representation in the case where the
  1008. // inst is a SpliceBlock?
  1009. FormatInst(inst.inst_id);
  1010. CloseBrace();
  1011. return;
  1012. }
  1013. case CARBON_KIND(InterfaceDecl decl): {
  1014. FormatDeclRhs(
  1015. decl.interface_id,
  1016. sem_ir_->interfaces().Get(decl.interface_id).pattern_block_id,
  1017. decl.decl_block_id);
  1018. return;
  1019. }
  1020. case CARBON_KIND(IntValue value): {
  1021. out_ << " ";
  1022. sem_ir_->ints()
  1023. .Get(value.int_id)
  1024. .print(out_, sem_ir_->types().IsSignedInt(value.type_id));
  1025. return;
  1026. }
  1027. case CARBON_KIND(NameBindingDecl name): {
  1028. FormatTrailingBlock(name.pattern_block_id);
  1029. return;
  1030. }
  1031. case CARBON_KIND(NamedConstraintDecl decl): {
  1032. FormatDeclRhs(decl.named_constraint_id,
  1033. sem_ir_->named_constraints()
  1034. .Get(decl.named_constraint_id)
  1035. .pattern_block_id,
  1036. decl.decl_block_id);
  1037. return;
  1038. }
  1039. case CARBON_KIND(Namespace ns): {
  1040. if (ns.import_id.has_value()) {
  1041. FormatArgs(ns.import_id, ns.name_scope_id);
  1042. } else {
  1043. FormatArgs(ns.name_scope_id);
  1044. }
  1045. return;
  1046. }
  1047. case CARBON_KIND(RequireImplsDecl decl): {
  1048. FormatArgs(decl.require_impls_id);
  1049. llvm::SaveAndRestore scope(
  1050. scope_, inst_namer_.GetScopeFor(decl.require_impls_id));
  1051. FormatRequireImpls(decl.require_impls_id);
  1052. FormatTrailingBlock(decl.decl_block_id);
  1053. return;
  1054. }
  1055. case CARBON_KIND(ReturnExpr ret): {
  1056. FormatArgs(ret.expr_id);
  1057. if (ret.dest_id.has_value()) {
  1058. FormatReturnSlotArg(ret.dest_id);
  1059. }
  1060. return;
  1061. }
  1062. case CARBON_KIND(ReturnSlot ret): {
  1063. // Omit inst.type_inst_id because it's not semantically significant.
  1064. FormatArgs(ret.storage_id);
  1065. return;
  1066. }
  1067. case InstKind::ReturnSlotPattern:
  1068. // No-op because type_id is the only semantically significant field,
  1069. // and it's handled separately.
  1070. return;
  1071. case CARBON_KIND(SpliceBlock splice): {
  1072. FormatArgs(splice.result_id);
  1073. FormatTrailingBlock(splice.block_id);
  1074. return;
  1075. }
  1076. case CARBON_KIND(StructType struct_type): {
  1077. out_ << " {";
  1078. llvm::ListSeparator sep;
  1079. for (auto field :
  1080. sem_ir_->struct_type_fields().Get(struct_type.fields_id)) {
  1081. out_ << sep << ".";
  1082. FormatName(field.name_id);
  1083. out_ << ": ";
  1084. FormatInstAsType(field.type_inst_id);
  1085. }
  1086. out_ << "}";
  1087. return;
  1088. }
  1089. case CARBON_KIND(WhereExpr where): {
  1090. FormatArgs(where.period_self_id);
  1091. FormatTrailingBlock(where.requirements_id);
  1092. return;
  1093. }
  1094. default:
  1095. FormatInstRhsDefault(inst);
  1096. return;
  1097. }
  1098. }
  1099. auto Formatter::FormatInstRhsDefault(Inst inst) -> void {
  1100. auto arg0 = inst.arg0_and_kind();
  1101. if (arg0.kind() == IdKind::None) {
  1102. return;
  1103. }
  1104. out_ << " ";
  1105. FormatInstArgAndKind(arg0);
  1106. auto arg1 = inst.arg1_and_kind();
  1107. if (arg1.kind() == IdKind::None) {
  1108. return;
  1109. }
  1110. // Several instructions have a second operand that's a specific ID. We
  1111. // don't include it in the argument list if there is no corresponding
  1112. // specific, that is, when we're not in a generic context.
  1113. if (auto arg1_specific_id = arg1.TryAs<SpecificId>();
  1114. arg1_specific_id && !arg1_specific_id->has_value()) {
  1115. return;
  1116. }
  1117. // Similarly, instructions that have a `DestInstId` as the second operand
  1118. // typically use it for the output argument, so we omit it because it should
  1119. // already be part of the inst's formatted form expression.
  1120. if (arg1.kind() == IdKind::For<DestInstId>) {
  1121. return;
  1122. }
  1123. out_ << ", ";
  1124. FormatInstArgAndKind(arg1);
  1125. }
  1126. auto Formatter::FormatCallRhs(Call inst) -> void {
  1127. out_ << " ";
  1128. FormatArg(inst.callee_id);
  1129. if (!inst.args_id.has_value()) {
  1130. out_ << "(<none>)";
  1131. return;
  1132. }
  1133. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  1134. // If there's a return argument, don't print it here, because it's printed on
  1135. // the LHS.
  1136. auto callee_function = SemIR::GetCalleeAsFunction(*sem_ir_, inst.callee_id);
  1137. auto function = sem_ir_->functions().Get(callee_function.function_id);
  1138. auto return_form_id = function.GetDeclaredReturnForm(
  1139. *sem_ir_, callee_function.resolved_specific_id);
  1140. int return_arg_index = -1;
  1141. if (return_form_id.has_value()) {
  1142. if (auto init_form =
  1143. sem_ir_->insts().TryGetAs<SemIR::InitForm>(return_form_id)) {
  1144. auto type_id = sem_ir_->types().GetTypeIdForTypeInstId(
  1145. init_form->type_component_inst_id);
  1146. if (SemIR::InitRepr::ForType(*sem_ir_, type_id).MightBeInPlace()) {
  1147. return_arg_index = init_form->index.index;
  1148. }
  1149. }
  1150. }
  1151. llvm::ListSeparator sep;
  1152. out_ << '(';
  1153. for (auto [i, inst_id] : llvm::enumerate(args)) {
  1154. if (static_cast<int>(i) == return_arg_index) {
  1155. continue;
  1156. }
  1157. out_ << sep;
  1158. FormatArg(inst_id);
  1159. }
  1160. out_ << ')';
  1161. }
  1162. auto Formatter::FormatImportCppDeclRhs() -> void {
  1163. out_ << " ";
  1164. OpenBrace();
  1165. for (const Parse::Tree::PackagingNames& import :
  1166. sem_ir_->parse_tree().imports()) {
  1167. if (import.package_id != PackageNameId::Cpp) {
  1168. continue;
  1169. }
  1170. Indent();
  1171. out_ << "import Cpp";
  1172. if (import.library_id.has_value()) {
  1173. out_ << " \""
  1174. << FormatEscaped(
  1175. sem_ir_->string_literal_values().Get(import.library_id))
  1176. << "\"";
  1177. } else if (import.inline_body_id.has_value()) {
  1178. out_ << " inline";
  1179. }
  1180. out_ << "\n";
  1181. }
  1182. CloseBrace();
  1183. }
  1184. auto Formatter::FormatImportRefRhs(AnyImportRef inst) -> void {
  1185. out_ << " ";
  1186. auto import_ir_inst = sem_ir_->import_ir_insts().Get(inst.import_ir_inst_id);
  1187. FormatArg(import_ir_inst.ir_id());
  1188. out_ << ", ";
  1189. if (inst.entity_name_id.has_value()) {
  1190. // Prefer to show the entity name when possible.
  1191. FormatArg(inst.entity_name_id);
  1192. } else {
  1193. // Show a name based on the location when possible, or the numeric
  1194. // instruction as a last resort.
  1195. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  1196. auto loc_id =
  1197. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  1198. switch (loc_id.kind()) {
  1199. case LocId::Kind::None: {
  1200. out_ << import_ir_inst.inst_id() << " [no loc]";
  1201. break;
  1202. }
  1203. case LocId::Kind::ImportIRInstId: {
  1204. // TODO: Probably don't want to format each indirection, but maybe
  1205. // reuse GetCanonicalImportIRInst?
  1206. out_ << import_ir_inst.inst_id() << " [indirect]";
  1207. break;
  1208. }
  1209. case LocId::Kind::NodeId: {
  1210. // Formats a NodeId from the import.
  1211. const auto& tree = import_ir.sem_ir->parse_tree();
  1212. auto token = tree.node_token(loc_id.node_id());
  1213. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1214. << tree.tokens().GetColumnNumber(token);
  1215. break;
  1216. }
  1217. case LocId::Kind::InstId:
  1218. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1219. }
  1220. }
  1221. out_ << ", "
  1222. << (inst.kind == InstKind::ImportRefLoaded ? "loaded" : "unloaded");
  1223. }
  1224. auto Formatter::FormatRequireImpls(RequireImplsId id) -> void {
  1225. out_ << ' ';
  1226. const auto& require = sem_ir_->require_impls().Get(id);
  1227. OpenBrace();
  1228. Indent();
  1229. out_ << "require ";
  1230. FormatArg(require.self_id);
  1231. out_ << " impls ";
  1232. FormatArg(require.facet_type_inst_id);
  1233. out_ << "\n";
  1234. CloseBrace();
  1235. }
  1236. auto Formatter::FormatRequireImplsBlock(RequireImplsBlockId block_id) -> void {
  1237. IndentLabel();
  1238. out_ << "!requires:\n";
  1239. if (!block_id.has_value()) {
  1240. return;
  1241. }
  1242. for (auto require_impls_id : sem_ir_->require_impls_blocks().Get(block_id)) {
  1243. Indent();
  1244. FormatArg(require_impls_id);
  1245. FormatRequireImpls(require_impls_id);
  1246. out_ << "\n";
  1247. }
  1248. }
  1249. auto Formatter::FormatArg(EntityNameId id) -> void {
  1250. if (!id.has_value()) {
  1251. out_ << "_";
  1252. return;
  1253. }
  1254. const auto& info = sem_ir_->entity_names().Get(id);
  1255. FormatName(info.name_id);
  1256. if (info.bind_index().has_value()) {
  1257. out_ << ", " << info.bind_index().index;
  1258. }
  1259. if (info.is_template) {
  1260. out_ << ", template";
  1261. }
  1262. }
  1263. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1264. const auto& info = sem_ir_->facet_types().Get(id);
  1265. // Nothing output to indicate that this is a facet type since this is only
  1266. // used as the argument to a `facet_type` instruction.
  1267. out_ << "<";
  1268. llvm::ListSeparator sep(" & ");
  1269. if (info.extend_constraints.empty() &&
  1270. info.extend_named_constraints.empty()) {
  1271. out_ << "type";
  1272. } else {
  1273. for (auto extend : info.extend_constraints) {
  1274. out_ << sep;
  1275. FormatName(extend.interface_id);
  1276. if (extend.specific_id.has_value()) {
  1277. out_ << ", ";
  1278. FormatName(extend.specific_id);
  1279. }
  1280. }
  1281. for (auto extend : info.extend_named_constraints) {
  1282. out_ << sep;
  1283. FormatName(extend.named_constraint_id);
  1284. if (extend.specific_id.has_value()) {
  1285. out_ << ", ";
  1286. FormatName(extend.specific_id);
  1287. }
  1288. }
  1289. }
  1290. if (info.other_requirements || !info.self_impls_constraints.empty() ||
  1291. !info.rewrite_constraints.empty()) {
  1292. out_ << " where ";
  1293. llvm::ListSeparator and_sep(" and ");
  1294. if (!info.self_impls_constraints.empty() ||
  1295. !info.self_impls_named_constraints.empty()) {
  1296. out_ << and_sep << ".Self impls ";
  1297. llvm::ListSeparator amp_sep(" & ");
  1298. for (auto self_impls : info.self_impls_constraints) {
  1299. out_ << amp_sep;
  1300. FormatName(self_impls.interface_id);
  1301. if (self_impls.specific_id.has_value()) {
  1302. out_ << ", ";
  1303. FormatName(self_impls.specific_id);
  1304. }
  1305. }
  1306. for (auto self_impls : info.self_impls_named_constraints) {
  1307. out_ << amp_sep;
  1308. FormatName(self_impls.named_constraint_id);
  1309. if (self_impls.specific_id.has_value()) {
  1310. out_ << ", ";
  1311. FormatName(self_impls.specific_id);
  1312. }
  1313. }
  1314. }
  1315. for (auto rewrite : info.rewrite_constraints) {
  1316. out_ << and_sep;
  1317. FormatArg(rewrite.lhs_id);
  1318. out_ << " = ";
  1319. FormatArg(rewrite.rhs_id);
  1320. }
  1321. if (info.other_requirements) {
  1322. out_ << and_sep << "TODO";
  1323. }
  1324. }
  1325. out_ << ">";
  1326. }
  1327. auto Formatter::FormatArg(ImportIRId id) -> void {
  1328. if (id.has_value()) {
  1329. out_ << GetImportIRLabel(id);
  1330. } else {
  1331. out_ << id;
  1332. }
  1333. }
  1334. auto Formatter::FormatArg(IntId id) -> void {
  1335. // We don't know the signedness to use here. Default to unsigned.
  1336. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  1337. }
  1338. auto Formatter::FormatArg(NameScopeId id) -> void {
  1339. OpenBrace();
  1340. FormatNameScope(id);
  1341. CloseBrace();
  1342. }
  1343. auto Formatter::FormatArg(InstBlockId id) -> void {
  1344. if (!id.has_value()) {
  1345. out_ << "invalid";
  1346. return;
  1347. }
  1348. out_ << '(';
  1349. llvm::ListSeparator sep;
  1350. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1351. out_ << sep;
  1352. FormatArg(inst_id);
  1353. }
  1354. out_ << ')';
  1355. }
  1356. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1357. FormatArg(static_cast<InstBlockId>(id));
  1358. }
  1359. auto Formatter::FormatArg(RealId id) -> void {
  1360. // TODO: Format with a `.` when the exponent is near zero.
  1361. const auto& real = sem_ir_->reals().Get(id);
  1362. real.mantissa.print(out_, /*isSigned=*/false);
  1363. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1364. }
  1365. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1366. out_ << '"'
  1367. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1368. /*use_hex_escapes=*/true)
  1369. << '"';
  1370. }
  1371. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1372. if (dest_id.has_value()) {
  1373. out_ << " to ";
  1374. FormatArg(dest_id);
  1375. }
  1376. }
  1377. auto Formatter::FormatName(NameId id) -> void {
  1378. out_ << sem_ir_->names().GetFormatted(id);
  1379. }
  1380. auto Formatter::FormatName(InstId id) -> void {
  1381. if (id.has_value()) {
  1382. IncludeChunkInOutput(tentative_inst_chunks_.Get(id));
  1383. }
  1384. out_ << inst_namer_.GetNameFor(scope_, id);
  1385. }
  1386. auto Formatter::FormatName(SpecificId id) -> void {
  1387. const auto& specific = sem_ir_->specifics().Get(id);
  1388. FormatName(specific.generic_id);
  1389. FormatArg(specific.args_id);
  1390. }
  1391. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1392. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1393. FormatName(interface.interface_id);
  1394. if (interface.specific_id.has_value()) {
  1395. out_ << ", ";
  1396. FormatArg(interface.specific_id);
  1397. }
  1398. }
  1399. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1400. out_ << inst_namer_.GetLabelFor(scope_, id);
  1401. }
  1402. auto Formatter::FormatConstant(ConstantId id) -> void {
  1403. if (!id.has_value()) {
  1404. out_ << "<not constant>";
  1405. return;
  1406. }
  1407. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1408. FormatName(inst_id);
  1409. // For an attached constant, also list the unattached constant.
  1410. if (id.is_symbolic() && sem_ir_->constant_values()
  1411. .GetSymbolicConstant(id)
  1412. .generic_id.has_value()) {
  1413. // TODO: Skip printing this if it's the same as `inst_id`.
  1414. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1415. out_ << " (";
  1416. FormatName(unattached_inst_id);
  1417. out_ << ")";
  1418. }
  1419. }
  1420. auto Formatter::FormatInstAsType(InstId id) -> void {
  1421. if (!id.has_value()) {
  1422. out_ << "invalid";
  1423. return;
  1424. }
  1425. // Types are formatted in the `constants` scope because they typically refer
  1426. // to constants.
  1427. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1428. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1429. const_id.has_value()) {
  1430. FormatConstant(const_id);
  1431. } else {
  1432. // Type instruction didn't have a constant value. Fall back to printing
  1433. // the instruction name.
  1434. FormatArg(id);
  1435. }
  1436. }
  1437. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1438. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1439. if (!type_id.has_value()) {
  1440. out_ << "invalid";
  1441. return;
  1442. }
  1443. // Types are formatted in the `constants` scope because they typically refer
  1444. // to constants.
  1445. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1446. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1447. }
  1448. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1449. CARBON_CHECK(id.has_value(),
  1450. "Callers are responsible for checking `id.has_value`");
  1451. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1452. CARBON_CHECK(import_ir.library_id().has_value());
  1453. auto package_id = import_ir.package_id();
  1454. llvm::StringRef package_name =
  1455. package_id.AsIdentifierId().has_value()
  1456. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1457. : package_id.AsSpecialName();
  1458. llvm::StringRef library_name =
  1459. (import_ir.library_id() != LibraryNameId::Default)
  1460. ? import_ir.string_literal_values().Get(
  1461. import_ir.library_id().AsStringLiteralValueId())
  1462. : "default";
  1463. return llvm::formatv("{0}//{1}", package_name, library_name);
  1464. }
  1465. } // namespace Carbon::SemIR
  1466. // NOLINTEND(misc-no-recursion)