formatter.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/sem_ir/formatter.h"
  5. #include "common/ostream.h"
  6. #include "llvm/ADT/Sequence.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "llvm/ADT/StringMap.h"
  9. #include "llvm/Support/SaveAndRestore.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/base/value_store.h"
  12. #include "toolchain/lex/tokenized_buffer.h"
  13. #include "toolchain/parse/tree.h"
  14. #include "toolchain/sem_ir/builtin_function_kind.h"
  15. #include "toolchain/sem_ir/function.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::SemIR {
  19. namespace {
  20. // Assigns names to instructions, blocks, and scopes in the Semantics IR.
  21. //
  22. // TODOs / future work ideas:
  23. // - Add a documentation file for the textual format and link to the
  24. // naming section here.
  25. // - Consider representing literals as just `literal` in the IR and using the
  26. // type to distinguish.
  27. class InstNamer {
  28. public:
  29. // int32_t matches the input value size.
  30. // NOLINTNEXTLINE(performance-enum-size)
  31. enum class ScopeId : int32_t {
  32. None = -1,
  33. File = 0,
  34. ImportRef = 1,
  35. Constants = 2,
  36. FirstFunction = 3,
  37. };
  38. static_assert(sizeof(ScopeId) == sizeof(FunctionId));
  39. struct NumberOfScopesTag {};
  40. InstNamer(const Lex::TokenizedBuffer& tokenized_buffer,
  41. const Parse::Tree& parse_tree, const File& sem_ir)
  42. : tokenized_buffer_(tokenized_buffer),
  43. parse_tree_(parse_tree),
  44. sem_ir_(sem_ir) {
  45. insts.resize(sem_ir.insts().size());
  46. labels.resize(sem_ir.inst_blocks().size());
  47. scopes.resize(static_cast<size_t>(GetScopeFor(NumberOfScopesTag())));
  48. // Build the constants scope.
  49. GetScopeInfo(ScopeId::Constants).name =
  50. globals.AddNameUnchecked("constants");
  51. CollectNamesInBlock(ScopeId::Constants, sem_ir.constants().GetAsVector());
  52. // Build the file scope.
  53. GetScopeInfo(ScopeId::File).name = globals.AddNameUnchecked("file");
  54. CollectNamesInBlock(ScopeId::File, sem_ir.top_inst_block_id());
  55. // Build the imports scope, used only by import-related instructions without
  56. // a block.
  57. // TODO: Consider other approaches for ImportRef constant formatting, as the
  58. // actual source of these remains unclear even though they're referenced in
  59. // constants.
  60. GetScopeInfo(ScopeId::ImportRef).name = globals.AddNameUnchecked("imports");
  61. // Build each function scope.
  62. for (auto [i, fn] : llvm::enumerate(sem_ir.functions().array_ref())) {
  63. auto fn_id = FunctionId(i);
  64. auto fn_scope = GetScopeFor(fn_id);
  65. // TODO: Provide a location for the function for use as a
  66. // disambiguator.
  67. auto fn_loc = Parse::NodeId::Invalid;
  68. GetScopeInfo(fn_scope).name = globals.AllocateName(
  69. *this, fn_loc, sem_ir.names().GetIRBaseName(fn.name_id).str());
  70. CollectNamesInBlock(fn_scope, fn.implicit_param_refs_id);
  71. CollectNamesInBlock(fn_scope, fn.param_refs_id);
  72. if (fn.return_slot_id.is_valid()) {
  73. insts[fn.return_slot_id.index] = {
  74. fn_scope,
  75. GetScopeInfo(fn_scope).insts.AllocateName(
  76. *this, sem_ir.insts().GetNodeId(fn.return_slot_id), "return")};
  77. }
  78. if (!fn.body_block_ids.empty()) {
  79. AddBlockLabel(fn_scope, fn.body_block_ids.front(), "entry", fn_loc);
  80. }
  81. for (auto block_id : fn.body_block_ids) {
  82. CollectNamesInBlock(fn_scope, block_id);
  83. }
  84. for (auto block_id : fn.body_block_ids) {
  85. AddBlockLabel(fn_scope, block_id);
  86. }
  87. }
  88. // Build each class scope.
  89. for (auto [i, class_info] : llvm::enumerate(sem_ir.classes().array_ref())) {
  90. auto class_id = ClassId(i);
  91. auto class_scope = GetScopeFor(class_id);
  92. // TODO: Provide a location for the class for use as a disambiguator.
  93. auto class_loc = Parse::NodeId::Invalid;
  94. GetScopeInfo(class_scope).name = globals.AllocateName(
  95. *this, class_loc,
  96. sem_ir.names().GetIRBaseName(class_info.name_id).str());
  97. AddBlockLabel(class_scope, class_info.body_block_id, "class", class_loc);
  98. CollectNamesInBlock(class_scope, class_info.body_block_id);
  99. }
  100. // Build each interface scope.
  101. for (auto [i, interface_info] :
  102. llvm::enumerate(sem_ir.interfaces().array_ref())) {
  103. auto interface_id = InterfaceId(i);
  104. auto interface_scope = GetScopeFor(interface_id);
  105. // TODO: Provide a location for the interface for use as a disambiguator.
  106. auto interface_loc = Parse::NodeId::Invalid;
  107. GetScopeInfo(interface_scope).name = globals.AllocateName(
  108. *this, interface_loc,
  109. sem_ir.names().GetIRBaseName(interface_info.name_id).str());
  110. AddBlockLabel(interface_scope, interface_info.body_block_id, "interface",
  111. interface_loc);
  112. CollectNamesInBlock(interface_scope, interface_info.body_block_id);
  113. }
  114. // Build each impl scope.
  115. for (auto [i, impl_info] : llvm::enumerate(sem_ir.impls().array_ref())) {
  116. auto impl_id = ImplId(i);
  117. auto impl_scope = GetScopeFor(impl_id);
  118. // TODO: Provide a location for the impl for use as a disambiguator.
  119. auto impl_loc = Parse::NodeId::Invalid;
  120. // TODO: Invent a name based on the self and constraint types.
  121. GetScopeInfo(impl_scope).name =
  122. globals.AllocateName(*this, impl_loc, "impl");
  123. AddBlockLabel(impl_scope, impl_info.body_block_id, "impl", impl_loc);
  124. CollectNamesInBlock(impl_scope, impl_info.body_block_id);
  125. }
  126. }
  127. // Returns the scope ID corresponding to an ID of a function, class, or
  128. // interface.
  129. template <typename IdT>
  130. auto GetScopeFor(IdT id) -> ScopeId {
  131. auto index = static_cast<int32_t>(ScopeId::FirstFunction);
  132. if constexpr (!std::same_as<FunctionId, IdT>) {
  133. index += sem_ir_.functions().size();
  134. if constexpr (!std::same_as<ClassId, IdT>) {
  135. index += sem_ir_.classes().size();
  136. if constexpr (!std::same_as<InterfaceId, IdT>) {
  137. index += sem_ir_.interfaces().size();
  138. if constexpr (!std::same_as<ImplId, IdT>) {
  139. index += sem_ir_.impls().size();
  140. static_assert(std::same_as<NumberOfScopesTag, IdT>,
  141. "Unknown ID kind for scope");
  142. }
  143. }
  144. }
  145. }
  146. if constexpr (!std::same_as<NumberOfScopesTag, IdT>) {
  147. index += id.index;
  148. }
  149. return static_cast<ScopeId>(index);
  150. }
  151. // Returns the IR name to use for a function, class, or interface.
  152. template <typename IdT>
  153. auto GetNameFor(IdT id) -> llvm::StringRef {
  154. if (!id.is_valid()) {
  155. return "invalid";
  156. }
  157. return GetScopeInfo(GetScopeFor(id)).name.str();
  158. }
  159. // Returns the IR name to use for an instruction, when referenced from a given
  160. // scope.
  161. auto GetNameFor(ScopeId scope_id, InstId inst_id) -> std::string {
  162. if (!inst_id.is_valid()) {
  163. return "invalid";
  164. }
  165. // Check for a builtin.
  166. if (inst_id.is_builtin()) {
  167. return inst_id.builtin_kind().label().str();
  168. }
  169. if (inst_id == InstId::PackageNamespace) {
  170. return "package";
  171. }
  172. auto& [inst_scope, inst_name] = insts[inst_id.index];
  173. if (!inst_name) {
  174. // This should not happen in valid IR.
  175. std::string str;
  176. llvm::raw_string_ostream(str) << "<unexpected instref " << inst_id << ">";
  177. return str;
  178. }
  179. if (inst_scope == scope_id) {
  180. return inst_name.str().str();
  181. }
  182. return (GetScopeInfo(inst_scope).name.str() + "." + inst_name.str()).str();
  183. }
  184. // Returns the IR name to use for a label, when referenced from a given scope.
  185. auto GetLabelFor(ScopeId scope_id, InstBlockId block_id) -> std::string {
  186. if (!block_id.is_valid()) {
  187. return "!invalid";
  188. }
  189. auto& [label_scope, label_name] = labels[block_id.index];
  190. if (!label_name) {
  191. // This should not happen in valid IR.
  192. std::string str;
  193. llvm::raw_string_ostream(str)
  194. << "<unexpected instblockref " << block_id << ">";
  195. return str;
  196. }
  197. if (label_scope == scope_id) {
  198. return label_name.str().str();
  199. }
  200. return (GetScopeInfo(label_scope).name.str() + "." + label_name.str())
  201. .str();
  202. }
  203. private:
  204. // A space in which unique names can be allocated.
  205. struct Namespace {
  206. // A result of a name lookup.
  207. struct NameResult;
  208. // A name in a namespace, which might be redirected to refer to another name
  209. // for disambiguation purposes.
  210. class Name {
  211. public:
  212. Name() : value_(nullptr) {}
  213. explicit Name(llvm::StringMapIterator<NameResult> it) : value_(&*it) {}
  214. explicit operator bool() const { return value_; }
  215. auto str() const -> llvm::StringRef {
  216. llvm::StringMapEntry<NameResult>* value = value_;
  217. CARBON_CHECK(value) << "cannot print a null name";
  218. while (value->second.ambiguous && value->second.fallback) {
  219. value = value->second.fallback.value_;
  220. }
  221. return value->first();
  222. }
  223. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  224. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  225. private:
  226. llvm::StringMapEntry<NameResult>* value_ = nullptr;
  227. };
  228. struct NameResult {
  229. bool ambiguous = false;
  230. Name fallback = Name();
  231. };
  232. llvm::StringRef prefix;
  233. llvm::StringMap<NameResult> allocated = {};
  234. int unnamed_count = 0;
  235. auto AddNameUnchecked(llvm::StringRef name) -> Name {
  236. return Name(allocated.insert({name, NameResult()}).first);
  237. }
  238. auto AllocateName(const InstNamer& namer, Parse::NodeId node,
  239. std::string name) -> Name {
  240. // The best (shortest) name for this instruction so far, and the current
  241. // name for it.
  242. Name best;
  243. Name current;
  244. // Add `name` as a name for this entity.
  245. auto add_name = [&](bool mark_ambiguous = true) {
  246. auto [it, added] = allocated.insert({name, NameResult()});
  247. Name new_name = Name(it);
  248. if (!added) {
  249. if (mark_ambiguous) {
  250. // This name was allocated for a different instruction. Mark it as
  251. // ambiguous and keep looking for a name for this instruction.
  252. new_name.SetAmbiguous();
  253. }
  254. } else {
  255. if (!best) {
  256. best = new_name;
  257. } else {
  258. CARBON_CHECK(current);
  259. current.SetFallback(new_name);
  260. }
  261. current = new_name;
  262. }
  263. return added;
  264. };
  265. // All names start with the prefix.
  266. name.insert(0, prefix);
  267. // Use the given name if it's available and not just the prefix.
  268. if (name.size() > prefix.size()) {
  269. add_name();
  270. }
  271. // Append location information to try to disambiguate.
  272. if (node.is_valid()) {
  273. auto token = namer.parse_tree_.node_token(node);
  274. llvm::raw_string_ostream(name)
  275. << ".loc" << namer.tokenized_buffer_.GetLineNumber(token);
  276. add_name();
  277. llvm::raw_string_ostream(name)
  278. << "_" << namer.tokenized_buffer_.GetColumnNumber(token);
  279. add_name();
  280. }
  281. // Append numbers until we find an available name.
  282. name += ".";
  283. auto name_size_without_counter = name.size();
  284. for (int counter = 1;; ++counter) {
  285. name.resize(name_size_without_counter);
  286. llvm::raw_string_ostream(name) << counter;
  287. if (add_name(/*mark_ambiguous=*/false)) {
  288. return best;
  289. }
  290. }
  291. }
  292. };
  293. // A named scope that contains named entities.
  294. struct Scope {
  295. Namespace::Name name;
  296. Namespace insts = {.prefix = "%"};
  297. Namespace labels = {.prefix = "!"};
  298. };
  299. auto GetScopeInfo(ScopeId scope_id) -> Scope& {
  300. return scopes[static_cast<int>(scope_id)];
  301. }
  302. auto AddBlockLabel(ScopeId scope_id, InstBlockId block_id,
  303. std::string name = "",
  304. Parse::NodeId node_id = Parse::NodeId::Invalid) -> void {
  305. if (!block_id.is_valid() || labels[block_id.index].second) {
  306. return;
  307. }
  308. if (!node_id.is_valid()) {
  309. if (const auto& block = sem_ir_.inst_blocks().Get(block_id);
  310. !block.empty()) {
  311. node_id = sem_ir_.insts().GetNodeId(block.front());
  312. }
  313. }
  314. labels[block_id.index] = {
  315. scope_id, GetScopeInfo(scope_id).labels.AllocateName(*this, node_id,
  316. std::move(name))};
  317. }
  318. // Finds and adds a suitable block label for the given SemIR instruction that
  319. // represents some kind of branch.
  320. auto AddBlockLabel(ScopeId scope_id, Parse::NodeId node_id, AnyBranch branch)
  321. -> void {
  322. llvm::StringRef name;
  323. switch (parse_tree_.node_kind(node_id)) {
  324. case Parse::NodeKind::IfExprIf:
  325. switch (branch.kind) {
  326. case BranchIf::Kind:
  327. name = "if.expr.then";
  328. break;
  329. case Branch::Kind:
  330. name = "if.expr.else";
  331. break;
  332. case BranchWithArg::Kind:
  333. name = "if.expr.result";
  334. break;
  335. default:
  336. break;
  337. }
  338. break;
  339. case Parse::NodeKind::IfCondition:
  340. switch (branch.kind) {
  341. case BranchIf::Kind:
  342. name = "if.then";
  343. break;
  344. case Branch::Kind:
  345. name = "if.else";
  346. break;
  347. default:
  348. break;
  349. }
  350. break;
  351. case Parse::NodeKind::IfStatement:
  352. name = "if.done";
  353. break;
  354. case Parse::NodeKind::ShortCircuitOperandAnd:
  355. name = branch.kind == BranchIf::Kind ? "and.rhs" : "and.result";
  356. break;
  357. case Parse::NodeKind::ShortCircuitOperandOr:
  358. name = branch.kind == BranchIf::Kind ? "or.rhs" : "or.result";
  359. break;
  360. case Parse::NodeKind::WhileConditionStart:
  361. name = "while.cond";
  362. break;
  363. case Parse::NodeKind::WhileCondition:
  364. switch (branch.kind) {
  365. case InstKind::BranchIf:
  366. name = "while.body";
  367. break;
  368. case InstKind::Branch:
  369. name = "while.done";
  370. break;
  371. default:
  372. break;
  373. }
  374. break;
  375. default:
  376. break;
  377. }
  378. AddBlockLabel(scope_id, branch.target_id, name.str(), node_id);
  379. }
  380. auto CollectNamesInBlock(ScopeId scope_id, InstBlockId block_id) -> void {
  381. if (block_id.is_valid()) {
  382. CollectNamesInBlock(scope_id, sem_ir_.inst_blocks().Get(block_id));
  383. }
  384. }
  385. auto CollectNamesInBlock(ScopeId scope_id, llvm::ArrayRef<InstId> block)
  386. -> void {
  387. Scope& scope = GetScopeInfo(scope_id);
  388. // Use bound names where available. Otherwise, assign a backup name.
  389. for (auto inst_id : block) {
  390. if (!inst_id.is_valid()) {
  391. continue;
  392. }
  393. auto untyped_inst = sem_ir_.insts().Get(inst_id);
  394. auto add_inst_name = [&](std::string name) {
  395. insts[inst_id.index] = {
  396. scope_id, scope.insts.AllocateName(
  397. *this, sem_ir_.insts().GetNodeId(inst_id), name)};
  398. };
  399. auto add_inst_name_id = [&](NameId name_id, llvm::StringRef suffix = "") {
  400. add_inst_name(
  401. (sem_ir_.names().GetIRBaseName(name_id).str() + suffix).str());
  402. };
  403. if (auto branch = untyped_inst.TryAs<AnyBranch>()) {
  404. AddBlockLabel(scope_id, sem_ir_.insts().GetNodeId(inst_id), *branch);
  405. }
  406. CARBON_KIND_SWITCH(untyped_inst) {
  407. case CARBON_KIND(AddrPattern inst): {
  408. // TODO: We need to assign names to parameters that appear in
  409. // function declarations, which may be nested within a pattern. For
  410. // now, just look through `addr`, but we should find a better way to
  411. // visit parameters.
  412. CollectNamesInBlock(scope_id, inst.inner_id);
  413. break;
  414. }
  415. case CARBON_KIND(AssociatedConstantDecl inst): {
  416. add_inst_name_id(inst.name_id);
  417. continue;
  418. }
  419. case BindAlias::Kind:
  420. case BindName::Kind:
  421. case BindSymbolicName::Kind: {
  422. auto inst = untyped_inst.As<AnyBindName>();
  423. add_inst_name_id(sem_ir_.bind_names().Get(inst.bind_name_id).name_id);
  424. continue;
  425. }
  426. case CARBON_KIND(ClassDecl inst): {
  427. add_inst_name_id(sem_ir_.classes().Get(inst.class_id).name_id,
  428. ".decl");
  429. CollectNamesInBlock(scope_id, inst.decl_block_id);
  430. continue;
  431. }
  432. case CARBON_KIND(ClassType inst): {
  433. add_inst_name_id(sem_ir_.classes().Get(inst.class_id).name_id);
  434. continue;
  435. }
  436. case CARBON_KIND(FunctionDecl inst): {
  437. add_inst_name_id(sem_ir_.functions().Get(inst.function_id).name_id);
  438. CollectNamesInBlock(scope_id, inst.decl_block_id);
  439. continue;
  440. }
  441. case CARBON_KIND(ImplDecl inst): {
  442. CollectNamesInBlock(scope_id, inst.decl_block_id);
  443. break;
  444. }
  445. case ImportRefUnused::Kind:
  446. case ImportRefUsed::Kind: {
  447. add_inst_name("import_ref");
  448. // When building import refs, we frequently add instructions without
  449. // a block. Constants that refer to them need to be separately
  450. // named.
  451. auto const_id = sem_ir_.constant_values().Get(inst_id);
  452. if (const_id.is_valid() && const_id.is_template() &&
  453. !insts[const_id.inst_id().index].second) {
  454. CollectNamesInBlock(ScopeId::ImportRef, const_id.inst_id());
  455. }
  456. continue;
  457. }
  458. case CARBON_KIND(InterfaceDecl inst): {
  459. add_inst_name_id(sem_ir_.interfaces().Get(inst.interface_id).name_id,
  460. ".decl");
  461. CollectNamesInBlock(scope_id, inst.decl_block_id);
  462. continue;
  463. }
  464. case CARBON_KIND(NameRef inst): {
  465. add_inst_name_id(inst.name_id, ".ref");
  466. continue;
  467. }
  468. // The namespace is specified here due to the name conflict.
  469. case CARBON_KIND(SemIR::Namespace inst): {
  470. add_inst_name_id(
  471. sem_ir_.name_scopes().Get(inst.name_scope_id).name_id);
  472. continue;
  473. }
  474. case CARBON_KIND(Param inst): {
  475. add_inst_name_id(inst.name_id);
  476. continue;
  477. }
  478. case CARBON_KIND(SpliceBlock inst): {
  479. CollectNamesInBlock(scope_id, inst.block_id);
  480. break;
  481. }
  482. case CARBON_KIND(VarStorage inst): {
  483. add_inst_name_id(inst.name_id, ".var");
  484. continue;
  485. }
  486. default: {
  487. break;
  488. }
  489. }
  490. // Sequentially number all remaining values.
  491. if (untyped_inst.kind().value_kind() != InstValueKind::None) {
  492. add_inst_name("");
  493. }
  494. }
  495. }
  496. const Lex::TokenizedBuffer& tokenized_buffer_;
  497. const Parse::Tree& parse_tree_;
  498. const File& sem_ir_;
  499. Namespace globals = {.prefix = "@"};
  500. std::vector<std::pair<ScopeId, Namespace::Name>> insts;
  501. std::vector<std::pair<ScopeId, Namespace::Name>> labels;
  502. std::vector<Scope> scopes;
  503. };
  504. } // namespace
  505. // Formatter for printing textual Semantics IR.
  506. class Formatter {
  507. public:
  508. enum class AddSpace : bool { Before, After };
  509. explicit Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  510. const Parse::Tree& parse_tree, const File& sem_ir,
  511. llvm::raw_ostream& out)
  512. : sem_ir_(sem_ir),
  513. out_(out),
  514. inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  515. // Prints the SemIR.
  516. //
  517. // Constants are printed first and may be referenced by later sections,
  518. // including file-scoped instructions. The file scope may contain entity
  519. // declarations which are defined later, such as classes.
  520. auto Format() -> void {
  521. out_ << "--- " << sem_ir_.filename() << "\n\n";
  522. FormatConstants();
  523. out_ << "file ";
  524. OpenBrace();
  525. // TODO: Handle the case where there are multiple top-level instruction
  526. // blocks. For example, there may be branching in the initializer of a
  527. // global or a type expression.
  528. if (auto block_id = sem_ir_.top_inst_block_id(); block_id.is_valid()) {
  529. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::File);
  530. FormatCodeBlock(block_id);
  531. }
  532. CloseBrace();
  533. out_ << '\n';
  534. for (int i : llvm::seq(sem_ir_.interfaces().size())) {
  535. FormatInterface(InterfaceId(i));
  536. }
  537. for (int i : llvm::seq(sem_ir_.impls().size())) {
  538. FormatImpl(ImplId(i));
  539. }
  540. for (int i : llvm::seq(sem_ir_.classes().size())) {
  541. FormatClass(ClassId(i));
  542. }
  543. for (int i : llvm::seq(sem_ir_.functions().size())) {
  544. FormatFunction(FunctionId(i));
  545. }
  546. // End-of-file newline.
  547. out_ << "\n";
  548. }
  549. // Begins a braced block. Writes an open brace, and prepares to insert a
  550. // newline after it if the braced block is non-empty.
  551. auto OpenBrace() -> void {
  552. // Put the constant value of an instruction before any braced block, rather
  553. // than at the end.
  554. FormatPendingConstantValue(AddSpace::After);
  555. out_ << '{';
  556. indent_ += 2;
  557. after_open_brace_ = true;
  558. }
  559. // Ends a braced block by writing a close brace.
  560. auto CloseBrace() -> void {
  561. indent_ -= 2;
  562. if (!after_open_brace_) {
  563. Indent();
  564. }
  565. out_ << '}';
  566. after_open_brace_ = false;
  567. }
  568. // Adds beginning-of-line indentation. If we're at the start of a braced
  569. // block, first starts a new line.
  570. auto Indent(int offset = 0) -> void {
  571. if (after_open_brace_) {
  572. out_ << '\n';
  573. after_open_brace_ = false;
  574. }
  575. out_.indent(indent_ + offset);
  576. }
  577. // Adds beginning-of-label indentation. This is one level less than normal
  578. // indentation. Labels also get a preceding blank line unless they're at the
  579. // start of a block.
  580. auto IndentLabel() -> void {
  581. CARBON_CHECK(indent_ >= 2);
  582. if (!after_open_brace_) {
  583. out_ << '\n';
  584. }
  585. Indent(-2);
  586. }
  587. auto FormatConstants() -> void {
  588. if (!sem_ir_.constants().size()) {
  589. return;
  590. }
  591. llvm::SaveAndRestore constants_scope(scope_, InstNamer::ScopeId::Constants);
  592. out_ << "constants ";
  593. OpenBrace();
  594. FormatCodeBlock(sem_ir_.constants().GetAsVector());
  595. CloseBrace();
  596. out_ << "\n\n";
  597. }
  598. auto FormatClass(ClassId id) -> void {
  599. const Class& class_info = sem_ir_.classes().Get(id);
  600. out_ << "\nclass ";
  601. FormatClassName(id);
  602. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  603. if (class_info.scope_id.is_valid()) {
  604. out_ << ' ';
  605. OpenBrace();
  606. FormatCodeBlock(class_info.body_block_id);
  607. FormatNameScope(class_info.scope_id, "!members:\n");
  608. CloseBrace();
  609. out_ << '\n';
  610. } else {
  611. out_ << ";\n";
  612. }
  613. }
  614. auto FormatInterface(InterfaceId id) -> void {
  615. const Interface& interface_info = sem_ir_.interfaces().Get(id);
  616. out_ << "\ninterface ";
  617. FormatInterfaceName(id);
  618. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  619. if (interface_info.scope_id.is_valid()) {
  620. out_ << ' ';
  621. OpenBrace();
  622. FormatCodeBlock(interface_info.body_block_id);
  623. // Always include the !members label because we always list the witness in
  624. // this section.
  625. IndentLabel();
  626. out_ << "!members:\n";
  627. FormatNameScope(interface_info.scope_id);
  628. Indent();
  629. out_ << "witness = ";
  630. FormatArg(interface_info.associated_entities_id);
  631. out_ << "\n";
  632. CloseBrace();
  633. out_ << '\n';
  634. } else {
  635. out_ << ";\n";
  636. }
  637. }
  638. auto FormatImpl(ImplId id) -> void {
  639. const Impl& impl_info = sem_ir_.impls().Get(id);
  640. out_ << "\nimpl ";
  641. FormatImplName(id);
  642. out_ << ": ";
  643. // TODO: Include the deduced parameter list if present.
  644. FormatType(impl_info.self_id);
  645. out_ << " as ";
  646. FormatType(impl_info.constraint_id);
  647. llvm::SaveAndRestore impl_scope(scope_, inst_namer_.GetScopeFor(id));
  648. if (impl_info.scope_id.is_valid()) {
  649. out_ << ' ';
  650. OpenBrace();
  651. FormatCodeBlock(impl_info.body_block_id);
  652. // Print the !members label even if the name scope is empty because we
  653. // always list the witness in this section.
  654. IndentLabel();
  655. out_ << "!members:\n";
  656. FormatNameScope(impl_info.scope_id);
  657. Indent();
  658. out_ << "witness = ";
  659. FormatArg(impl_info.witness_id);
  660. out_ << "\n";
  661. CloseBrace();
  662. out_ << '\n';
  663. } else {
  664. out_ << ";\n";
  665. }
  666. }
  667. auto FormatFunction(FunctionId id) -> void {
  668. const Function& fn = sem_ir_.functions().Get(id);
  669. out_ << "\nfn ";
  670. FormatFunctionName(id);
  671. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  672. if (fn.implicit_param_refs_id != InstBlockId::Empty) {
  673. out_ << "[";
  674. FormatParamList(fn.implicit_param_refs_id);
  675. out_ << "]";
  676. }
  677. out_ << "(";
  678. FormatParamList(fn.param_refs_id);
  679. out_ << ")";
  680. if (fn.return_type_id.is_valid()) {
  681. out_ << " -> ";
  682. if (fn.return_slot_id.is_valid()) {
  683. FormatInstName(fn.return_slot_id);
  684. out_ << ": ";
  685. }
  686. FormatType(fn.return_type_id);
  687. }
  688. if (fn.builtin_kind != BuiltinFunctionKind::None) {
  689. out_ << " = \"";
  690. out_.write_escaped(fn.builtin_kind.name(),
  691. /*UseHexEscapes=*/true);
  692. out_ << "\"";
  693. }
  694. if (!fn.body_block_ids.empty()) {
  695. out_ << ' ';
  696. OpenBrace();
  697. for (auto block_id : fn.body_block_ids) {
  698. IndentLabel();
  699. FormatLabel(block_id);
  700. out_ << ":\n";
  701. FormatCodeBlock(block_id);
  702. }
  703. CloseBrace();
  704. out_ << '\n';
  705. } else {
  706. out_ << ";\n";
  707. }
  708. }
  709. auto FormatParamList(InstBlockId param_refs_id) -> void {
  710. llvm::ListSeparator sep;
  711. for (InstId param_id : sem_ir_.inst_blocks().Get(param_refs_id)) {
  712. out_ << sep;
  713. if (!param_id.is_valid()) {
  714. out_ << "invalid";
  715. continue;
  716. }
  717. if (auto addr = sem_ir_.insts().TryGetAs<SemIR::AddrPattern>(param_id)) {
  718. out_ << "addr ";
  719. param_id = addr->inner_id;
  720. }
  721. FormatInstName(param_id);
  722. out_ << ": ";
  723. FormatType(sem_ir_.insts().Get(param_id).type_id());
  724. }
  725. }
  726. auto FormatCodeBlock(InstBlockId block_id) -> void {
  727. if (block_id.is_valid()) {
  728. FormatCodeBlock(sem_ir_.inst_blocks().Get(block_id));
  729. }
  730. }
  731. auto FormatCodeBlock(llvm::ArrayRef<InstId> block) -> void {
  732. for (const InstId inst_id : block) {
  733. FormatInstruction(inst_id);
  734. }
  735. }
  736. auto FormatTrailingBlock(InstBlockId block_id) -> void {
  737. out_ << ' ';
  738. OpenBrace();
  739. FormatCodeBlock(block_id);
  740. CloseBrace();
  741. }
  742. auto FormatNameScope(NameScopeId id, llvm::StringRef label = "") -> void {
  743. const auto& scope = sem_ir_.name_scopes().Get(id);
  744. if (scope.names.empty() && scope.extended_scopes.empty() &&
  745. !scope.has_error) {
  746. // Name scope is empty.
  747. return;
  748. }
  749. if (!label.empty()) {
  750. IndentLabel();
  751. out_ << label;
  752. }
  753. // Name scopes aren't kept in any particular order. Sort the entries before
  754. // we print them for stability and consistency.
  755. llvm::SmallVector<std::pair<InstId, NameId>> entries;
  756. for (auto [name_id, inst_id] : scope.names) {
  757. entries.push_back({inst_id, name_id});
  758. }
  759. llvm::sort(entries,
  760. [](auto a, auto b) { return a.first.index < b.first.index; });
  761. for (auto [inst_id, name_id] : entries) {
  762. Indent();
  763. out_ << ".";
  764. FormatName(name_id);
  765. out_ << " = ";
  766. FormatInstName(inst_id);
  767. out_ << "\n";
  768. }
  769. for (auto extended_scope_id : scope.extended_scopes) {
  770. // TODO: Print this scope in a better way.
  771. Indent();
  772. out_ << "extend " << extended_scope_id << "\n";
  773. }
  774. if (scope.has_error) {
  775. Indent();
  776. out_ << "has_error\n";
  777. }
  778. }
  779. auto FormatInstruction(InstId inst_id) -> void {
  780. if (!inst_id.is_valid()) {
  781. Indent();
  782. out_ << "invalid\n";
  783. return;
  784. }
  785. FormatInstruction(inst_id, sem_ir_.insts().Get(inst_id));
  786. }
  787. auto FormatInstruction(InstId inst_id, Inst inst) -> void {
  788. switch (inst.kind()) {
  789. #define CARBON_SEM_IR_INST_KIND(InstT) \
  790. case InstT::Kind: \
  791. FormatInstruction(inst_id, inst.As<InstT>()); \
  792. break;
  793. #include "toolchain/sem_ir/inst_kind.def"
  794. }
  795. }
  796. template <typename InstT>
  797. auto FormatInstruction(InstId inst_id, InstT inst) -> void {
  798. Indent();
  799. FormatInstructionLHS(inst_id, inst);
  800. out_ << InstT::Kind.ir_name();
  801. pending_constant_value_ = sem_ir_.constant_values().Get(inst_id);
  802. pending_constant_value_is_self_ =
  803. pending_constant_value_.inst_id() == inst_id;
  804. FormatInstructionRHS(inst);
  805. FormatPendingConstantValue(AddSpace::Before);
  806. out_ << "\n";
  807. }
  808. // Don't print a constant for ImportRefUnused.
  809. auto FormatInstruction(InstId inst_id, ImportRefUnused inst) -> void {
  810. Indent();
  811. FormatInstructionLHS(inst_id, inst);
  812. out_ << ImportRefUnused::Kind.ir_name();
  813. FormatInstructionRHS(inst);
  814. out_ << "\n";
  815. }
  816. // If there is a pending constant value attached to the current instruction,
  817. // print it now and clear it out. The constant value gets printed before the
  818. // first braced block argument, or at the end of the instruction if there are
  819. // no such arguments.
  820. auto FormatPendingConstantValue(AddSpace space_where) -> void {
  821. if (pending_constant_value_ == ConstantId::NotConstant) {
  822. return;
  823. }
  824. if (space_where == AddSpace::Before) {
  825. out_ << ' ';
  826. }
  827. out_ << '[';
  828. if (pending_constant_value_.is_valid()) {
  829. out_ << (pending_constant_value_.is_symbolic() ? "symbolic" : "template");
  830. if (!pending_constant_value_is_self_) {
  831. out_ << " = ";
  832. FormatInstName(pending_constant_value_.inst_id());
  833. }
  834. } else {
  835. out_ << pending_constant_value_;
  836. }
  837. out_ << ']';
  838. if (space_where == AddSpace::After) {
  839. out_ << ' ';
  840. }
  841. pending_constant_value_ = ConstantId::NotConstant;
  842. }
  843. auto FormatInstructionLHS(InstId inst_id, Inst inst) -> void {
  844. switch (inst.kind().value_kind()) {
  845. case InstValueKind::Typed:
  846. FormatInstName(inst_id);
  847. out_ << ": ";
  848. switch (GetExprCategory(sem_ir_, inst_id)) {
  849. case ExprCategory::NotExpr:
  850. case ExprCategory::Error:
  851. case ExprCategory::Value:
  852. case ExprCategory::Mixed:
  853. break;
  854. case ExprCategory::DurableRef:
  855. case ExprCategory::EphemeralRef:
  856. out_ << "ref ";
  857. break;
  858. case ExprCategory::Initializing:
  859. out_ << "init ";
  860. break;
  861. }
  862. FormatType(inst.type_id());
  863. out_ << " = ";
  864. break;
  865. case InstValueKind::None:
  866. break;
  867. }
  868. }
  869. // Print ImportRefUnused with type-like semantics even though it lacks a
  870. // type_id.
  871. auto FormatInstructionLHS(InstId inst_id, ImportRefUnused /*inst*/) -> void {
  872. FormatInstName(inst_id);
  873. out_ << " = ";
  874. }
  875. template <typename InstT>
  876. auto FormatInstructionRHS(InstT inst) -> void {
  877. // By default, an instruction has a comma-separated argument list.
  878. using Info = Internal::InstLikeTypeInfo<InstT>;
  879. if constexpr (Info::NumArgs == 2) {
  880. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  881. } else if constexpr (Info::NumArgs == 1) {
  882. FormatArgs(Info::template Get<0>(inst));
  883. } else {
  884. FormatArgs();
  885. }
  886. }
  887. auto FormatInstructionRHS(BindSymbolicName inst) -> void {
  888. // A BindSymbolicName with no value is a purely symbolic binding, such as
  889. // the `Self` in an interface. Don't print out `invalid` for the value.
  890. if (inst.value_id.is_valid()) {
  891. FormatArgs(inst.bind_name_id, inst.value_id);
  892. } else {
  893. FormatArgs(inst.bind_name_id);
  894. }
  895. }
  896. auto FormatInstructionRHS(BlockArg inst) -> void {
  897. out_ << " ";
  898. FormatLabel(inst.block_id);
  899. }
  900. auto FormatInstructionRHS(Namespace inst) -> void {
  901. if (inst.import_id.is_valid()) {
  902. FormatArgs(inst.import_id, inst.name_scope_id);
  903. } else {
  904. FormatArgs(inst.name_scope_id);
  905. }
  906. }
  907. auto FormatInstruction(InstId /*inst_id*/, BranchIf inst) -> void {
  908. if (!in_terminator_sequence_) {
  909. Indent();
  910. }
  911. out_ << "if ";
  912. FormatInstName(inst.cond_id);
  913. out_ << " " << Branch::Kind.ir_name() << " ";
  914. FormatLabel(inst.target_id);
  915. out_ << " else ";
  916. in_terminator_sequence_ = true;
  917. }
  918. auto FormatInstruction(InstId /*inst_id*/, BranchWithArg inst) -> void {
  919. if (!in_terminator_sequence_) {
  920. Indent();
  921. }
  922. out_ << BranchWithArg::Kind.ir_name() << " ";
  923. FormatLabel(inst.target_id);
  924. out_ << "(";
  925. FormatInstName(inst.arg_id);
  926. out_ << ")\n";
  927. in_terminator_sequence_ = false;
  928. }
  929. auto FormatInstruction(InstId /*inst_id*/, Branch inst) -> void {
  930. if (!in_terminator_sequence_) {
  931. Indent();
  932. }
  933. out_ << Branch::Kind.ir_name() << " ";
  934. FormatLabel(inst.target_id);
  935. out_ << "\n";
  936. in_terminator_sequence_ = false;
  937. }
  938. auto FormatInstructionRHS(Call inst) -> void {
  939. out_ << " ";
  940. FormatArg(inst.callee_id);
  941. if (!inst.args_id.is_valid()) {
  942. out_ << "(<invalid>)";
  943. return;
  944. }
  945. llvm::ArrayRef<InstId> args = sem_ir_.inst_blocks().Get(inst.args_id);
  946. bool has_return_slot = GetInitRepr(sem_ir_, inst.type_id).has_return_slot();
  947. InstId return_slot_id = InstId::Invalid;
  948. if (has_return_slot) {
  949. return_slot_id = args.back();
  950. args = args.drop_back();
  951. }
  952. llvm::ListSeparator sep;
  953. out_ << '(';
  954. for (auto inst_id : args) {
  955. out_ << sep;
  956. FormatArg(inst_id);
  957. }
  958. out_ << ')';
  959. if (has_return_slot) {
  960. FormatReturnSlot(return_slot_id);
  961. }
  962. }
  963. auto FormatInstructionRHS(ArrayInit inst) -> void {
  964. FormatArgs(inst.inits_id);
  965. FormatReturnSlot(inst.dest_id);
  966. }
  967. auto FormatInstructionRHS(InitializeFrom inst) -> void {
  968. FormatArgs(inst.src_id);
  969. FormatReturnSlot(inst.dest_id);
  970. }
  971. auto FormatInstructionRHS(StructInit init) -> void {
  972. FormatArgs(init.elements_id);
  973. FormatReturnSlot(init.dest_id);
  974. }
  975. auto FormatInstructionRHS(TupleInit init) -> void {
  976. FormatArgs(init.elements_id);
  977. FormatReturnSlot(init.dest_id);
  978. }
  979. auto FormatInstructionRHS(FunctionDecl inst) -> void {
  980. FormatArgs(inst.function_id);
  981. FormatTrailingBlock(inst.decl_block_id);
  982. }
  983. auto FormatInstructionRHS(ClassDecl inst) -> void {
  984. FormatArgs(inst.class_id);
  985. FormatTrailingBlock(inst.decl_block_id);
  986. }
  987. auto FormatInstructionRHS(ImplDecl inst) -> void {
  988. FormatArgs(inst.impl_id);
  989. FormatTrailingBlock(inst.decl_block_id);
  990. }
  991. auto FormatInstructionRHS(InterfaceDecl inst) -> void {
  992. FormatArgs(inst.interface_id);
  993. FormatTrailingBlock(inst.decl_block_id);
  994. }
  995. auto FormatInstructionRHS(IntLiteral inst) -> void {
  996. out_ << " ";
  997. sem_ir_.ints()
  998. .Get(inst.int_id)
  999. .print(out_, sem_ir_.types().IsSignedInt(inst.type_id));
  1000. }
  1001. auto FormatInstructionRHS(ImportRefUnused inst) -> void {
  1002. // Don't format the inst_id because it refers to a different IR.
  1003. // TODO: Consider a better way to format the InstID from other IRs.
  1004. out_ << " " << inst.ir_id << ", " << inst.inst_id << ", unused";
  1005. }
  1006. auto FormatInstructionRHS(ImportRefUsed inst) -> void {
  1007. // Don't format the inst_id because it refers to a different IR.
  1008. // TODO: Consider a better way to format the InstID from other IRs.
  1009. out_ << " " << inst.ir_id << ", " << inst.inst_id << ", used";
  1010. }
  1011. auto FormatInstructionRHS(SpliceBlock inst) -> void {
  1012. FormatArgs(inst.result_id);
  1013. FormatTrailingBlock(inst.block_id);
  1014. }
  1015. // StructTypeFields are formatted as part of their StructType.
  1016. auto FormatInstruction(InstId /*inst_id*/, StructTypeField /*inst*/) -> void {
  1017. }
  1018. auto FormatInstructionRHS(StructType inst) -> void {
  1019. out_ << " {";
  1020. llvm::ListSeparator sep;
  1021. for (auto field_id : sem_ir_.inst_blocks().Get(inst.fields_id)) {
  1022. out_ << sep << ".";
  1023. auto field = sem_ir_.insts().GetAs<StructTypeField>(field_id);
  1024. FormatName(field.name_id);
  1025. out_ << ": ";
  1026. FormatType(field.field_type_id);
  1027. }
  1028. out_ << "}";
  1029. }
  1030. auto FormatArgs() -> void {}
  1031. template <typename... Args>
  1032. auto FormatArgs(Args... args) -> void {
  1033. out_ << ' ';
  1034. llvm::ListSeparator sep;
  1035. ((out_ << sep, FormatArg(args)), ...);
  1036. }
  1037. auto FormatArg(BoolValue v) -> void { out_ << v; }
  1038. auto FormatArg(BuiltinKind kind) -> void { out_ << kind.label(); }
  1039. auto FormatArg(BindNameId id) -> void {
  1040. FormatName(sem_ir_.bind_names().Get(id).name_id);
  1041. }
  1042. auto FormatArg(FunctionId id) -> void { FormatFunctionName(id); }
  1043. auto FormatArg(ClassId id) -> void { FormatClassName(id); }
  1044. auto FormatArg(InterfaceId id) -> void { FormatInterfaceName(id); }
  1045. auto FormatArg(ImplId id) -> void { FormatImplName(id); }
  1046. auto FormatArg(ImportIRId id) -> void { out_ << id; }
  1047. auto FormatArg(IntId id) -> void {
  1048. // We don't know the signedness to use here. Default to unsigned.
  1049. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  1050. }
  1051. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  1052. auto FormatArg(NameScopeId id) -> void {
  1053. OpenBrace();
  1054. FormatNameScope(id);
  1055. CloseBrace();
  1056. }
  1057. auto FormatArg(InstId id) -> void { FormatInstName(id); }
  1058. auto FormatArg(InstBlockId id) -> void {
  1059. if (!id.is_valid()) {
  1060. out_ << "invalid";
  1061. return;
  1062. }
  1063. out_ << '(';
  1064. llvm::ListSeparator sep;
  1065. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  1066. out_ << sep;
  1067. FormatArg(inst_id);
  1068. }
  1069. out_ << ')';
  1070. }
  1071. auto FormatArg(RealId id) -> void {
  1072. // TODO: Format with a `.` when the exponent is near zero.
  1073. const auto& real = sem_ir_.reals().Get(id);
  1074. real.mantissa.print(out_, /*isSigned=*/false);
  1075. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1076. }
  1077. auto FormatArg(StringLiteralValueId id) -> void {
  1078. out_ << '"';
  1079. out_.write_escaped(sem_ir_.string_literal_values().Get(id),
  1080. /*UseHexEscapes=*/true);
  1081. out_ << '"';
  1082. }
  1083. auto FormatArg(NameId id) -> void { FormatName(id); }
  1084. auto FormatArg(TypeId id) -> void { FormatType(id); }
  1085. auto FormatArg(TypeBlockId id) -> void {
  1086. out_ << '(';
  1087. llvm::ListSeparator sep;
  1088. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  1089. out_ << sep;
  1090. FormatArg(type_id);
  1091. }
  1092. out_ << ')';
  1093. }
  1094. auto FormatReturnSlot(InstId dest_id) -> void {
  1095. out_ << " to ";
  1096. FormatArg(dest_id);
  1097. }
  1098. auto FormatName(NameId id) -> void {
  1099. out_ << sem_ir_.names().GetFormatted(id);
  1100. }
  1101. auto FormatInstName(InstId id) -> void {
  1102. out_ << inst_namer_.GetNameFor(scope_, id);
  1103. }
  1104. auto FormatLabel(InstBlockId id) -> void {
  1105. out_ << inst_namer_.GetLabelFor(scope_, id);
  1106. }
  1107. auto FormatFunctionName(FunctionId id) -> void {
  1108. out_ << inst_namer_.GetNameFor(id);
  1109. }
  1110. auto FormatClassName(ClassId id) -> void {
  1111. out_ << inst_namer_.GetNameFor(id);
  1112. }
  1113. auto FormatInterfaceName(InterfaceId id) -> void {
  1114. out_ << inst_namer_.GetNameFor(id);
  1115. }
  1116. auto FormatImplName(ImplId id) -> void { out_ << inst_namer_.GetNameFor(id); }
  1117. auto FormatType(TypeId id) -> void {
  1118. if (!id.is_valid()) {
  1119. out_ << "invalid";
  1120. } else {
  1121. out_ << sem_ir_.StringifyType(id);
  1122. }
  1123. }
  1124. private:
  1125. const File& sem_ir_;
  1126. llvm::raw_ostream& out_;
  1127. InstNamer inst_namer_;
  1128. // The current scope that we are formatting within. References to names in
  1129. // this scope will not have a `@scope.` prefix added.
  1130. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  1131. // Whether we are formatting in a terminator sequence, that is, a sequence of
  1132. // branches at the end of a block. The entirety of a terminator sequence is
  1133. // formatted on a single line, despite being multiple instructions.
  1134. bool in_terminator_sequence_ = false;
  1135. // The indent depth to use for new instructions.
  1136. int indent_ = 0;
  1137. // Whether we are currently formatting immediately after an open brace. If so,
  1138. // a newline will be inserted before the next line indent.
  1139. bool after_open_brace_ = false;
  1140. // The constant value of the current instruction, if it has one that has not
  1141. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  1142. // there is nothing to print.
  1143. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  1144. // Whether `pending_constant_value_`'s instruction is the same as the
  1145. // instruction currently being printed. If true, only the phase of the
  1146. // constant is printed, and the value is omitted.
  1147. bool pending_constant_value_is_self_ = false;
  1148. };
  1149. auto FormatFile(const Lex::TokenizedBuffer& tokenized_buffer,
  1150. const Parse::Tree& parse_tree, const File& sem_ir,
  1151. llvm::raw_ostream& out) -> void {
  1152. Formatter(tokenized_buffer, parse_tree, sem_ir, out).Format();
  1153. }
  1154. } // namespace Carbon::SemIR