formatter.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647
  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. IdTag(), 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. // Print the !members label even if the name scope is empty because we
  436. // always list the witness in this section.
  437. IndentLabel();
  438. out_ << "!members:\n";
  439. if (impl_info.scope_id.has_value()) {
  440. FormatNameScope(impl_info.scope_id);
  441. }
  442. Indent();
  443. out_ << "witness = ";
  444. FormatArg(impl_info.witness_id);
  445. out_ << "\n";
  446. CloseBrace();
  447. } else {
  448. Semicolon();
  449. }
  450. out_ << '\n';
  451. FormatEntityEnd(impl_info.generic_id);
  452. }
  453. auto Formatter::FormatFunction(FunctionId id, const Function& fn) -> void {
  454. if (!ShouldFormatEntity(fn)) {
  455. return;
  456. }
  457. std::string function_start;
  458. switch (fn.virtual_modifier) {
  459. case FunctionFields::VirtualModifier::Virtual:
  460. function_start += "virtual ";
  461. break;
  462. case FunctionFields::VirtualModifier::Abstract:
  463. function_start += "abstract ";
  464. break;
  465. case FunctionFields::VirtualModifier::Override:
  466. function_start += "override ";
  467. break;
  468. case FunctionFields::VirtualModifier::None:
  469. break;
  470. }
  471. if (fn.is_extern) {
  472. function_start += "extern ";
  473. }
  474. function_start += "fn";
  475. PrepareToFormatDecl(fn.first_owning_decl_id);
  476. FormatEntityStart(function_start, fn, id);
  477. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  478. auto return_type_info = ReturnTypeInfo::ForFunction(*sem_ir_, fn);
  479. FormatParamList(fn.call_params_id, return_type_info.is_valid() &&
  480. return_type_info.has_return_slot());
  481. if (fn.builtin_function_kind() != BuiltinFunctionKind::None) {
  482. out_ << " = \""
  483. << FormatEscaped(fn.builtin_function_kind().name(),
  484. /*use_hex_escapes=*/true)
  485. << "\"";
  486. }
  487. if (fn.thunk_decl_id().has_value()) {
  488. out_ << " [thunk ";
  489. FormatArg(fn.thunk_decl_id());
  490. out_ << "]";
  491. }
  492. if (!fn.body_block_ids.empty()) {
  493. out_ << ' ';
  494. OpenBrace();
  495. for (auto block_id : fn.body_block_ids) {
  496. IndentLabel();
  497. FormatLabel(block_id);
  498. out_ << ":\n";
  499. FormatCodeBlock(block_id);
  500. }
  501. CloseBrace();
  502. } else {
  503. Semicolon();
  504. }
  505. out_ << '\n';
  506. FormatEntityEnd(fn.generic_id);
  507. }
  508. auto Formatter::FormatSpecificRegion(const Generic& generic,
  509. const Specific& specific,
  510. GenericInstIndex::Region region,
  511. llvm::StringRef region_name) -> void {
  512. if (!specific.GetValueBlock(region).has_value()) {
  513. return;
  514. }
  515. if (!region_name.empty()) {
  516. IndentLabel();
  517. out_ << "!" << region_name << ":\n";
  518. }
  519. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  520. sem_ir_->inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  521. sem_ir_->inst_blocks().GetOrEmpty(specific.GetValueBlock(region)))) {
  522. Indent();
  523. if (generic_inst_id) {
  524. FormatName(*generic_inst_id);
  525. } else {
  526. out_ << "<missing>";
  527. }
  528. out_ << " => ";
  529. if (specific_inst_id) {
  530. FormatName(*specific_inst_id);
  531. } else {
  532. out_ << "<missing>";
  533. }
  534. out_ << "\n";
  535. }
  536. }
  537. auto Formatter::FormatSpecific(SpecificId id, const Specific& specific)
  538. -> void {
  539. const auto& generic = sem_ir_->generics().Get(specific.generic_id);
  540. if (!ShouldFormatEntity(generic.decl_id)) {
  541. // Omit specifics if we also omitted the generic.
  542. return;
  543. }
  544. if (specific.IsUnresolved()) {
  545. // Omit specifics that were never resolved. Such specifics exist only to
  546. // track the way the arguments were spelled, and that information is
  547. // conveyed entirely by the name of the specific. These specifics may also
  548. // not be referenced by any SemIR that we format, so including them adds
  549. // clutter and possibly emits references to instructions we didn't name.
  550. return;
  551. }
  552. llvm::SaveAndRestore generic_scope(
  553. scope_, inst_namer_.GetScopeFor(specific.generic_id));
  554. out_ << "\n";
  555. out_ << "specific ";
  556. FormatName(id);
  557. out_ << " ";
  558. OpenBrace();
  559. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Declaration,
  560. "");
  561. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Definition,
  562. "definition");
  563. CloseBrace();
  564. out_ << "\n";
  565. }
  566. auto Formatter::PrepareToFormatDecl(InstId first_owning_decl_id) -> void {
  567. // If this decl was imported from a different IR, annotate the name of
  568. // that IR in the output before the `{` or `;`.
  569. if (first_owning_decl_id.has_value()) {
  570. auto import_ir_inst_id =
  571. sem_ir_->insts().GetImportSource(first_owning_decl_id);
  572. if (import_ir_inst_id.has_value()) {
  573. auto import_ir_id =
  574. sem_ir_->import_ir_insts().Get(import_ir_inst_id).ir_id();
  575. if (const auto* import_file =
  576. sem_ir_->import_irs().Get(import_ir_id).sem_ir) {
  577. pending_imported_from_ = import_file->filename();
  578. }
  579. }
  580. }
  581. }
  582. auto Formatter::FormatGenericStart(llvm::StringRef entity_kind,
  583. GenericId generic_id) -> void {
  584. const auto& generic = sem_ir_->generics().Get(generic_id);
  585. out_ << "\n";
  586. Indent();
  587. out_ << "generic " << entity_kind << " ";
  588. FormatName(generic_id);
  589. llvm::SaveAndRestore generic_scope(scope_,
  590. inst_namer_.GetScopeFor(generic_id));
  591. FormatParamList(generic.bindings_id);
  592. out_ << " ";
  593. OpenBrace();
  594. FormatCodeBlock(generic.decl_block_id);
  595. if (generic.definition_block_id.has_value()) {
  596. IndentLabel();
  597. out_ << "!definition:\n";
  598. FormatCodeBlock(generic.definition_block_id);
  599. }
  600. }
  601. auto Formatter::FormatEntityEnd(GenericId generic_id) -> void {
  602. if (generic_id.has_value()) {
  603. FormatGenericEnd();
  604. }
  605. }
  606. auto Formatter::FormatGenericEnd() -> void {
  607. CloseBrace();
  608. out_ << '\n';
  609. }
  610. auto Formatter::FormatParamList(InstBlockId params_id, bool has_return_slot)
  611. -> void {
  612. if (!params_id.has_value()) {
  613. // TODO: This happens for imported functions, for which we don't currently
  614. // import the call parameters list.
  615. return;
  616. }
  617. llvm::StringLiteral close = ")";
  618. out_ << "(";
  619. llvm::ListSeparator sep;
  620. for (InstId param_id : sem_ir_->inst_blocks().Get(params_id)) {
  621. auto is_out_param = sem_ir_->insts().Is<OutParam>(param_id);
  622. if (is_out_param) {
  623. // TODO: An input parameter following an output parameter is formatted a
  624. // bit strangely. For example, alternating input and output parameters
  625. // produces:
  626. //
  627. // fn @F(%in1: %t) -> %out1: %t, %in2: %t -> %out2: %t
  628. //
  629. // This doesn't actually happen right now, though.
  630. out_ << std::exchange(close, llvm::StringLiteral(""));
  631. out_ << " -> ";
  632. } else {
  633. out_ << sep;
  634. }
  635. if (!param_id.has_value()) {
  636. out_ << "invalid";
  637. continue;
  638. }
  639. // Don't include the name of the return slot parameter if the function
  640. // doesn't have a return slot; the name won't be used for anything in that
  641. // case.
  642. // TODO: Should the call parameter even exist in that case? There isn't a
  643. // corresponding argument in a `call` instruction.
  644. if (!is_out_param || has_return_slot) {
  645. FormatName(param_id);
  646. out_ << ": ";
  647. }
  648. FormatTypeOfInst(param_id);
  649. }
  650. out_ << close;
  651. }
  652. auto Formatter::FormatCodeBlock(InstBlockId block_id) -> void {
  653. bool elided = false;
  654. for (const InstId inst_id : sem_ir_->inst_blocks().GetOrEmpty(block_id)) {
  655. if (ShouldFormatInst(inst_id)) {
  656. FormatInst(inst_id);
  657. elided = false;
  658. } else if (!elided) {
  659. // When formatting a block, leave a hint that instructions were elided.
  660. Indent();
  661. out_ << "<elided>\n";
  662. elided = true;
  663. }
  664. }
  665. }
  666. auto Formatter::FormatTrailingBlock(InstBlockId block_id) -> void {
  667. out_ << ' ';
  668. OpenBrace();
  669. FormatCodeBlock(block_id);
  670. CloseBrace();
  671. }
  672. auto Formatter::FormatNameScope(NameScopeId id, llvm::StringRef label) -> void {
  673. const auto& scope = sem_ir_->name_scopes().Get(id);
  674. if (scope.entries().empty() && scope.extended_scopes().empty() &&
  675. scope.import_ir_scopes().empty() && !scope.is_cpp_scope() &&
  676. !scope.has_error()) {
  677. // Name scope is empty.
  678. return;
  679. }
  680. if (!label.empty()) {
  681. IndentLabel();
  682. out_ << label;
  683. }
  684. for (auto [name_id, result] : scope.entries()) {
  685. Indent();
  686. out_ << ".";
  687. FormatName(name_id);
  688. switch (result.access_kind()) {
  689. case AccessKind::Public:
  690. break;
  691. case AccessKind::Protected:
  692. out_ << " [protected]";
  693. break;
  694. case AccessKind::Private:
  695. out_ << " [private]";
  696. break;
  697. }
  698. out_ << " = ";
  699. if (result.is_poisoned()) {
  700. out_ << "<poisoned>";
  701. } else {
  702. FormatName(result.is_found() ? result.target_inst_id() : InstId::None);
  703. }
  704. out_ << "\n";
  705. }
  706. for (auto extended_scope_id : scope.extended_scopes()) {
  707. Indent();
  708. out_ << "extend ";
  709. FormatName(extended_scope_id);
  710. out_ << "\n";
  711. }
  712. // This is used to cluster all "Core//prelude/..." imports, but not
  713. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  714. // add or remove an unused prelude file, but is intended to still show the
  715. // existence of indirect imports.
  716. bool has_prelude_components = false;
  717. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  718. auto label = GetImportIRLabel(import_ir_id);
  719. if (label.starts_with("Core//prelude/")) {
  720. if (has_prelude_components) {
  721. // Only print the existence once.
  722. continue;
  723. } else {
  724. has_prelude_components = true;
  725. label = "Core//prelude/...";
  726. }
  727. }
  728. Indent();
  729. out_ << "import " << label << "\n";
  730. }
  731. if (scope.is_cpp_scope()) {
  732. Indent();
  733. out_ << "import Cpp//...\n";
  734. }
  735. if (scope.has_error()) {
  736. Indent();
  737. out_ << "has_error\n";
  738. }
  739. }
  740. auto Formatter::FormatInst(InstId inst_id) -> void {
  741. if (!inst_id.has_value()) {
  742. Indent();
  743. out_ << "none\n";
  744. return;
  745. }
  746. if (!in_terminator_sequence_) {
  747. Indent();
  748. }
  749. auto inst = sem_ir_->insts().GetWithAttachedType(inst_id);
  750. CARBON_KIND_SWITCH(inst) {
  751. case CARBON_KIND(Branch branch): {
  752. out_ << Branch::Kind.ir_name() << " ";
  753. FormatLabel(branch.target_id);
  754. out_ << "\n";
  755. in_terminator_sequence_ = false;
  756. return;
  757. }
  758. case CARBON_KIND(BranchIf branch_if): {
  759. out_ << "if ";
  760. FormatName(branch_if.cond_id);
  761. out_ << " " << Branch::Kind.ir_name() << " ";
  762. FormatLabel(branch_if.target_id);
  763. out_ << " else ";
  764. in_terminator_sequence_ = true;
  765. return;
  766. }
  767. case CARBON_KIND(BranchWithArg branch_with_arg): {
  768. out_ << BranchWithArg::Kind.ir_name() << " ";
  769. FormatLabel(branch_with_arg.target_id);
  770. out_ << "(";
  771. FormatName(branch_with_arg.arg_id);
  772. out_ << ")\n";
  773. in_terminator_sequence_ = false;
  774. return;
  775. }
  776. default: {
  777. FormatInstLhs(inst_id, inst);
  778. out_ << inst.kind().ir_name();
  779. // Add constants for everything except `ImportRefUnloaded`.
  780. if (!inst.Is<ImportRefUnloaded>()) {
  781. pending_constant_value_ =
  782. sem_ir_->constant_values().GetAttached(inst_id);
  783. pending_constant_value_is_self_ =
  784. sem_ir_->constant_values().GetInstIdIfValid(
  785. pending_constant_value_) == inst_id;
  786. }
  787. FormatInstRhs(inst);
  788. // This usually prints the constant, but when `FormatInstRhs` prints it
  789. // first (or for `ImportRefUnloaded`), this does nothing.
  790. FormatPendingConstantValue(AddSpace::Before);
  791. out_ << "\n";
  792. return;
  793. }
  794. }
  795. }
  796. auto Formatter::FormatPendingImportedFrom(AddSpace space_where) -> void {
  797. if (pending_imported_from_.empty()) {
  798. return;
  799. }
  800. if (space_where == AddSpace::Before) {
  801. out_ << ' ';
  802. }
  803. out_ << "[from \"" << FormatEscaped(pending_imported_from_) << "\"]";
  804. if (space_where == AddSpace::After) {
  805. out_ << ' ';
  806. }
  807. pending_imported_from_ = llvm::StringRef();
  808. }
  809. auto Formatter::FormatPendingConstantValue(AddSpace space_where) -> void {
  810. if (pending_constant_value_ == ConstantId::NotConstant) {
  811. return;
  812. }
  813. if (space_where == AddSpace::Before) {
  814. out_ << ' ';
  815. }
  816. out_ << '[';
  817. if (pending_constant_value_.has_value()) {
  818. switch (sem_ir_->constant_values().GetDependence(pending_constant_value_)) {
  819. case ConstantDependence::None:
  820. out_ << "concrete";
  821. break;
  822. case ConstantDependence::PeriodSelf:
  823. out_ << "symbolic_self";
  824. break;
  825. // TODO: Consider renaming this. This will cause a lot of SemIR churn.
  826. case ConstantDependence::Checked:
  827. out_ << "symbolic";
  828. break;
  829. case ConstantDependence::Template:
  830. out_ << "template";
  831. break;
  832. }
  833. if (!pending_constant_value_is_self_) {
  834. out_ << " = ";
  835. FormatConstant(pending_constant_value_);
  836. }
  837. } else {
  838. out_ << pending_constant_value_;
  839. }
  840. out_ << ']';
  841. if (space_where == AddSpace::After) {
  842. out_ << ' ';
  843. }
  844. pending_constant_value_ = ConstantId::NotConstant;
  845. }
  846. auto Formatter::FormatInstLhs(InstId inst_id, Inst inst) -> void {
  847. // Every typed instruction is named, and there are some untyped instructions
  848. // that have names (such as `ImportRefUnloaded`). When there's a typed
  849. // instruction with no name, it means an instruction is incorrectly not named
  850. // -- but should be printed as such.
  851. bool has_name = inst_namer_.has_name(inst_id);
  852. if (!has_name && !inst.kind().has_type()) {
  853. return;
  854. }
  855. FormatName(inst_id);
  856. if (inst.kind().has_type()) {
  857. out_ << ": ";
  858. switch (GetExprCategory(*sem_ir_, inst_id)) {
  859. case ExprCategory::NotExpr:
  860. case ExprCategory::Error:
  861. case ExprCategory::Value:
  862. case ExprCategory::Pattern:
  863. case ExprCategory::Mixed:
  864. break;
  865. case ExprCategory::DurableRef:
  866. case ExprCategory::EphemeralRef:
  867. out_ << "ref ";
  868. break;
  869. case ExprCategory::Initializing:
  870. out_ << "init ";
  871. break;
  872. }
  873. FormatTypeOfInst(inst_id);
  874. }
  875. out_ << " = ";
  876. }
  877. auto Formatter::FormatInstArgAndKind(Inst::ArgAndKind arg_and_kind) -> void {
  878. GetFormatArgFn(arg_and_kind.kind())(*this, arg_and_kind.value());
  879. }
  880. auto Formatter::FormatInstRhs(Inst inst) -> void {
  881. CARBON_KIND_SWITCH(inst) {
  882. case InstKind::ArrayInit:
  883. case InstKind::StructInit:
  884. case InstKind::TupleInit: {
  885. auto init = inst.As<AnyAggregateInit>();
  886. FormatArgs(init.elements_id);
  887. FormatReturnSlotArg(init.dest_id);
  888. return;
  889. }
  890. case InstKind::ImportRefLoaded:
  891. case InstKind::ImportRefUnloaded:
  892. FormatImportRefRhs(inst.As<AnyImportRef>());
  893. return;
  894. case InstKind::OutParam:
  895. case InstKind::RefParam:
  896. case InstKind::ValueParam: {
  897. auto param = inst.As<AnyParam>();
  898. FormatArgs(param.index);
  899. // Omit pretty_name because it's an implementation detail of
  900. // pretty-printing.
  901. return;
  902. }
  903. case CARBON_KIND(AssociatedConstantDecl decl): {
  904. FormatArgs(decl.assoc_const_id);
  905. llvm::SaveAndRestore scope(scope_,
  906. inst_namer_.GetScopeFor(decl.assoc_const_id));
  907. FormatTrailingBlock(decl.decl_block_id);
  908. return;
  909. }
  910. case CARBON_KIND(SymbolicBinding bind): {
  911. // A SymbolicBinding with no value is a purely symbolic binding, such as
  912. // the `Self` in an interface. Don't print out `none` for the value.
  913. if (bind.value_id.has_value()) {
  914. FormatArgs(bind.entity_name_id, bind.value_id);
  915. } else {
  916. FormatArgs(bind.entity_name_id);
  917. }
  918. return;
  919. }
  920. case CARBON_KIND(BlockArg block): {
  921. out_ << " ";
  922. FormatLabel(block.block_id);
  923. return;
  924. }
  925. case CARBON_KIND(Call call): {
  926. FormatCallRhs(call);
  927. return;
  928. }
  929. case CARBON_KIND(ClassDecl decl): {
  930. FormatDeclRhs(decl.class_id,
  931. sem_ir_->classes().Get(decl.class_id).pattern_block_id,
  932. decl.decl_block_id);
  933. return;
  934. }
  935. case CARBON_KIND(CustomLayoutType type): {
  936. out_ << " {";
  937. auto layout = sem_ir_->custom_layouts().Get(type.layout_id);
  938. out_ << "size=" << layout[CustomLayoutId::SizeIndex]
  939. << ", align=" << layout[CustomLayoutId::AlignIndex];
  940. for (auto [field, offset] : llvm::zip_equal(
  941. sem_ir_->struct_type_fields().Get(type.fields_id),
  942. layout.drop_front(CustomLayoutId::FirstFieldIndex))) {
  943. out_ << ", .";
  944. FormatName(field.name_id);
  945. out_ << "@" << offset << ": ";
  946. FormatInstAsType(field.type_inst_id);
  947. }
  948. out_ << "}";
  949. return;
  950. }
  951. case CARBON_KIND(FloatValue value): {
  952. llvm::SmallVector<char, 16> buffer;
  953. sem_ir_->floats().Get(value.float_id).toString(buffer);
  954. out_ << " " << buffer;
  955. return;
  956. }
  957. case CARBON_KIND(FunctionDecl decl): {
  958. FormatDeclRhs(decl.function_id,
  959. sem_ir_->functions().Get(decl.function_id).pattern_block_id,
  960. decl.decl_block_id);
  961. return;
  962. }
  963. case InstKind::ImportCppDecl: {
  964. FormatImportCppDeclRhs();
  965. return;
  966. }
  967. case CARBON_KIND(ImplDecl decl): {
  968. FormatDeclRhs(decl.impl_id,
  969. sem_ir_->impls().Get(decl.impl_id).pattern_block_id,
  970. decl.decl_block_id);
  971. return;
  972. }
  973. case CARBON_KIND(InitializeFrom init): {
  974. FormatArgs(init.src_id);
  975. FormatReturnSlotArg(init.dest_id);
  976. return;
  977. }
  978. case CARBON_KIND(InstValue inst): {
  979. out_ << ' ';
  980. OpenBrace();
  981. // TODO: Should we use a more compact representation in the case where the
  982. // inst is a SpliceBlock?
  983. FormatInst(inst.inst_id);
  984. CloseBrace();
  985. return;
  986. }
  987. case CARBON_KIND(InterfaceDecl decl): {
  988. FormatDeclRhs(
  989. decl.interface_id,
  990. sem_ir_->interfaces().Get(decl.interface_id).pattern_block_id,
  991. decl.decl_block_id);
  992. return;
  993. }
  994. case CARBON_KIND(IntValue value): {
  995. out_ << " ";
  996. sem_ir_->ints()
  997. .Get(value.int_id)
  998. .print(out_, sem_ir_->types().IsSignedInt(value.type_id));
  999. return;
  1000. }
  1001. case CARBON_KIND(NameBindingDecl name): {
  1002. FormatTrailingBlock(name.pattern_block_id);
  1003. return;
  1004. }
  1005. case CARBON_KIND(NamedConstraintDecl decl): {
  1006. FormatDeclRhs(decl.named_constraint_id,
  1007. sem_ir_->named_constraints()
  1008. .Get(decl.named_constraint_id)
  1009. .pattern_block_id,
  1010. decl.decl_block_id);
  1011. return;
  1012. }
  1013. case CARBON_KIND(Namespace ns): {
  1014. if (ns.import_id.has_value()) {
  1015. FormatArgs(ns.import_id, ns.name_scope_id);
  1016. } else {
  1017. FormatArgs(ns.name_scope_id);
  1018. }
  1019. return;
  1020. }
  1021. case CARBON_KIND(RequireImplsDecl decl): {
  1022. FormatArgs(decl.require_impls_id);
  1023. llvm::SaveAndRestore scope(
  1024. scope_, inst_namer_.GetScopeFor(decl.require_impls_id));
  1025. FormatRequireImpls(decl.require_impls_id);
  1026. FormatTrailingBlock(decl.decl_block_id);
  1027. return;
  1028. }
  1029. case CARBON_KIND(ReturnExpr ret): {
  1030. FormatArgs(ret.expr_id);
  1031. if (ret.dest_id.has_value()) {
  1032. FormatReturnSlotArg(ret.dest_id);
  1033. }
  1034. return;
  1035. }
  1036. case CARBON_KIND(ReturnSlot ret): {
  1037. // Omit inst.type_inst_id because it's not semantically significant.
  1038. FormatArgs(ret.storage_id);
  1039. return;
  1040. }
  1041. case InstKind::ReturnSlotPattern:
  1042. // No-op because type_id is the only semantically significant field,
  1043. // and it's handled separately.
  1044. return;
  1045. case CARBON_KIND(SpliceBlock splice): {
  1046. FormatArgs(splice.result_id);
  1047. FormatTrailingBlock(splice.block_id);
  1048. return;
  1049. }
  1050. case CARBON_KIND(StructType struct_type): {
  1051. out_ << " {";
  1052. llvm::ListSeparator sep;
  1053. for (auto field :
  1054. sem_ir_->struct_type_fields().Get(struct_type.fields_id)) {
  1055. out_ << sep << ".";
  1056. FormatName(field.name_id);
  1057. out_ << ": ";
  1058. FormatInstAsType(field.type_inst_id);
  1059. }
  1060. out_ << "}";
  1061. return;
  1062. }
  1063. case CARBON_KIND(WhereExpr where): {
  1064. FormatArgs(where.period_self_id);
  1065. FormatTrailingBlock(where.requirements_id);
  1066. return;
  1067. }
  1068. default:
  1069. FormatInstRhsDefault(inst);
  1070. return;
  1071. }
  1072. }
  1073. auto Formatter::FormatInstRhsDefault(Inst inst) -> void {
  1074. auto arg0 = inst.arg0_and_kind();
  1075. if (arg0.kind() == IdKind::None) {
  1076. return;
  1077. }
  1078. out_ << " ";
  1079. FormatInstArgAndKind(arg0);
  1080. auto arg1 = inst.arg1_and_kind();
  1081. if (arg1.kind() == IdKind::None) {
  1082. return;
  1083. }
  1084. // Several instructions have a second operand that's a specific ID. We
  1085. // don't include it in the argument list if there is no corresponding
  1086. // specific, that is, when we're not in a generic context.
  1087. if (auto arg1_specific_id = arg1.TryAs<SpecificId>();
  1088. arg1_specific_id && !arg1_specific_id->has_value()) {
  1089. return;
  1090. }
  1091. out_ << ", ";
  1092. FormatInstArgAndKind(arg1);
  1093. }
  1094. auto Formatter::FormatCallRhs(Call inst) -> void {
  1095. out_ << " ";
  1096. FormatArg(inst.callee_id);
  1097. if (!inst.args_id.has_value()) {
  1098. out_ << "(<none>)";
  1099. return;
  1100. }
  1101. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  1102. auto return_info = ReturnTypeInfo::ForType(*sem_ir_, inst.type_id);
  1103. if (!return_info.is_valid()) {
  1104. out_ << "(<invalid return info>)";
  1105. return;
  1106. }
  1107. bool has_return_slot = return_info.has_return_slot();
  1108. InstId return_slot_arg_id = InstId::None;
  1109. if (has_return_slot) {
  1110. return_slot_arg_id = args.consume_back();
  1111. }
  1112. llvm::ListSeparator sep;
  1113. out_ << '(';
  1114. for (auto inst_id : args) {
  1115. out_ << sep;
  1116. FormatArg(inst_id);
  1117. }
  1118. out_ << ')';
  1119. if (has_return_slot) {
  1120. FormatReturnSlotArg(return_slot_arg_id);
  1121. }
  1122. }
  1123. auto Formatter::FormatImportCppDeclRhs() -> void {
  1124. out_ << " ";
  1125. OpenBrace();
  1126. for (const Parse::Tree::PackagingNames& import :
  1127. sem_ir_->parse_tree().imports()) {
  1128. if (import.package_id != PackageNameId::Cpp) {
  1129. continue;
  1130. }
  1131. Indent();
  1132. out_ << "import Cpp";
  1133. if (import.library_id.has_value()) {
  1134. out_ << " \""
  1135. << FormatEscaped(
  1136. sem_ir_->string_literal_values().Get(import.library_id))
  1137. << "\"";
  1138. } else if (import.inline_body_id.has_value()) {
  1139. out_ << " inline";
  1140. }
  1141. out_ << "\n";
  1142. }
  1143. CloseBrace();
  1144. }
  1145. auto Formatter::FormatImportRefRhs(AnyImportRef inst) -> void {
  1146. out_ << " ";
  1147. auto import_ir_inst = sem_ir_->import_ir_insts().Get(inst.import_ir_inst_id);
  1148. FormatArg(import_ir_inst.ir_id());
  1149. out_ << ", ";
  1150. if (inst.entity_name_id.has_value()) {
  1151. // Prefer to show the entity name when possible.
  1152. FormatArg(inst.entity_name_id);
  1153. } else {
  1154. // Show a name based on the location when possible, or the numeric
  1155. // instruction as a last resort.
  1156. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  1157. auto loc_id =
  1158. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  1159. switch (loc_id.kind()) {
  1160. case LocId::Kind::None: {
  1161. out_ << import_ir_inst.inst_id() << " [no loc]";
  1162. break;
  1163. }
  1164. case LocId::Kind::ImportIRInstId: {
  1165. // TODO: Probably don't want to format each indirection, but maybe
  1166. // reuse GetCanonicalImportIRInst?
  1167. out_ << import_ir_inst.inst_id() << " [indirect]";
  1168. break;
  1169. }
  1170. case LocId::Kind::NodeId: {
  1171. // Formats a NodeId from the import.
  1172. const auto& tree = import_ir.sem_ir->parse_tree();
  1173. auto token = tree.node_token(loc_id.node_id());
  1174. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1175. << tree.tokens().GetColumnNumber(token);
  1176. break;
  1177. }
  1178. case LocId::Kind::InstId:
  1179. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1180. }
  1181. }
  1182. out_ << ", "
  1183. << (inst.kind == InstKind::ImportRefLoaded ? "loaded" : "unloaded");
  1184. }
  1185. auto Formatter::FormatRequireImpls(RequireImplsId id) -> void {
  1186. out_ << ' ';
  1187. const auto& require = sem_ir_->require_impls().Get(id);
  1188. OpenBrace();
  1189. Indent();
  1190. out_ << "require ";
  1191. FormatArg(require.self_id);
  1192. out_ << " impls ";
  1193. FormatArg(require.facet_type_inst_id);
  1194. out_ << "\n";
  1195. CloseBrace();
  1196. }
  1197. auto Formatter::FormatRequireImplsBlock(RequireImplsBlockId block_id) -> void {
  1198. IndentLabel();
  1199. out_ << "!requires:\n";
  1200. if (!block_id.has_value()) {
  1201. return;
  1202. }
  1203. for (auto require_impls_id : sem_ir_->require_impls_blocks().Get(block_id)) {
  1204. Indent();
  1205. FormatArg(require_impls_id);
  1206. FormatRequireImpls(require_impls_id);
  1207. out_ << "\n";
  1208. }
  1209. }
  1210. auto Formatter::FormatArg(EntityNameId id) -> void {
  1211. if (!id.has_value()) {
  1212. out_ << "_";
  1213. return;
  1214. }
  1215. const auto& info = sem_ir_->entity_names().Get(id);
  1216. FormatName(info.name_id);
  1217. if (info.bind_index().has_value()) {
  1218. out_ << ", " << info.bind_index().index;
  1219. }
  1220. if (info.is_template) {
  1221. out_ << ", template";
  1222. }
  1223. }
  1224. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1225. const auto& info = sem_ir_->facet_types().Get(id);
  1226. // Nothing output to indicate that this is a facet type since this is only
  1227. // used as the argument to a `facet_type` instruction.
  1228. out_ << "<";
  1229. llvm::ListSeparator sep(" & ");
  1230. if (info.extend_constraints.empty() &&
  1231. info.extend_named_constraints.empty()) {
  1232. out_ << "type";
  1233. } else {
  1234. for (auto extend : info.extend_constraints) {
  1235. out_ << sep;
  1236. FormatName(extend.interface_id);
  1237. if (extend.specific_id.has_value()) {
  1238. out_ << ", ";
  1239. FormatName(extend.specific_id);
  1240. }
  1241. }
  1242. for (auto extend : info.extend_named_constraints) {
  1243. out_ << sep;
  1244. FormatName(extend.named_constraint_id);
  1245. if (extend.specific_id.has_value()) {
  1246. out_ << ", ";
  1247. FormatName(extend.specific_id);
  1248. }
  1249. }
  1250. }
  1251. if (info.other_requirements || !info.builtin_constraint_mask.empty() ||
  1252. !info.self_impls_constraints.empty() ||
  1253. !info.rewrite_constraints.empty()) {
  1254. out_ << " where ";
  1255. llvm::ListSeparator and_sep(" and ");
  1256. if (!info.self_impls_constraints.empty() ||
  1257. !info.self_impls_named_constraints.empty()) {
  1258. out_ << and_sep << ".Self impls ";
  1259. llvm::ListSeparator amp_sep(" & ");
  1260. for (auto self_impls : info.self_impls_constraints) {
  1261. out_ << amp_sep;
  1262. FormatName(self_impls.interface_id);
  1263. if (self_impls.specific_id.has_value()) {
  1264. out_ << ", ";
  1265. FormatName(self_impls.specific_id);
  1266. }
  1267. }
  1268. for (auto self_impls : info.self_impls_named_constraints) {
  1269. out_ << amp_sep;
  1270. FormatName(self_impls.named_constraint_id);
  1271. if (self_impls.specific_id.has_value()) {
  1272. out_ << ", ";
  1273. FormatName(self_impls.specific_id);
  1274. }
  1275. }
  1276. }
  1277. for (auto rewrite : info.rewrite_constraints) {
  1278. out_ << and_sep;
  1279. FormatArg(rewrite.lhs_id);
  1280. out_ << " = ";
  1281. FormatArg(rewrite.rhs_id);
  1282. }
  1283. if (info.builtin_constraint_mask.HasAnyOf(
  1284. BuiltinConstraintMask::TypeCanDestroy)) {
  1285. out_ << and_sep << ".Self impls <CanDestroy>";
  1286. }
  1287. if (info.other_requirements) {
  1288. out_ << and_sep << "TODO";
  1289. }
  1290. }
  1291. out_ << ">";
  1292. }
  1293. auto Formatter::FormatArg(ImportIRId id) -> void {
  1294. if (id.has_value()) {
  1295. out_ << GetImportIRLabel(id);
  1296. } else {
  1297. out_ << id;
  1298. }
  1299. }
  1300. auto Formatter::FormatArg(IntId id) -> void {
  1301. // We don't know the signedness to use here. Default to unsigned.
  1302. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  1303. }
  1304. auto Formatter::FormatArg(NameScopeId id) -> void {
  1305. OpenBrace();
  1306. FormatNameScope(id);
  1307. CloseBrace();
  1308. }
  1309. auto Formatter::FormatArg(InstBlockId id) -> void {
  1310. if (!id.has_value()) {
  1311. out_ << "invalid";
  1312. return;
  1313. }
  1314. out_ << '(';
  1315. llvm::ListSeparator sep;
  1316. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1317. out_ << sep;
  1318. FormatArg(inst_id);
  1319. }
  1320. out_ << ')';
  1321. }
  1322. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1323. FormatArg(static_cast<InstBlockId>(id));
  1324. }
  1325. auto Formatter::FormatArg(RealId id) -> void {
  1326. // TODO: Format with a `.` when the exponent is near zero.
  1327. const auto& real = sem_ir_->reals().Get(id);
  1328. real.mantissa.print(out_, /*isSigned=*/false);
  1329. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1330. }
  1331. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1332. out_ << '"'
  1333. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1334. /*use_hex_escapes=*/true)
  1335. << '"';
  1336. }
  1337. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1338. out_ << " to ";
  1339. FormatArg(dest_id);
  1340. }
  1341. auto Formatter::FormatName(NameId id) -> void {
  1342. out_ << sem_ir_->names().GetFormatted(id);
  1343. }
  1344. auto Formatter::FormatName(InstId id) -> void {
  1345. if (id.has_value()) {
  1346. IncludeChunkInOutput(tentative_inst_chunks_.Get(id));
  1347. }
  1348. out_ << inst_namer_.GetNameFor(scope_, id);
  1349. }
  1350. auto Formatter::FormatName(SpecificId id) -> void {
  1351. const auto& specific = sem_ir_->specifics().Get(id);
  1352. FormatName(specific.generic_id);
  1353. FormatArg(specific.args_id);
  1354. }
  1355. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1356. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1357. FormatName(interface.interface_id);
  1358. if (interface.specific_id.has_value()) {
  1359. out_ << ", ";
  1360. FormatArg(interface.specific_id);
  1361. }
  1362. }
  1363. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1364. out_ << inst_namer_.GetLabelFor(scope_, id);
  1365. }
  1366. auto Formatter::FormatConstant(ConstantId id) -> void {
  1367. if (!id.has_value()) {
  1368. out_ << "<not constant>";
  1369. return;
  1370. }
  1371. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1372. FormatName(inst_id);
  1373. // For an attached constant, also list the unattached constant.
  1374. if (id.is_symbolic() && sem_ir_->constant_values()
  1375. .GetSymbolicConstant(id)
  1376. .generic_id.has_value()) {
  1377. // TODO: Skip printing this if it's the same as `inst_id`.
  1378. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1379. out_ << " (";
  1380. FormatName(unattached_inst_id);
  1381. out_ << ")";
  1382. }
  1383. }
  1384. auto Formatter::FormatInstAsType(InstId id) -> void {
  1385. if (!id.has_value()) {
  1386. out_ << "invalid";
  1387. return;
  1388. }
  1389. // Types are formatted in the `constants` scope because they typically refer
  1390. // to constants.
  1391. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1392. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1393. const_id.has_value()) {
  1394. FormatConstant(const_id);
  1395. } else {
  1396. // Type instruction didn't have a constant value. Fall back to printing
  1397. // the instruction name.
  1398. FormatArg(id);
  1399. }
  1400. }
  1401. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1402. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1403. if (!type_id.has_value()) {
  1404. out_ << "invalid";
  1405. return;
  1406. }
  1407. // Types are formatted in the `constants` scope because they typically refer
  1408. // to constants.
  1409. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1410. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1411. }
  1412. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1413. CARBON_CHECK(id.has_value(),
  1414. "Callers are responsible for checking `id.has_value`");
  1415. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1416. CARBON_CHECK(import_ir.library_id().has_value());
  1417. auto package_id = import_ir.package_id();
  1418. llvm::StringRef package_name =
  1419. package_id.AsIdentifierId().has_value()
  1420. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1421. : package_id.AsSpecialName();
  1422. llvm::StringRef library_name =
  1423. (import_ir.library_id() != LibraryNameId::Default)
  1424. ? import_ir.string_literal_values().Get(
  1425. import_ir.library_id().AsStringLiteralValueId())
  1426. : "default";
  1427. return llvm::formatv("{0}//{1}", package_name, library_name);
  1428. }
  1429. } // namespace Carbon::SemIR
  1430. // NOLINTEND(misc-no-recursion)