semantics_ir_formatter.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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/semantics/semantics_ir_formatter.h"
  5. #include "llvm/ADT/StringExtras.h"
  6. #include "llvm/ADT/StringSet.h"
  7. #include "llvm/Support/SaveAndRestore.h"
  8. #include "toolchain/lexer/tokenized_buffer.h"
  9. #include "toolchain/parser/parse_tree.h"
  10. namespace Carbon {
  11. namespace {
  12. // Assigns names to nodes, blocks, and scopes in the Semantics IR.
  13. //
  14. // TODOs / future work ideas:
  15. // - Add a documentation file for the textual format and link to the
  16. // naming section here.
  17. // - Consider harmonizing `FooLiteral` vs. `foo_value` node names vs.
  18. // IR names.
  19. // - Also consider representing these as just `value` or `literal`
  20. // in the IR and using the type to distinguish.
  21. // - Add block names based on the control flow construct names (`for`,
  22. // `if`, `then`, `else`, ...). Either base this on the semantics or
  23. // just on the keywords used to build that control flow -- little
  24. // or no harm to getting it wrong. Tools will also want to be able
  25. // to query the construct that resulted in control flow.
  26. class NodeNamer {
  27. public:
  28. enum class ScopeIndex : int {
  29. None = -1,
  30. Package = 0,
  31. };
  32. NodeNamer(const TokenizedBuffer& tokenized_buffer,
  33. const ParseTree& parse_tree, const SemanticsIR& semantics_ir)
  34. : tokenized_buffer_(tokenized_buffer),
  35. parse_tree_(parse_tree),
  36. semantics_ir_(semantics_ir) {
  37. nodes.resize(semantics_ir.nodes_size());
  38. labels.resize(semantics_ir.node_blocks_size());
  39. scopes.resize(1 + semantics_ir.functions_size());
  40. // Build the package scope.
  41. GetScopeInfo(ScopeIndex::Package).name =
  42. globals.AddNameUnchecked("package");
  43. CollectNamesInBlock(ScopeIndex::Package, semantics_ir.top_node_block_id());
  44. // Build each function scope.
  45. for (int i = 0; i != semantics_ir.functions_size(); ++i) {
  46. auto fn_id = SemanticsFunctionId(i);
  47. auto fn_scope = GetScopeFor(fn_id);
  48. const auto& fn = semantics_ir.GetFunction(fn_id);
  49. GetScopeInfo(fn_scope).name = globals.AllocateName(
  50. *this,
  51. // TODO: Provide a location for the function for use as a
  52. // disambiguator.
  53. ParseTree::Node::Invalid,
  54. fn.name_id.is_valid() ? semantics_ir.GetString(fn.name_id).str()
  55. : "");
  56. CollectNamesInBlock(fn_scope, fn.param_refs_id);
  57. for (auto block_id : fn.body_block_ids) {
  58. AddBlockLabel(fn_scope, block_id,
  59. block_id == fn.body_block_ids.front() ? "entry" : "");
  60. CollectNamesInBlock(fn_scope, block_id);
  61. }
  62. }
  63. }
  64. // Returns the scope index corresponding to a function.
  65. auto GetScopeFor(SemanticsFunctionId fn_id) -> ScopeIndex {
  66. return ScopeIndex(fn_id.index + 1);
  67. }
  68. // Returns the IR name to use for a function.
  69. auto GetNameFor(SemanticsFunctionId fn_id) -> llvm::StringRef {
  70. if (!fn_id.is_valid()) {
  71. return "invalid";
  72. }
  73. return GetScopeInfo(GetScopeFor(fn_id)).name;
  74. }
  75. // Returns the IR name to use for a node, when referenced from a given scope.
  76. auto GetNameFor(ScopeIndex scope_idx, SemanticsNodeId node_id)
  77. -> std::string {
  78. if (!node_id.is_valid()) {
  79. return "invalid";
  80. }
  81. // Check for a builtin.
  82. if (node_id.index < SemanticsBuiltinKind::ValidCount) {
  83. return SemanticsBuiltinKind::FromInt(node_id.index).label().str();
  84. }
  85. auto& [node_scope, node_name] = nodes[node_id.index];
  86. if (!node_name) {
  87. // This should not happen in valid IR.
  88. return "<unexpected noderef " + llvm::itostr(node_id.index) + ">";
  89. }
  90. if (node_scope == scope_idx) {
  91. return node_name.str().str();
  92. }
  93. return (GetScopeInfo(node_scope).name.str() + "." + node_name.str()).str();
  94. }
  95. // Returns the IR name to use for a label, when referenced from a given scope.
  96. auto GetLabelFor(ScopeIndex scope_idx, SemanticsNodeBlockId block_id)
  97. -> std::string {
  98. if (!block_id.is_valid()) {
  99. return "!invalid";
  100. }
  101. auto& [label_scope, label_name] = labels[block_id.index];
  102. if (!label_name) {
  103. // This should not happen in valid IR.
  104. return "<unexpected nodeblockref " + llvm::itostr(block_id.index) + ">";
  105. }
  106. if (label_scope == scope_idx) {
  107. return label_name.str().str();
  108. }
  109. return (GetScopeInfo(label_scope).name.str() + "." + label_name.str())
  110. .str();
  111. }
  112. private:
  113. // A space in which unique names can be allocated.
  114. struct Namespace {
  115. // A result of a name lookup.
  116. struct NameResult;
  117. // A name in a namespace, which might be redirected to refer to another name
  118. // for disambiguation purposes.
  119. class Name {
  120. public:
  121. Name() : value_(nullptr) {}
  122. explicit Name(llvm::StringMapIterator<NameResult> it) : value_(&*it) {}
  123. explicit operator bool() const { return value_; }
  124. auto str() const -> llvm::StringRef {
  125. llvm::StringMapEntry<NameResult>* value = value_;
  126. CARBON_CHECK(value) << "cannot print a null name";
  127. while (value->second.ambiguous && value->second.fallback) {
  128. value = value->second.fallback.value_;
  129. }
  130. return value->first();
  131. }
  132. operator llvm::StringRef() const { return str(); }
  133. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  134. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  135. private:
  136. llvm::StringMapEntry<NameResult>* value_;
  137. };
  138. struct NameResult {
  139. bool ambiguous = false;
  140. Name fallback = Name();
  141. };
  142. llvm::StringRef prefix;
  143. llvm::StringMap<NameResult> allocated = {};
  144. int unnamed_count = 0;
  145. auto AddNameUnchecked(llvm::StringRef name) -> Name {
  146. return Name(allocated.insert({name, NameResult()}).first);
  147. }
  148. auto AllocateName(const NodeNamer& namer, ParseTree::Node node,
  149. std::string name = "") -> Name {
  150. // The best (shortest) name for this node so far, and the current name
  151. // for it.
  152. Name best;
  153. Name current;
  154. // Add `name` as a name for this entity.
  155. auto add_name = [&](bool mark_ambiguous = true) {
  156. auto [it, added] = allocated.insert({name, NameResult()});
  157. Name new_name = Name(it);
  158. if (!added) {
  159. if (mark_ambiguous) {
  160. // This name was allocated for a different node. Mark it as
  161. // ambiguous and keep looking for a name for this node.
  162. new_name.SetAmbiguous();
  163. }
  164. } else {
  165. if (!best) {
  166. best = new_name;
  167. } else {
  168. CARBON_CHECK(current);
  169. current.SetFallback(new_name);
  170. }
  171. current = new_name;
  172. }
  173. return added;
  174. };
  175. // All names start with the prefix.
  176. name.insert(0, prefix);
  177. // Use the given name if it's available and not just the prefix.
  178. if (name.size() > prefix.size()) {
  179. add_name();
  180. }
  181. // Append location information to try to disambiguate.
  182. if (node.is_valid()) {
  183. auto token = namer.parse_tree_.node_token(node);
  184. llvm::raw_string_ostream(name)
  185. << ".loc" << namer.tokenized_buffer_.GetLineNumber(token);
  186. add_name();
  187. llvm::raw_string_ostream(name)
  188. << "_" << namer.tokenized_buffer_.GetColumnNumber(token);
  189. add_name();
  190. }
  191. // Append numbers until we find an available name.
  192. name += ".";
  193. auto name_size_without_counter = name.size();
  194. for (int counter = 1;; ++counter) {
  195. name.resize(name_size_without_counter);
  196. llvm::raw_string_ostream(name) << counter;
  197. if (add_name(/*mark_ambiguous=*/false)) {
  198. return best;
  199. }
  200. }
  201. }
  202. };
  203. // A named scope that contains named entities.
  204. struct Scope {
  205. Namespace::Name name;
  206. Namespace nodes = {.prefix = "%"};
  207. Namespace labels = {.prefix = "!"};
  208. };
  209. auto GetScopeInfo(ScopeIndex scope_idx) -> Scope& {
  210. return scopes[(int)scope_idx];
  211. }
  212. auto AddBlockLabel(ScopeIndex scope_idx, SemanticsNodeBlockId block_id,
  213. std::string name = "") -> void {
  214. if (!block_id.is_valid()) {
  215. return;
  216. }
  217. ParseTree::Node parse_node = ParseTree::Node::Invalid;
  218. if (auto& block = semantics_ir_.GetNodeBlock(block_id); !block.empty()) {
  219. parse_node = semantics_ir_.GetNode(block.front()).parse_node();
  220. }
  221. labels[block_id.index] = {scope_idx,
  222. GetScopeInfo(scope_idx).labels.AllocateName(
  223. *this, parse_node, std::move(name))};
  224. }
  225. auto CollectNamesInBlock(ScopeIndex scope_idx, SemanticsNodeBlockId block_id)
  226. -> void {
  227. if (!block_id.is_valid()) {
  228. return;
  229. }
  230. Scope& scope = GetScopeInfo(scope_idx);
  231. // Use bound names where available. The BindName node appears after the node
  232. // that it's giving a name to, so we need to do this before assigning
  233. // fallback names.
  234. for (auto node_id : semantics_ir_.GetNodeBlock(block_id)) {
  235. auto node = semantics_ir_.GetNode(node_id);
  236. if (node.kind() == SemanticsNodeKind::BindName) {
  237. auto [name_id, named_node_id] = node.GetAsBindName();
  238. nodes[named_node_id.index] = {
  239. scope_idx,
  240. scope.nodes.AllocateName(*this, node.parse_node(),
  241. semantics_ir_.GetString(name_id).str())};
  242. }
  243. }
  244. // Sequentially number all remaining values.
  245. for (auto node_id : semantics_ir_.GetNodeBlock(block_id)) {
  246. auto node = semantics_ir_.GetNode(node_id);
  247. if (node.kind() != SemanticsNodeKind::BindName &&
  248. node.kind().value_kind() != SemanticsNodeValueKind::None) {
  249. auto& name = nodes[node_id.index];
  250. if (!name.second) {
  251. name = {scope_idx,
  252. scope.nodes.AllocateName(*this, node.parse_node())};
  253. }
  254. }
  255. }
  256. }
  257. const TokenizedBuffer& tokenized_buffer_;
  258. const ParseTree& parse_tree_;
  259. const SemanticsIR& semantics_ir_;
  260. Namespace globals = {.prefix = "@"};
  261. std::vector<std::pair<ScopeIndex, Namespace::Name>> nodes;
  262. std::vector<std::pair<ScopeIndex, Namespace::Name>> labels;
  263. std::vector<Scope> scopes;
  264. };
  265. } // namespace
  266. // Formatter for printing textual Semantics IR.
  267. class SemanticsIRFormatter {
  268. public:
  269. explicit SemanticsIRFormatter(const TokenizedBuffer& tokenized_buffer,
  270. const ParseTree& parse_tree,
  271. const SemanticsIR& semantics_ir,
  272. llvm::raw_ostream& out)
  273. : semantics_ir_(semantics_ir),
  274. out_(out),
  275. node_namer_(tokenized_buffer, parse_tree, semantics_ir) {}
  276. auto Format() -> void {
  277. // TODO: Include information from the package declaration, once we fully
  278. // support it.
  279. out_ << "package {\n";
  280. // TODO: Handle the case where there are multiple top-level node blocks.
  281. // For example, there may be branching in the initializer of a global or a
  282. // type expression.
  283. if (auto block_id = semantics_ir_.top_node_block_id();
  284. block_id.is_valid()) {
  285. llvm::SaveAndRestore package_scope(scope_,
  286. NodeNamer::ScopeIndex::Package);
  287. FormatCodeBlock(block_id);
  288. }
  289. out_ << "}\n";
  290. for (int i = 0; i != semantics_ir_.functions_size(); ++i) {
  291. FormatFunction(SemanticsFunctionId(i));
  292. }
  293. }
  294. auto FormatFunction(SemanticsFunctionId id) -> void {
  295. const SemanticsFunction& fn = semantics_ir_.GetFunction(id);
  296. out_ << "\nfn ";
  297. FormatFunctionName(id);
  298. out_ << "(";
  299. llvm::SaveAndRestore function_scope(scope_, node_namer_.GetScopeFor(id));
  300. llvm::ListSeparator sep;
  301. for (const SemanticsNodeId param_id :
  302. semantics_ir_.GetNodeBlock(fn.param_refs_id)) {
  303. out_ << sep;
  304. auto param = semantics_ir_.GetNode(param_id);
  305. auto [name_id, node_id] = param.GetAsBindName();
  306. FormatNodeName(node_id);
  307. out_ << ": ";
  308. FormatType(param.type_id());
  309. }
  310. out_ << ")";
  311. if (fn.return_type_id.is_valid()) {
  312. out_ << " -> ";
  313. FormatType(fn.return_type_id);
  314. }
  315. if (!fn.body_block_ids.empty()) {
  316. out_ << " {";
  317. for (auto block_id : fn.body_block_ids) {
  318. out_ << "\n";
  319. FormatLabel(block_id);
  320. out_ << ":\n";
  321. FormatCodeBlock(block_id);
  322. }
  323. out_ << "}\n";
  324. } else {
  325. out_ << ";\n";
  326. }
  327. }
  328. auto FormatCodeBlock(SemanticsNodeBlockId block_id) -> void {
  329. if (!block_id.is_valid()) {
  330. return;
  331. }
  332. for (const SemanticsNodeId node_id : semantics_ir_.GetNodeBlock(block_id)) {
  333. FormatInstruction(node_id);
  334. }
  335. }
  336. auto FormatInstruction(SemanticsNodeId node_id) -> void {
  337. if (!node_id.is_valid()) {
  338. out_ << " " << SemanticsNodeKind::Invalid.ir_name() << "\n";
  339. return;
  340. }
  341. FormatInstruction(node_id, semantics_ir_.GetNode(node_id));
  342. }
  343. auto FormatInstruction(SemanticsNodeId node_id, SemanticsNode node) -> void {
  344. switch (node.kind()) {
  345. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  346. case SemanticsNodeKind::Name: \
  347. FormatInstruction<SemanticsNode::Name>(node_id, node); \
  348. break;
  349. #include "toolchain/semantics/semantics_node_kind.def"
  350. }
  351. }
  352. template <typename Kind>
  353. auto FormatInstruction(SemanticsNodeId node_id, SemanticsNode node) -> void {
  354. out_ << " ";
  355. FormatInstructionLHS(node_id, node);
  356. out_ << node.kind().ir_name();
  357. FormatInstructionRHS<Kind>(node);
  358. out_ << "\n";
  359. }
  360. auto FormatInstructionLHS(SemanticsNodeId node_id, SemanticsNode node)
  361. -> void {
  362. switch (node.kind().value_kind()) {
  363. case SemanticsNodeValueKind::Typed:
  364. FormatNodeName(node_id);
  365. out_ << ": ";
  366. FormatType(node.type_id());
  367. out_ << " = ";
  368. break;
  369. case SemanticsNodeValueKind::Untyped:
  370. FormatNodeName(node_id);
  371. out_ << " = ";
  372. break;
  373. case SemanticsNodeValueKind::None:
  374. break;
  375. }
  376. }
  377. template <typename Kind>
  378. auto FormatInstructionRHS(SemanticsNode node) -> void {
  379. // By default, an instruction has a comma-separated argument list.
  380. FormatArgs(Kind::Get(node));
  381. }
  382. // BindName is handled by the NodeNamer and doesn't appear in the output.
  383. // These nodes are currently used simply to give a name to another node, and
  384. // are never referenced themselves.
  385. // TODO: Include BindName nodes in the output if we start referring to them.
  386. template <>
  387. auto FormatInstruction<SemanticsNode::BindName>(SemanticsNodeId,
  388. SemanticsNode) -> void {}
  389. template <>
  390. auto FormatInstructionRHS<SemanticsNode::BlockArg>(SemanticsNode node)
  391. -> void {
  392. out_ << " ";
  393. FormatLabel(node.GetAsBlockArg());
  394. }
  395. template <>
  396. auto FormatInstruction<SemanticsNode::BranchIf>(SemanticsNodeId,
  397. SemanticsNode node) -> void {
  398. if (!in_terminator_sequence) {
  399. out_ << " ";
  400. }
  401. auto [label_id, cond_id] = node.GetAsBranchIf();
  402. out_ << "if ";
  403. FormatNodeName(cond_id);
  404. out_ << " " << SemanticsNodeKind::Branch.ir_name() << " ";
  405. FormatLabel(label_id);
  406. out_ << " else ";
  407. in_terminator_sequence = true;
  408. }
  409. template <>
  410. auto FormatInstruction<SemanticsNode::BranchWithArg>(SemanticsNodeId,
  411. SemanticsNode node)
  412. -> void {
  413. if (!in_terminator_sequence) {
  414. out_ << " ";
  415. }
  416. auto [label_id, arg_id] = node.GetAsBranchWithArg();
  417. out_ << SemanticsNodeKind::BranchWithArg.ir_name() << " ";
  418. FormatLabel(label_id);
  419. out_ << "(";
  420. FormatNodeName(arg_id);
  421. out_ << ")\n";
  422. in_terminator_sequence = false;
  423. }
  424. template <>
  425. auto FormatInstruction<SemanticsNode::Branch>(SemanticsNodeId,
  426. SemanticsNode node) -> void {
  427. if (!in_terminator_sequence) {
  428. out_ << " ";
  429. }
  430. out_ << SemanticsNodeKind::Branch.ir_name() << " ";
  431. FormatLabel(node.GetAsBranch());
  432. out_ << "\n";
  433. in_terminator_sequence = false;
  434. }
  435. template <>
  436. auto FormatInstructionRHS<SemanticsNode::Call>(SemanticsNode node) -> void {
  437. out_ << " ";
  438. auto [args_id, callee_id] = node.GetAsCall();
  439. FormatArg(callee_id);
  440. FormatArg(args_id);
  441. }
  442. template <>
  443. auto FormatInstructionRHS<SemanticsNode::CrossReference>(SemanticsNode node)
  444. -> void {
  445. // TODO: Figure out a way to make this meaningful. We'll need some way to
  446. // name cross-reference IRs, perhaps by the node ID of the import?
  447. auto [xref_id, node_id] = node.GetAsCrossReference();
  448. out_ << " " << xref_id << "." << node_id;
  449. }
  450. // StructTypeFields are formatted as part of their StructType.
  451. template <>
  452. auto FormatInstruction<SemanticsNode::StructTypeField>(SemanticsNodeId,
  453. SemanticsNode)
  454. -> void {}
  455. template <>
  456. auto FormatInstructionRHS<SemanticsNode::StructType>(SemanticsNode node)
  457. -> void {
  458. out_ << " {";
  459. llvm::ListSeparator sep;
  460. for (auto field_id : semantics_ir_.GetNodeBlock(node.GetAsStructType())) {
  461. out_ << sep << ".";
  462. auto [field_name_id, field_type_id] =
  463. semantics_ir_.GetNode(field_id).GetAsStructTypeField();
  464. FormatString(field_name_id);
  465. out_ << ": ";
  466. FormatType(field_type_id);
  467. }
  468. out_ << "}";
  469. }
  470. auto FormatArgs(SemanticsNode::NoArgs) -> void {}
  471. template <typename Arg1>
  472. auto FormatArgs(Arg1 arg) -> void {
  473. out_ << ' ';
  474. FormatArg(arg);
  475. }
  476. template <typename Arg1, typename Arg2>
  477. auto FormatArgs(std::pair<Arg1, Arg2> args) -> void {
  478. out_ << ' ';
  479. FormatArg(args.first);
  480. out_ << ",";
  481. FormatArgs(args.second);
  482. }
  483. auto FormatArg(SemanticsBoolValue v) -> void { out_ << v; }
  484. auto FormatArg(SemanticsBuiltinKind kind) -> void { out_ << kind.label(); }
  485. auto FormatArg(SemanticsFunctionId id) -> void { FormatFunctionName(id); }
  486. auto FormatArg(SemanticsIntegerLiteralId id) -> void {
  487. out_ << semantics_ir_.GetIntegerLiteral(id);
  488. }
  489. auto FormatArg(SemanticsMemberIndex index) -> void { out_ << index; }
  490. // TODO: Should we be printing scopes inline, or should we have a separate
  491. // step to print them like we do for functions?
  492. auto FormatArg(SemanticsNameScopeId id) -> void {
  493. // Name scopes aren't kept in any particular order. Sort the entries before
  494. // we print them for stability and consistency.
  495. std::vector<std::pair<SemanticsNodeId, SemanticsStringId>> entries;
  496. for (auto [name_id, node_id] : semantics_ir_.GetNameScope(id)) {
  497. entries.push_back({node_id, name_id});
  498. }
  499. llvm::sort(entries,
  500. [](auto a, auto b) { return a.first.index < b.first.index; });
  501. out_ << '{';
  502. llvm::ListSeparator sep;
  503. for (auto [node_id, name_id] : entries) {
  504. out_ << sep << ".";
  505. FormatString(name_id);
  506. out_ << " = ";
  507. FormatNodeName(node_id);
  508. }
  509. out_ << '}';
  510. }
  511. auto FormatArg(SemanticsNodeId id) -> void { FormatNodeName(id); }
  512. auto FormatArg(SemanticsNodeBlockId id) -> void {
  513. out_ << '(';
  514. llvm::ListSeparator sep;
  515. for (auto node_id : semantics_ir_.GetNodeBlock(id)) {
  516. out_ << sep;
  517. FormatArg(node_id);
  518. }
  519. out_ << ')';
  520. }
  521. auto FormatArg(SemanticsRealLiteralId id) -> void {
  522. // TODO: Format with a `.` when the exponent is near zero.
  523. const auto& real = semantics_ir_.GetRealLiteral(id);
  524. out_ << real.mantissa << (real.is_decimal ? 'e' : 'p') << real.exponent;
  525. }
  526. auto FormatArg(SemanticsStringId id) -> void {
  527. out_ << '"';
  528. out_.write_escaped(semantics_ir_.GetString(id), /*UseHexEscapes=*/true);
  529. out_ << '"';
  530. }
  531. auto FormatArg(SemanticsTypeId id) -> void { FormatType(id); }
  532. auto FormatArg(SemanticsTypeBlockId id) -> void {
  533. out_ << '(';
  534. llvm::ListSeparator sep;
  535. for (auto type_id : semantics_ir_.GetTypeBlock(id)) {
  536. out_ << sep;
  537. FormatArg(type_id);
  538. }
  539. out_ << ')';
  540. }
  541. auto FormatNodeName(SemanticsNodeId id) -> void {
  542. out_ << node_namer_.GetNameFor(scope_, id);
  543. }
  544. auto FormatLabel(SemanticsNodeBlockId id) -> void {
  545. out_ << node_namer_.GetLabelFor(scope_, id);
  546. }
  547. auto FormatString(SemanticsStringId id) -> void {
  548. out_ << semantics_ir_.GetString(id);
  549. }
  550. auto FormatFunctionName(SemanticsFunctionId id) -> void {
  551. out_ << node_namer_.GetNameFor(id);
  552. }
  553. auto FormatType(SemanticsTypeId id) -> void {
  554. if (!id.is_valid()) {
  555. out_ << "invalid";
  556. } else {
  557. out_ << semantics_ir_.StringifyType(id, /*in_type_context=*/true);
  558. }
  559. }
  560. private:
  561. const SemanticsIR& semantics_ir_;
  562. llvm::raw_ostream& out_;
  563. NodeNamer node_namer_;
  564. NodeNamer::ScopeIndex scope_ = NodeNamer::ScopeIndex::None;
  565. bool in_terminator_sequence = false;
  566. };
  567. auto FormatSemanticsIR(const TokenizedBuffer& tokenized_buffer,
  568. const ParseTree& parse_tree,
  569. const SemanticsIR& semantics_ir, llvm::raw_ostream& out)
  570. -> void {
  571. SemanticsIRFormatter(tokenized_buffer, parse_tree, semantics_ir, out)
  572. .Format();
  573. }
  574. } // namespace Carbon