formatter.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  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 Import::Kind: {
  448. add_inst_name("import");
  449. continue;
  450. }
  451. case ImportRefUnused::Kind:
  452. case ImportRefUsed::Kind: {
  453. add_inst_name("import_ref");
  454. // When building import refs, we frequently add instructions without a
  455. // block. Constants that refer to them need to be separately named.
  456. auto const_id = sem_ir_.constant_values().Get(inst_id);
  457. if (const_id.is_valid() && const_id.is_template() &&
  458. !insts[const_id.inst_id().index].second) {
  459. CollectNamesInBlock(ScopeId::ImportRef, const_id.inst_id());
  460. }
  461. continue;
  462. }
  463. case InterfaceDecl::Kind: {
  464. add_inst_name_id(sem_ir_.interfaces()
  465. .Get(inst.As<InterfaceDecl>().interface_id)
  466. .name_id,
  467. ".decl");
  468. CollectNamesInBlock(scope_id, inst.As<InterfaceDecl>().decl_block_id);
  469. continue;
  470. }
  471. case NameRef::Kind: {
  472. add_inst_name_id(inst.As<NameRef>().name_id, ".ref");
  473. continue;
  474. }
  475. case Param::Kind: {
  476. add_inst_name_id(inst.As<Param>().name_id);
  477. continue;
  478. }
  479. case SpliceBlock::Kind: {
  480. CollectNamesInBlock(scope_id, inst.As<SpliceBlock>().block_id);
  481. break;
  482. }
  483. case VarStorage::Kind: {
  484. add_inst_name_id(inst.As<VarStorage>().name_id, ".var");
  485. continue;
  486. }
  487. default: {
  488. break;
  489. }
  490. }
  491. // Sequentially number all remaining values.
  492. if (inst.kind().value_kind() != InstValueKind::None) {
  493. add_inst_name("");
  494. }
  495. }
  496. }
  497. const Lex::TokenizedBuffer& tokenized_buffer_;
  498. const Parse::Tree& parse_tree_;
  499. const File& sem_ir_;
  500. Namespace globals = {.prefix = "@"};
  501. std::vector<std::pair<ScopeId, Namespace::Name>> insts;
  502. std::vector<std::pair<ScopeId, Namespace::Name>> labels;
  503. std::vector<Scope> scopes;
  504. };
  505. } // namespace
  506. // Formatter for printing textual Semantics IR.
  507. class Formatter {
  508. public:
  509. enum class AddSpace : bool { Before, After };
  510. explicit Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  511. const Parse::Tree& parse_tree, const File& sem_ir,
  512. llvm::raw_ostream& out)
  513. : sem_ir_(sem_ir),
  514. out_(out),
  515. inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  516. // Prints the SemIR.
  517. //
  518. // Constants are printed first and may be referenced by later sections,
  519. // including file-scoped instructions. The file scope may contain entity
  520. // declarations which are defined later, such as classes.
  521. auto Format() -> void {
  522. out_ << "--- " << sem_ir_.filename() << "\n\n";
  523. FormatConstants();
  524. out_ << "file ";
  525. OpenBrace();
  526. // TODO: Handle the case where there are multiple top-level instruction
  527. // blocks. For example, there may be branching in the initializer of a
  528. // global or a type expression.
  529. if (auto block_id = sem_ir_.top_inst_block_id(); block_id.is_valid()) {
  530. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::File);
  531. FormatCodeBlock(block_id);
  532. }
  533. CloseBrace();
  534. out_ << '\n';
  535. for (int i : llvm::seq(sem_ir_.interfaces().size())) {
  536. FormatInterface(InterfaceId(i));
  537. }
  538. for (int i : llvm::seq(sem_ir_.impls().size())) {
  539. FormatImpl(ImplId(i));
  540. }
  541. for (int i : llvm::seq(sem_ir_.classes().size())) {
  542. FormatClass(ClassId(i));
  543. }
  544. for (int i : llvm::seq(sem_ir_.functions().size())) {
  545. FormatFunction(FunctionId(i));
  546. }
  547. // End-of-file newline.
  548. out_ << "\n";
  549. }
  550. // Begins a braced block. Writes an open brace, and prepares to insert a
  551. // newline after it if the braced block is non-empty.
  552. auto OpenBrace() -> void {
  553. // Put the constant value of an instruction before any braced block, rather
  554. // than at the end.
  555. FormatPendingConstantValue(AddSpace::After);
  556. out_ << '{';
  557. indent_ += 2;
  558. after_open_brace_ = true;
  559. }
  560. // Ends a braced block by writing a close brace.
  561. auto CloseBrace() -> void {
  562. indent_ -= 2;
  563. if (!after_open_brace_) {
  564. Indent();
  565. }
  566. out_ << '}';
  567. after_open_brace_ = false;
  568. }
  569. // Adds beginning-of-line indentation. If we're at the start of a braced
  570. // block, first starts a new line.
  571. auto Indent(int offset = 0) -> void {
  572. if (after_open_brace_) {
  573. out_ << '\n';
  574. after_open_brace_ = false;
  575. }
  576. out_.indent(indent_ + offset);
  577. }
  578. // Adds beginning-of-label indentation. This is one level less than normal
  579. // indentation. Labels also get a preceding blank line unless they're at the
  580. // start of a block.
  581. auto IndentLabel() -> void {
  582. CARBON_CHECK(indent_ >= 2);
  583. if (!after_open_brace_) {
  584. out_ << '\n';
  585. }
  586. Indent(-2);
  587. }
  588. auto FormatConstants() -> void {
  589. if (!sem_ir_.constants().size()) {
  590. return;
  591. }
  592. llvm::SaveAndRestore constants_scope(scope_, InstNamer::ScopeId::Constants);
  593. out_ << "constants ";
  594. OpenBrace();
  595. FormatCodeBlock(sem_ir_.constants().GetAsVector());
  596. CloseBrace();
  597. out_ << "\n\n";
  598. }
  599. auto FormatClass(ClassId id) -> void {
  600. const Class& class_info = sem_ir_.classes().Get(id);
  601. out_ << "\nclass ";
  602. FormatClassName(id);
  603. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  604. if (class_info.scope_id.is_valid()) {
  605. out_ << ' ';
  606. OpenBrace();
  607. FormatCodeBlock(class_info.body_block_id);
  608. FormatNameScope(class_info.scope_id, "!members:\n");
  609. CloseBrace();
  610. out_ << '\n';
  611. } else {
  612. out_ << ";\n";
  613. }
  614. }
  615. auto FormatInterface(InterfaceId id) -> void {
  616. const Interface& interface_info = sem_ir_.interfaces().Get(id);
  617. out_ << "\ninterface ";
  618. FormatInterfaceName(id);
  619. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  620. if (interface_info.scope_id.is_valid()) {
  621. out_ << ' ';
  622. OpenBrace();
  623. FormatCodeBlock(interface_info.body_block_id);
  624. // Always include the !members label because we always list the witness in
  625. // this section.
  626. IndentLabel();
  627. out_ << "!members:\n";
  628. FormatNameScope(interface_info.scope_id);
  629. Indent();
  630. out_ << "witness = ";
  631. FormatArg(interface_info.associated_entities_id);
  632. out_ << "\n";
  633. CloseBrace();
  634. out_ << '\n';
  635. } else {
  636. out_ << ";\n";
  637. }
  638. }
  639. auto FormatImpl(ImplId id) -> void {
  640. const Impl& impl_info = sem_ir_.impls().Get(id);
  641. out_ << "\nimpl ";
  642. FormatImplName(id);
  643. out_ << ": ";
  644. // TODO: Include the deduced parameter list if present.
  645. FormatType(impl_info.self_id);
  646. out_ << " as ";
  647. FormatType(impl_info.constraint_id);
  648. llvm::SaveAndRestore impl_scope(scope_, inst_namer_.GetScopeFor(id));
  649. if (impl_info.scope_id.is_valid()) {
  650. out_ << ' ';
  651. OpenBrace();
  652. FormatCodeBlock(impl_info.body_block_id);
  653. // Print the !members label even if the name scope is empty because we
  654. // always list the witness in this section.
  655. IndentLabel();
  656. out_ << "!members:\n";
  657. FormatNameScope(impl_info.scope_id);
  658. Indent();
  659. out_ << "witness = ";
  660. FormatArg(impl_info.witness_id);
  661. out_ << "\n";
  662. CloseBrace();
  663. out_ << '\n';
  664. } else {
  665. out_ << ";\n";
  666. }
  667. }
  668. auto FormatFunction(FunctionId id) -> void {
  669. const Function& fn = sem_ir_.functions().Get(id);
  670. out_ << "\nfn ";
  671. FormatFunctionName(id);
  672. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  673. if (fn.implicit_param_refs_id != InstBlockId::Empty) {
  674. out_ << "[";
  675. FormatParamList(fn.implicit_param_refs_id);
  676. out_ << "]";
  677. }
  678. out_ << "(";
  679. FormatParamList(fn.param_refs_id);
  680. out_ << ")";
  681. if (fn.return_type_id.is_valid()) {
  682. out_ << " -> ";
  683. if (fn.return_slot_id.is_valid()) {
  684. FormatInstName(fn.return_slot_id);
  685. out_ << ": ";
  686. }
  687. FormatType(fn.return_type_id);
  688. }
  689. if (!fn.body_block_ids.empty()) {
  690. out_ << ' ';
  691. OpenBrace();
  692. for (auto block_id : fn.body_block_ids) {
  693. IndentLabel();
  694. FormatLabel(block_id);
  695. out_ << ":\n";
  696. FormatCodeBlock(block_id);
  697. }
  698. CloseBrace();
  699. out_ << '\n';
  700. } else {
  701. out_ << ";\n";
  702. }
  703. }
  704. auto FormatParamList(InstBlockId param_refs_id) -> void {
  705. llvm::ListSeparator sep;
  706. for (InstId param_id : sem_ir_.inst_blocks().Get(param_refs_id)) {
  707. out_ << sep;
  708. if (!param_id.is_valid()) {
  709. out_ << "invalid";
  710. continue;
  711. }
  712. if (auto addr = sem_ir_.insts().TryGetAs<SemIR::AddrPattern>(param_id)) {
  713. out_ << "addr ";
  714. param_id = addr->inner_id;
  715. }
  716. FormatInstName(param_id);
  717. out_ << ": ";
  718. FormatType(sem_ir_.insts().Get(param_id).type_id());
  719. }
  720. }
  721. auto FormatCodeBlock(InstBlockId block_id) -> void {
  722. if (block_id.is_valid()) {
  723. FormatCodeBlock(sem_ir_.inst_blocks().Get(block_id));
  724. }
  725. }
  726. auto FormatCodeBlock(llvm::ArrayRef<InstId> block) -> void {
  727. for (const InstId inst_id : block) {
  728. FormatInstruction(inst_id);
  729. }
  730. }
  731. auto FormatTrailingBlock(InstBlockId block_id) -> void {
  732. out_ << ' ';
  733. OpenBrace();
  734. FormatCodeBlock(block_id);
  735. CloseBrace();
  736. }
  737. auto FormatNameScope(NameScopeId id, llvm::StringRef label = "") -> void {
  738. const auto& scope = sem_ir_.name_scopes().Get(id);
  739. if (scope.names.empty() && scope.extended_scopes.empty() &&
  740. !scope.has_error) {
  741. // Name scope is empty.
  742. return;
  743. }
  744. if (!label.empty()) {
  745. IndentLabel();
  746. out_ << label;
  747. }
  748. // Name scopes aren't kept in any particular order. Sort the entries before
  749. // we print them for stability and consistency.
  750. llvm::SmallVector<std::pair<InstId, NameId>> entries;
  751. for (auto [name_id, inst_id] : scope.names) {
  752. entries.push_back({inst_id, name_id});
  753. }
  754. llvm::sort(entries,
  755. [](auto a, auto b) { return a.first.index < b.first.index; });
  756. for (auto [inst_id, name_id] : entries) {
  757. Indent();
  758. out_ << ".";
  759. FormatName(name_id);
  760. out_ << " = ";
  761. FormatInstName(inst_id);
  762. out_ << "\n";
  763. }
  764. for (auto extended_scope_id : scope.extended_scopes) {
  765. // TODO: Print this scope in a better way.
  766. Indent();
  767. out_ << "extend " << extended_scope_id << "\n";
  768. }
  769. if (scope.has_error) {
  770. Indent();
  771. out_ << "has_error\n";
  772. }
  773. }
  774. auto FormatInstruction(InstId inst_id) -> void {
  775. if (!inst_id.is_valid()) {
  776. Indent();
  777. out_ << "invalid\n";
  778. return;
  779. }
  780. FormatInstruction(inst_id, sem_ir_.insts().Get(inst_id));
  781. }
  782. auto FormatInstruction(InstId inst_id, Inst inst) -> void {
  783. switch (inst.kind()) {
  784. #define CARBON_SEM_IR_INST_KIND(InstT) \
  785. case InstT::Kind: \
  786. FormatInstruction(inst_id, inst.As<InstT>()); \
  787. break;
  788. #include "toolchain/sem_ir/inst_kind.def"
  789. }
  790. }
  791. template <typename InstT>
  792. auto FormatInstruction(InstId inst_id, InstT inst) -> void {
  793. Indent();
  794. FormatInstructionLHS(inst_id, inst);
  795. out_ << InstT::Kind.ir_name();
  796. pending_constant_value_ = sem_ir_.constant_values().Get(inst_id);
  797. pending_constant_value_is_self_ =
  798. pending_constant_value_.inst_id() == inst_id;
  799. FormatInstructionRHS(inst);
  800. FormatPendingConstantValue(AddSpace::Before);
  801. out_ << "\n";
  802. }
  803. // Don't print a constant for ImportRefUnused.
  804. auto FormatInstruction(InstId inst_id, ImportRefUnused inst) -> void {
  805. Indent();
  806. FormatInstructionLHS(inst_id, inst);
  807. out_ << ImportRefUnused::Kind.ir_name();
  808. FormatInstructionRHS(inst);
  809. out_ << "\n";
  810. }
  811. // If there is a pending constant value attached to the current instruction,
  812. // print it now and clear it out. The constant value gets printed before the
  813. // first braced block argument, or at the end of the instruction if there are
  814. // no such arguments.
  815. auto FormatPendingConstantValue(AddSpace space_where) -> void {
  816. if (pending_constant_value_ == ConstantId::NotConstant) {
  817. return;
  818. }
  819. if (space_where == AddSpace::Before) {
  820. out_ << ' ';
  821. }
  822. out_ << '[';
  823. if (pending_constant_value_.is_valid()) {
  824. out_ << (pending_constant_value_.is_symbolic() ? "symbolic" : "template");
  825. if (!pending_constant_value_is_self_) {
  826. out_ << " = ";
  827. FormatInstName(pending_constant_value_.inst_id());
  828. }
  829. } else {
  830. out_ << pending_constant_value_;
  831. }
  832. out_ << ']';
  833. if (space_where == AddSpace::After) {
  834. out_ << ' ';
  835. }
  836. pending_constant_value_ = ConstantId::NotConstant;
  837. }
  838. auto FormatInstructionLHS(InstId inst_id, Inst inst) -> void {
  839. switch (inst.kind().value_kind()) {
  840. case InstValueKind::Typed:
  841. FormatInstName(inst_id);
  842. out_ << ": ";
  843. switch (GetExprCategory(sem_ir_, inst_id)) {
  844. case ExprCategory::NotExpr:
  845. case ExprCategory::Error:
  846. case ExprCategory::Value:
  847. case ExprCategory::Mixed:
  848. break;
  849. case ExprCategory::DurableRef:
  850. case ExprCategory::EphemeralRef:
  851. out_ << "ref ";
  852. break;
  853. case ExprCategory::Initializing:
  854. out_ << "init ";
  855. break;
  856. }
  857. FormatType(inst.type_id());
  858. out_ << " = ";
  859. break;
  860. case InstValueKind::None:
  861. break;
  862. }
  863. }
  864. // Print ImportRefUnused with type-like semantics even though it lacks a
  865. // type_id.
  866. auto FormatInstructionLHS(InstId inst_id, ImportRefUnused /*inst*/) -> void {
  867. FormatInstName(inst_id);
  868. out_ << " = ";
  869. }
  870. template <typename InstT>
  871. auto FormatInstructionRHS(InstT inst) -> void {
  872. // By default, an instruction has a comma-separated argument list.
  873. using Info = Internal::InstLikeTypeInfo<InstT>;
  874. if constexpr (Info::NumArgs == 2) {
  875. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  876. } else if constexpr (Info::NumArgs == 1) {
  877. FormatArgs(Info::template Get<0>(inst));
  878. } else {
  879. FormatArgs();
  880. }
  881. }
  882. auto FormatInstructionRHS(BindSymbolicName inst) -> void {
  883. // A BindSymbolicName with no value is a purely symbolic binding, such as
  884. // the `Self` in an interface. Don't print out `invalid` for the value.
  885. if (inst.value_id.is_valid()) {
  886. FormatArgs(inst.bind_name_id, inst.value_id);
  887. } else {
  888. FormatArgs(inst.bind_name_id);
  889. }
  890. }
  891. auto FormatInstructionRHS(BlockArg inst) -> void {
  892. out_ << " ";
  893. FormatLabel(inst.block_id);
  894. }
  895. auto FormatInstructionRHS(Namespace inst) -> void {
  896. if (inst.import_id.is_valid()) {
  897. FormatArgs(inst.import_id, inst.name_scope_id);
  898. } else {
  899. FormatArgs(inst.name_scope_id);
  900. }
  901. }
  902. auto FormatInstruction(InstId /*inst_id*/, BranchIf inst) -> void {
  903. if (!in_terminator_sequence_) {
  904. Indent();
  905. }
  906. out_ << "if ";
  907. FormatInstName(inst.cond_id);
  908. out_ << " " << Branch::Kind.ir_name() << " ";
  909. FormatLabel(inst.target_id);
  910. out_ << " else ";
  911. in_terminator_sequence_ = true;
  912. }
  913. auto FormatInstruction(InstId /*inst_id*/, BranchWithArg inst) -> void {
  914. if (!in_terminator_sequence_) {
  915. Indent();
  916. }
  917. out_ << BranchWithArg::Kind.ir_name() << " ";
  918. FormatLabel(inst.target_id);
  919. out_ << "(";
  920. FormatInstName(inst.arg_id);
  921. out_ << ")\n";
  922. in_terminator_sequence_ = false;
  923. }
  924. auto FormatInstruction(InstId /*inst_id*/, Branch inst) -> void {
  925. if (!in_terminator_sequence_) {
  926. Indent();
  927. }
  928. out_ << Branch::Kind.ir_name() << " ";
  929. FormatLabel(inst.target_id);
  930. out_ << "\n";
  931. in_terminator_sequence_ = false;
  932. }
  933. auto FormatInstructionRHS(Call inst) -> void {
  934. out_ << " ";
  935. FormatArg(inst.callee_id);
  936. if (!inst.args_id.is_valid()) {
  937. out_ << "(<invalid>)";
  938. return;
  939. }
  940. llvm::ArrayRef<InstId> args = sem_ir_.inst_blocks().Get(inst.args_id);
  941. bool has_return_slot = GetInitRepr(sem_ir_, inst.type_id).has_return_slot();
  942. InstId return_slot_id = InstId::Invalid;
  943. if (has_return_slot) {
  944. return_slot_id = args.back();
  945. args = args.drop_back();
  946. }
  947. llvm::ListSeparator sep;
  948. out_ << '(';
  949. for (auto inst_id : args) {
  950. out_ << sep;
  951. FormatArg(inst_id);
  952. }
  953. out_ << ')';
  954. if (has_return_slot) {
  955. FormatReturnSlot(return_slot_id);
  956. }
  957. }
  958. auto FormatInstructionRHS(ArrayInit inst) -> void {
  959. FormatArgs(inst.inits_id);
  960. FormatReturnSlot(inst.dest_id);
  961. }
  962. auto FormatInstructionRHS(InitializeFrom inst) -> void {
  963. FormatArgs(inst.src_id);
  964. FormatReturnSlot(inst.dest_id);
  965. }
  966. auto FormatInstructionRHS(StructInit init) -> void {
  967. FormatArgs(init.elements_id);
  968. FormatReturnSlot(init.dest_id);
  969. }
  970. auto FormatInstructionRHS(TupleInit init) -> void {
  971. FormatArgs(init.elements_id);
  972. FormatReturnSlot(init.dest_id);
  973. }
  974. auto FormatInstructionRHS(FunctionDecl inst) -> void {
  975. FormatArgs(inst.function_id);
  976. FormatTrailingBlock(inst.decl_block_id);
  977. }
  978. auto FormatInstructionRHS(ClassDecl inst) -> void {
  979. FormatArgs(inst.class_id);
  980. FormatTrailingBlock(inst.decl_block_id);
  981. }
  982. auto FormatInstructionRHS(ImplDecl inst) -> void {
  983. FormatArgs(inst.impl_id);
  984. FormatTrailingBlock(inst.decl_block_id);
  985. }
  986. auto FormatInstructionRHS(InterfaceDecl inst) -> void {
  987. FormatArgs(inst.interface_id);
  988. FormatTrailingBlock(inst.decl_block_id);
  989. }
  990. auto FormatInstructionRHS(ImportRefUnused inst) -> void {
  991. // Don't format the inst_id because it refers to a different IR.
  992. // TODO: Consider a better way to format the InstID from other IRs.
  993. out_ << " " << inst.ir_id << ", " << inst.inst_id << ", unused";
  994. }
  995. auto FormatInstructionRHS(ImportRefUsed inst) -> void {
  996. // Don't format the inst_id because it refers to a different IR.
  997. // TODO: Consider a better way to format the InstID from other IRs.
  998. out_ << " " << inst.ir_id << ", " << inst.inst_id << ", used";
  999. }
  1000. auto FormatInstructionRHS(SpliceBlock inst) -> void {
  1001. FormatArgs(inst.result_id);
  1002. FormatTrailingBlock(inst.block_id);
  1003. }
  1004. // StructTypeFields are formatted as part of their StructType.
  1005. auto FormatInstruction(InstId /*inst_id*/, StructTypeField /*inst*/) -> void {
  1006. }
  1007. auto FormatInstructionRHS(StructType inst) -> void {
  1008. out_ << " {";
  1009. llvm::ListSeparator sep;
  1010. for (auto field_id : sem_ir_.inst_blocks().Get(inst.fields_id)) {
  1011. out_ << sep << ".";
  1012. auto field = sem_ir_.insts().GetAs<StructTypeField>(field_id);
  1013. FormatName(field.name_id);
  1014. out_ << ": ";
  1015. FormatType(field.field_type_id);
  1016. }
  1017. out_ << "}";
  1018. }
  1019. auto FormatArgs() -> void {}
  1020. template <typename... Args>
  1021. auto FormatArgs(Args... args) -> void {
  1022. out_ << ' ';
  1023. llvm::ListSeparator sep;
  1024. ((out_ << sep, FormatArg(args)), ...);
  1025. }
  1026. auto FormatArg(BoolValue v) -> void { out_ << v; }
  1027. auto FormatArg(BuiltinKind kind) -> void { out_ << kind.label(); }
  1028. auto FormatArg(BindNameId id) -> void {
  1029. FormatName(sem_ir_.bind_names().Get(id).name_id);
  1030. }
  1031. auto FormatArg(FunctionId id) -> void { FormatFunctionName(id); }
  1032. auto FormatArg(ClassId id) -> void { FormatClassName(id); }
  1033. auto FormatArg(InterfaceId id) -> void { FormatInterfaceName(id); }
  1034. auto FormatArg(ImplId id) -> void { FormatImplName(id); }
  1035. auto FormatArg(ImportIRId id) -> void { out_ << id; }
  1036. auto FormatArg(IntId id) -> void {
  1037. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  1038. }
  1039. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  1040. auto FormatArg(NameScopeId id) -> void {
  1041. OpenBrace();
  1042. FormatNameScope(id);
  1043. CloseBrace();
  1044. }
  1045. auto FormatArg(InstId id) -> void { FormatInstName(id); }
  1046. auto FormatArg(InstBlockId id) -> void {
  1047. if (!id.is_valid()) {
  1048. out_ << "invalid";
  1049. return;
  1050. }
  1051. out_ << '(';
  1052. llvm::ListSeparator sep;
  1053. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  1054. out_ << sep;
  1055. FormatArg(inst_id);
  1056. }
  1057. out_ << ')';
  1058. }
  1059. auto FormatArg(RealId id) -> void {
  1060. // TODO: Format with a `.` when the exponent is near zero.
  1061. const auto& real = sem_ir_.reals().Get(id);
  1062. real.mantissa.print(out_, /*isSigned=*/false);
  1063. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1064. }
  1065. auto FormatArg(StringLiteralValueId id) -> void {
  1066. out_ << '"';
  1067. out_.write_escaped(sem_ir_.string_literal_values().Get(id),
  1068. /*UseHexEscapes=*/true);
  1069. out_ << '"';
  1070. }
  1071. auto FormatArg(NameId id) -> void { FormatName(id); }
  1072. auto FormatArg(TypeId id) -> void { FormatType(id); }
  1073. auto FormatArg(TypeBlockId id) -> void {
  1074. out_ << '(';
  1075. llvm::ListSeparator sep;
  1076. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  1077. out_ << sep;
  1078. FormatArg(type_id);
  1079. }
  1080. out_ << ')';
  1081. }
  1082. auto FormatReturnSlot(InstId dest_id) -> void {
  1083. out_ << " to ";
  1084. FormatArg(dest_id);
  1085. }
  1086. auto FormatName(NameId id) -> void {
  1087. out_ << sem_ir_.names().GetFormatted(id);
  1088. }
  1089. auto FormatInstName(InstId id) -> void {
  1090. out_ << inst_namer_.GetNameFor(scope_, id);
  1091. }
  1092. auto FormatLabel(InstBlockId id) -> void {
  1093. out_ << inst_namer_.GetLabelFor(scope_, id);
  1094. }
  1095. auto FormatFunctionName(FunctionId id) -> void {
  1096. out_ << inst_namer_.GetNameFor(id);
  1097. }
  1098. auto FormatClassName(ClassId id) -> void {
  1099. out_ << inst_namer_.GetNameFor(id);
  1100. }
  1101. auto FormatInterfaceName(InterfaceId id) -> void {
  1102. out_ << inst_namer_.GetNameFor(id);
  1103. }
  1104. auto FormatImplName(ImplId id) -> void { out_ << inst_namer_.GetNameFor(id); }
  1105. auto FormatType(TypeId id) -> void {
  1106. if (!id.is_valid()) {
  1107. out_ << "invalid";
  1108. } else {
  1109. out_ << sem_ir_.StringifyType(id);
  1110. }
  1111. }
  1112. private:
  1113. const File& sem_ir_;
  1114. llvm::raw_ostream& out_;
  1115. InstNamer inst_namer_;
  1116. // The current scope that we are formatting within. References to names in
  1117. // this scope will not have a `@scope.` prefix added.
  1118. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  1119. // Whether we are formatting in a terminator sequence, that is, a sequence of
  1120. // branches at the end of a block. The entirety of a terminator sequence is
  1121. // formatted on a single line, despite being multiple instructions.
  1122. bool in_terminator_sequence_ = false;
  1123. // The indent depth to use for new instructions.
  1124. int indent_ = 0;
  1125. // Whether we are currently formatting immediately after an open brace. If so,
  1126. // a newline will be inserted before the next line indent.
  1127. bool after_open_brace_ = false;
  1128. // The constant value of the current instruction, if it has one that has not
  1129. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  1130. // there is nothing to print.
  1131. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  1132. // Whether `pending_constant_value_`'s instruction is the same as the
  1133. // instruction currently being printed. If true, only the phase of the
  1134. // constant is printed, and the value is omitted.
  1135. bool pending_constant_value_is_self_ = false;
  1136. };
  1137. auto FormatFile(const Lex::TokenizedBuffer& tokenized_buffer,
  1138. const Parse::Tree& parse_tree, const File& sem_ir,
  1139. llvm::raw_ostream& out) -> void {
  1140. Formatter(tokenized_buffer, parse_tree, sem_ir, out).Format();
  1141. }
  1142. } // namespace Carbon::SemIR