formatter.cpp 40 KB

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