formatter.cpp 40 KB

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