formatter.cpp 40 KB

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