formatter.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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 "llvm/ADT/Sequence.h"
  6. #include "llvm/ADT/StringExtras.h"
  7. #include "llvm/ADT/StringMap.h"
  8. #include "llvm/Support/SaveAndRestore.h"
  9. #include "toolchain/lex/tokenized_buffer.h"
  10. #include "toolchain/parse/tree.h"
  11. namespace Carbon::SemIR {
  12. namespace {
  13. // Assigns names to nodes, blocks, and scopes in the Semantics IR.
  14. //
  15. // TODOs / future work ideas:
  16. // - Add a documentation file for the textual format and link to the
  17. // naming section here.
  18. // - Consider representing literals as just `literal` in the IR and using the
  19. // type to distinguish.
  20. class NodeNamer {
  21. public:
  22. // int32_t matches the input value size.
  23. // NOLINTNEXTLINE(performance-enum-size)
  24. enum class ScopeIndex : int32_t {
  25. None = -1,
  26. Package = 0,
  27. };
  28. static_assert(sizeof(ScopeIndex) == sizeof(FunctionId));
  29. NodeNamer(const Lex::TokenizedBuffer& tokenized_buffer,
  30. const Parse::Tree& parse_tree, const File& semantics_ir)
  31. : tokenized_buffer_(tokenized_buffer),
  32. parse_tree_(parse_tree),
  33. semantics_ir_(semantics_ir) {
  34. nodes.resize(semantics_ir.nodes_size());
  35. labels.resize(semantics_ir.node_blocks_size());
  36. scopes.resize(1 + semantics_ir.functions().size() +
  37. semantics_ir.classes().size());
  38. // Build the package scope.
  39. GetScopeInfo(ScopeIndex::Package).name =
  40. globals.AddNameUnchecked("package");
  41. CollectNamesInBlock(ScopeIndex::Package, semantics_ir.top_node_block_id());
  42. // Build each function scope.
  43. for (auto [i, fn] : llvm::enumerate(semantics_ir.functions().array_ref())) {
  44. auto fn_id = FunctionId(i);
  45. auto fn_scope = GetScopeFor(fn_id);
  46. // TODO: Provide a location for the function for use as a
  47. // disambiguator.
  48. auto fn_loc = Parse::Node::Invalid;
  49. GetScopeInfo(fn_scope).name = globals.AllocateName(
  50. *this, fn_loc,
  51. fn.name_id.is_valid() ? semantics_ir.strings().Get(fn.name_id).str()
  52. : "");
  53. CollectNamesInBlock(fn_scope, fn.param_refs_id);
  54. if (fn.return_slot_id.is_valid()) {
  55. nodes[fn.return_slot_id.index] = {
  56. fn_scope,
  57. GetScopeInfo(fn_scope).nodes.AllocateName(
  58. *this, semantics_ir.GetNode(fn.return_slot_id).parse_node(),
  59. "return")};
  60. }
  61. if (!fn.body_block_ids.empty()) {
  62. AddBlockLabel(fn_scope, fn.body_block_ids.front(), "entry", fn_loc);
  63. }
  64. for (auto block_id : fn.body_block_ids) {
  65. CollectNamesInBlock(fn_scope, block_id);
  66. }
  67. for (auto block_id : fn.body_block_ids) {
  68. AddBlockLabel(fn_scope, block_id);
  69. }
  70. }
  71. // Build each class scope.
  72. for (auto [i, class_info] :
  73. llvm::enumerate(semantics_ir.classes().array_ref())) {
  74. auto class_id = ClassId(i);
  75. auto class_scope = GetScopeFor(class_id);
  76. // TODO: Provide a location for the class for use as a
  77. // disambiguator.
  78. auto class_loc = Parse::Node::Invalid;
  79. GetScopeInfo(class_scope).name = globals.AllocateName(
  80. *this, class_loc,
  81. class_info.name_id.is_valid()
  82. ? semantics_ir.strings().Get(class_info.name_id).str()
  83. : "");
  84. AddBlockLabel(class_scope, class_info.body_block_id, "class", class_loc);
  85. CollectNamesInBlock(class_scope, class_info.body_block_id);
  86. }
  87. }
  88. // Returns the scope index corresponding to a function.
  89. auto GetScopeFor(FunctionId fn_id) -> ScopeIndex {
  90. return static_cast<ScopeIndex>(1 + fn_id.index);
  91. }
  92. // Returns the scope index corresponding to a class.
  93. auto GetScopeFor(ClassId class_id) -> ScopeIndex {
  94. return static_cast<ScopeIndex>(1 + semantics_ir_.functions().size() +
  95. class_id.index);
  96. }
  97. // Returns the IR name to use for a function.
  98. auto GetNameFor(FunctionId fn_id) -> llvm::StringRef {
  99. if (!fn_id.is_valid()) {
  100. return "invalid";
  101. }
  102. return GetScopeInfo(GetScopeFor(fn_id)).name.str();
  103. }
  104. // Returns the IR name to use for a class.
  105. auto GetNameFor(ClassId class_id) -> llvm::StringRef {
  106. if (!class_id.is_valid()) {
  107. return "invalid";
  108. }
  109. return GetScopeInfo(GetScopeFor(class_id)).name.str();
  110. }
  111. // Returns the IR name to use for a node, when referenced from a given scope.
  112. auto GetNameFor(ScopeIndex scope_idx, NodeId node_id) -> std::string {
  113. if (!node_id.is_valid()) {
  114. return "invalid";
  115. }
  116. // Check for a builtin.
  117. if (node_id.index < BuiltinKind::ValidCount) {
  118. return BuiltinKind::FromInt(node_id.index).label().str();
  119. }
  120. auto& [node_scope, node_name] = nodes[node_id.index];
  121. if (!node_name) {
  122. // This should not happen in valid IR.
  123. return "<unexpected noderef " + llvm::itostr(node_id.index) + ">";
  124. }
  125. if (node_scope == scope_idx) {
  126. return node_name.str().str();
  127. }
  128. return (GetScopeInfo(node_scope).name.str() + "." + node_name.str()).str();
  129. }
  130. // Returns the IR name to use for a label, when referenced from a given scope.
  131. auto GetLabelFor(ScopeIndex scope_idx, NodeBlockId block_id) -> std::string {
  132. if (!block_id.is_valid()) {
  133. return "!invalid";
  134. }
  135. auto& [label_scope, label_name] = labels[block_id.index];
  136. if (!label_name) {
  137. // This should not happen in valid IR.
  138. return "<unexpected nodeblockref " + llvm::itostr(block_id.index) + ">";
  139. }
  140. if (label_scope == scope_idx) {
  141. return label_name.str().str();
  142. }
  143. return (GetScopeInfo(label_scope).name.str() + "." + label_name.str())
  144. .str();
  145. }
  146. private:
  147. // A space in which unique names can be allocated.
  148. struct Namespace {
  149. // A result of a name lookup.
  150. struct NameResult;
  151. // A name in a namespace, which might be redirected to refer to another name
  152. // for disambiguation purposes.
  153. class Name {
  154. public:
  155. Name() : value_(nullptr) {}
  156. explicit Name(llvm::StringMapIterator<NameResult> it) : value_(&*it) {}
  157. explicit operator bool() const { return value_; }
  158. auto str() const -> llvm::StringRef {
  159. llvm::StringMapEntry<NameResult>* value = value_;
  160. CARBON_CHECK(value) << "cannot print a null name";
  161. while (value->second.ambiguous && value->second.fallback) {
  162. value = value->second.fallback.value_;
  163. }
  164. return value->first();
  165. }
  166. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  167. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  168. private:
  169. llvm::StringMapEntry<NameResult>* value_ = nullptr;
  170. };
  171. struct NameResult {
  172. bool ambiguous = false;
  173. Name fallback = Name();
  174. };
  175. llvm::StringRef prefix;
  176. llvm::StringMap<NameResult> allocated = {};
  177. int unnamed_count = 0;
  178. auto AddNameUnchecked(llvm::StringRef name) -> Name {
  179. return Name(allocated.insert({name, NameResult()}).first);
  180. }
  181. auto AllocateName(const NodeNamer& namer, Parse::Node node,
  182. std::string name = "") -> Name {
  183. // The best (shortest) name for this node so far, and the current name
  184. // for it.
  185. Name best;
  186. Name current;
  187. // Add `name` as a name for this entity.
  188. auto add_name = [&](bool mark_ambiguous = true) {
  189. auto [it, added] = allocated.insert({name, NameResult()});
  190. Name new_name = Name(it);
  191. if (!added) {
  192. if (mark_ambiguous) {
  193. // This name was allocated for a different node. Mark it as
  194. // ambiguous and keep looking for a name for this node.
  195. new_name.SetAmbiguous();
  196. }
  197. } else {
  198. if (!best) {
  199. best = new_name;
  200. } else {
  201. CARBON_CHECK(current);
  202. current.SetFallback(new_name);
  203. }
  204. current = new_name;
  205. }
  206. return added;
  207. };
  208. // All names start with the prefix.
  209. name.insert(0, prefix);
  210. // Use the given name if it's available and not just the prefix.
  211. if (name.size() > prefix.size()) {
  212. add_name();
  213. }
  214. // Append location information to try to disambiguate.
  215. if (node.is_valid()) {
  216. auto token = namer.parse_tree_.node_token(node);
  217. llvm::raw_string_ostream(name)
  218. << ".loc" << namer.tokenized_buffer_.GetLineNumber(token);
  219. add_name();
  220. llvm::raw_string_ostream(name)
  221. << "_" << namer.tokenized_buffer_.GetColumnNumber(token);
  222. add_name();
  223. }
  224. // Append numbers until we find an available name.
  225. name += ".";
  226. auto name_size_without_counter = name.size();
  227. for (int counter = 1;; ++counter) {
  228. name.resize(name_size_without_counter);
  229. llvm::raw_string_ostream(name) << counter;
  230. if (add_name(/*mark_ambiguous=*/false)) {
  231. return best;
  232. }
  233. }
  234. }
  235. };
  236. // A named scope that contains named entities.
  237. struct Scope {
  238. Namespace::Name name;
  239. Namespace nodes = {.prefix = "%"};
  240. Namespace labels = {.prefix = "!"};
  241. };
  242. auto GetScopeInfo(ScopeIndex scope_idx) -> Scope& {
  243. return scopes[static_cast<int>(scope_idx)];
  244. }
  245. auto AddBlockLabel(ScopeIndex scope_idx, NodeBlockId block_id,
  246. std::string name = "",
  247. Parse::Node parse_node = Parse::Node::Invalid) -> void {
  248. if (!block_id.is_valid() || labels[block_id.index].second) {
  249. return;
  250. }
  251. if (parse_node == Parse::Node::Invalid) {
  252. if (const auto& block = semantics_ir_.GetNodeBlock(block_id);
  253. !block.empty()) {
  254. parse_node = semantics_ir_.GetNode(block.front()).parse_node();
  255. }
  256. }
  257. labels[block_id.index] = {scope_idx,
  258. GetScopeInfo(scope_idx).labels.AllocateName(
  259. *this, parse_node, std::move(name))};
  260. }
  261. // Finds and adds a suitable block label for the given semantics node that
  262. // represents some kind of branch.
  263. auto AddBlockLabel(ScopeIndex scope_idx, NodeBlockId block_id, Node node)
  264. -> void {
  265. llvm::StringRef name;
  266. switch (parse_tree_.node_kind(node.parse_node())) {
  267. case Parse::NodeKind::IfExpressionIf:
  268. switch (node.kind()) {
  269. case BranchIf::Kind:
  270. name = "if.expr.then";
  271. break;
  272. case Branch::Kind:
  273. name = "if.expr.else";
  274. break;
  275. case BranchWithArg::Kind:
  276. name = "if.expr.result";
  277. break;
  278. default:
  279. break;
  280. }
  281. break;
  282. case Parse::NodeKind::IfCondition:
  283. switch (node.kind()) {
  284. case BranchIf::Kind:
  285. name = "if.then";
  286. break;
  287. case Branch::Kind:
  288. name = "if.else";
  289. break;
  290. default:
  291. break;
  292. }
  293. break;
  294. case Parse::NodeKind::IfStatement:
  295. name = "if.done";
  296. break;
  297. case Parse::NodeKind::ShortCircuitOperand: {
  298. bool is_rhs = node.Is<BranchIf>();
  299. bool is_and = tokenized_buffer_.GetKind(parse_tree_.node_token(
  300. node.parse_node())) == Lex::TokenKind::And;
  301. name = is_and ? (is_rhs ? "and.rhs" : "and.result")
  302. : (is_rhs ? "or.rhs" : "or.result");
  303. break;
  304. }
  305. case Parse::NodeKind::WhileConditionStart:
  306. name = "while.cond";
  307. break;
  308. case Parse::NodeKind::WhileCondition:
  309. switch (node.kind()) {
  310. case NodeKind::BranchIf:
  311. name = "while.body";
  312. break;
  313. case NodeKind::Branch:
  314. name = "while.done";
  315. break;
  316. default:
  317. break;
  318. }
  319. break;
  320. default:
  321. break;
  322. }
  323. AddBlockLabel(scope_idx, block_id, name.str(), node.parse_node());
  324. }
  325. auto CollectNamesInBlock(ScopeIndex scope_idx, NodeBlockId block_id) -> void {
  326. if (!block_id.is_valid()) {
  327. return;
  328. }
  329. Scope& scope = GetScopeInfo(scope_idx);
  330. // Use bound names where available. Otherwise, assign a backup name.
  331. for (auto node_id : semantics_ir_.GetNodeBlock(block_id)) {
  332. if (!node_id.is_valid()) {
  333. continue;
  334. }
  335. auto node = semantics_ir_.GetNode(node_id);
  336. auto add_node_name = [&](std::string name) {
  337. nodes[node_id.index] = {scope_idx, scope.nodes.AllocateName(
  338. *this, node.parse_node(), name)};
  339. };
  340. auto add_node_name_id = [&](StringId name_id) {
  341. if (name_id.is_valid()) {
  342. add_node_name(semantics_ir_.strings().Get(name_id).str());
  343. } else {
  344. add_node_name("");
  345. }
  346. };
  347. switch (node.kind()) {
  348. case Branch::Kind: {
  349. AddBlockLabel(scope_idx, node.As<Branch>().target_id, node);
  350. break;
  351. }
  352. case BranchIf::Kind: {
  353. AddBlockLabel(scope_idx, node.As<BranchIf>().target_id, node);
  354. break;
  355. }
  356. case BranchWithArg::Kind: {
  357. AddBlockLabel(scope_idx, node.As<BranchWithArg>().target_id, node);
  358. break;
  359. }
  360. case SpliceBlock::Kind: {
  361. CollectNamesInBlock(scope_idx, node.As<SpliceBlock>().block_id);
  362. break;
  363. }
  364. case BindName::Kind: {
  365. add_node_name_id(node.As<BindName>().name_id);
  366. continue;
  367. }
  368. case FunctionDeclaration::Kind: {
  369. add_node_name_id(semantics_ir_.functions()
  370. .Get(node.As<FunctionDeclaration>().function_id)
  371. .name_id);
  372. continue;
  373. }
  374. case ClassType::Kind: {
  375. add_node_name_id(semantics_ir_.classes()
  376. .Get(node.As<ClassType>().class_id)
  377. .name_id);
  378. continue;
  379. }
  380. case NameReference::Kind: {
  381. add_node_name(semantics_ir_.strings()
  382. .Get(node.As<NameReference>().name_id)
  383. .str() +
  384. ".ref");
  385. continue;
  386. }
  387. case Parameter::Kind: {
  388. add_node_name_id(node.As<Parameter>().name_id);
  389. continue;
  390. }
  391. case VarStorage::Kind: {
  392. // TODO: Eventually this name will be optional, and we'll want to
  393. // provide something like `var` as a default. However, that's not
  394. // possible right now so cannot be tested.
  395. add_node_name_id(node.As<VarStorage>().name_id);
  396. continue;
  397. }
  398. default: {
  399. break;
  400. }
  401. }
  402. // Sequentially number all remaining values.
  403. if (node.kind().value_kind() != NodeValueKind::None) {
  404. add_node_name("");
  405. }
  406. }
  407. }
  408. const Lex::TokenizedBuffer& tokenized_buffer_;
  409. const Parse::Tree& parse_tree_;
  410. const File& semantics_ir_;
  411. Namespace globals = {.prefix = "@"};
  412. std::vector<std::pair<ScopeIndex, Namespace::Name>> nodes;
  413. std::vector<std::pair<ScopeIndex, Namespace::Name>> labels;
  414. std::vector<Scope> scopes;
  415. };
  416. } // namespace
  417. // Formatter for printing textual Semantics IR.
  418. class Formatter {
  419. public:
  420. explicit Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  421. const Parse::Tree& parse_tree, const File& semantics_ir,
  422. llvm::raw_ostream& out)
  423. : semantics_ir_(semantics_ir),
  424. out_(out),
  425. node_namer_(tokenized_buffer, parse_tree, semantics_ir) {}
  426. auto Format() -> void {
  427. out_ << "file \"" << semantics_ir_.filename() << "\" {\n";
  428. // TODO: Include information from the package declaration, once we
  429. // fully support it.
  430. // TODO: Handle the case where there are multiple top-level node blocks.
  431. // For example, there may be branching in the initializer of a global or a
  432. // type expression.
  433. if (auto block_id = semantics_ir_.top_node_block_id();
  434. block_id.is_valid()) {
  435. llvm::SaveAndRestore package_scope(scope_,
  436. NodeNamer::ScopeIndex::Package);
  437. FormatCodeBlock(block_id);
  438. }
  439. out_ << "}\n";
  440. for (int i : llvm::seq(semantics_ir_.classes().size())) {
  441. FormatClass(ClassId(i));
  442. }
  443. for (int i : llvm::seq(semantics_ir_.functions().size())) {
  444. FormatFunction(FunctionId(i));
  445. }
  446. }
  447. auto FormatClass(ClassId id) -> void {
  448. const Class& class_info = semantics_ir_.classes().Get(id);
  449. out_ << "\nclass ";
  450. FormatClassName(id);
  451. llvm::SaveAndRestore class_scope(scope_, node_namer_.GetScopeFor(id));
  452. if (class_info.scope_id.is_valid()) {
  453. out_ << " {\n";
  454. FormatCodeBlock(class_info.body_block_id);
  455. out_ << "\n!members:";
  456. FormatNameScope(class_info.scope_id, "", "\n .");
  457. out_ << "\n}\n";
  458. } else {
  459. out_ << ";\n";
  460. }
  461. }
  462. auto FormatFunction(FunctionId id) -> void {
  463. const Function& fn = semantics_ir_.functions().Get(id);
  464. out_ << "\nfn ";
  465. FormatFunctionName(id);
  466. out_ << "(";
  467. llvm::SaveAndRestore function_scope(scope_, node_namer_.GetScopeFor(id));
  468. llvm::ListSeparator sep;
  469. for (const NodeId param_id : semantics_ir_.GetNodeBlock(fn.param_refs_id)) {
  470. out_ << sep;
  471. if (!param_id.is_valid()) {
  472. out_ << "invalid";
  473. continue;
  474. }
  475. FormatNodeName(param_id);
  476. out_ << ": ";
  477. FormatType(semantics_ir_.GetNode(param_id).type_id());
  478. }
  479. out_ << ")";
  480. if (fn.return_type_id.is_valid()) {
  481. out_ << " -> ";
  482. if (fn.return_slot_id.is_valid()) {
  483. FormatNodeName(fn.return_slot_id);
  484. out_ << ": ";
  485. }
  486. FormatType(fn.return_type_id);
  487. }
  488. if (!fn.body_block_ids.empty()) {
  489. out_ << " {";
  490. for (auto block_id : fn.body_block_ids) {
  491. out_ << "\n";
  492. FormatLabel(block_id);
  493. out_ << ":\n";
  494. FormatCodeBlock(block_id);
  495. }
  496. out_ << "}\n";
  497. } else {
  498. out_ << ";\n";
  499. }
  500. }
  501. auto FormatCodeBlock(NodeBlockId block_id) -> void {
  502. if (!block_id.is_valid()) {
  503. return;
  504. }
  505. for (const NodeId node_id : semantics_ir_.GetNodeBlock(block_id)) {
  506. FormatInstruction(node_id);
  507. }
  508. }
  509. auto FormatNameScope(NameScopeId id, llvm::StringRef separator,
  510. llvm::StringRef prefix) -> void {
  511. // Name scopes aren't kept in any particular order. Sort the entries before
  512. // we print them for stability and consistency.
  513. llvm::SmallVector<std::pair<NodeId, StringId>> entries;
  514. for (auto [name_id, node_id] : semantics_ir_.GetNameScope(id)) {
  515. entries.push_back({node_id, name_id});
  516. }
  517. llvm::sort(entries,
  518. [](auto a, auto b) { return a.first.index < b.first.index; });
  519. llvm::ListSeparator sep(separator);
  520. for (auto [node_id, name_id] : entries) {
  521. out_ << sep << prefix;
  522. FormatString(name_id);
  523. out_ << " = ";
  524. FormatNodeName(node_id);
  525. }
  526. }
  527. auto FormatInstruction(NodeId node_id) -> void {
  528. if (!node_id.is_valid()) {
  529. Indent();
  530. out_ << "invalid\n";
  531. return;
  532. }
  533. FormatInstruction(node_id, semantics_ir_.GetNode(node_id));
  534. }
  535. auto FormatInstruction(NodeId node_id, Node node) -> void {
  536. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  537. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  538. switch (node.kind()) {
  539. #define CARBON_SEM_IR_NODE_KIND(NodeT) \
  540. case NodeT::Kind: \
  541. FormatInstruction(node_id, node.As<NodeT>()); \
  542. break;
  543. #include "toolchain/sem_ir/node_kind.def"
  544. }
  545. }
  546. auto Indent() -> void { out_.indent(indent_); }
  547. template <typename NodeT>
  548. auto FormatInstruction(NodeId node_id, NodeT node) -> void {
  549. Indent();
  550. FormatInstructionLHS(node_id, node);
  551. out_ << NodeT::Kind.ir_name();
  552. FormatInstructionRHS(node);
  553. out_ << "\n";
  554. }
  555. auto FormatInstructionLHS(NodeId node_id, Node node) -> void {
  556. switch (node.kind().value_kind()) {
  557. case NodeValueKind::Typed:
  558. FormatNodeName(node_id);
  559. out_ << ": ";
  560. switch (GetExpressionCategory(semantics_ir_, node_id)) {
  561. case ExpressionCategory::NotExpression:
  562. case ExpressionCategory::Error:
  563. case ExpressionCategory::Value:
  564. case ExpressionCategory::Mixed:
  565. break;
  566. case ExpressionCategory::DurableReference:
  567. case ExpressionCategory::EphemeralReference:
  568. out_ << "ref ";
  569. break;
  570. case ExpressionCategory::Initializing:
  571. out_ << "init ";
  572. break;
  573. }
  574. FormatType(node.type_id());
  575. out_ << " = ";
  576. break;
  577. case NodeValueKind::None:
  578. break;
  579. }
  580. }
  581. template <typename NodeT>
  582. auto FormatInstructionRHS(NodeT node) -> void {
  583. // By default, an instruction has a comma-separated argument list.
  584. using Info = TypedNodeArgsInfo<NodeT>;
  585. if constexpr (Info::NumArgs == 2) {
  586. FormatArgs(Info::template Get<0>(node), Info::template Get<1>(node));
  587. } else if constexpr (Info::NumArgs == 1) {
  588. FormatArgs(Info::template Get<0>(node));
  589. } else {
  590. FormatArgs();
  591. }
  592. }
  593. auto FormatInstructionRHS(BlockArg node) -> void {
  594. out_ << " ";
  595. FormatLabel(node.block_id);
  596. }
  597. auto FormatInstruction(NodeId /*node_id*/, BranchIf node) -> void {
  598. if (!in_terminator_sequence_) {
  599. Indent();
  600. }
  601. out_ << "if ";
  602. FormatNodeName(node.cond_id);
  603. out_ << " " << Branch::Kind.ir_name() << " ";
  604. FormatLabel(node.target_id);
  605. out_ << " else ";
  606. in_terminator_sequence_ = true;
  607. }
  608. auto FormatInstruction(NodeId /*node_id*/, BranchWithArg node) -> void {
  609. if (!in_terminator_sequence_) {
  610. Indent();
  611. }
  612. out_ << BranchWithArg::Kind.ir_name() << " ";
  613. FormatLabel(node.target_id);
  614. out_ << "(";
  615. FormatNodeName(node.arg_id);
  616. out_ << ")\n";
  617. in_terminator_sequence_ = false;
  618. }
  619. auto FormatInstruction(NodeId /*node_id*/, Branch node) -> void {
  620. if (!in_terminator_sequence_) {
  621. Indent();
  622. }
  623. out_ << Branch::Kind.ir_name() << " ";
  624. FormatLabel(node.target_id);
  625. out_ << "\n";
  626. in_terminator_sequence_ = false;
  627. }
  628. auto FormatInstructionRHS(ArrayInit node) -> void {
  629. out_ << " ";
  630. FormatArg(node.tuple_id);
  631. llvm::ArrayRef<NodeId> inits_and_return_slot =
  632. semantics_ir_.GetNodeBlock(node.inits_and_return_slot_id);
  633. auto inits = inits_and_return_slot.drop_back(1);
  634. auto return_slot_id = inits_and_return_slot.back();
  635. out_ << ", (";
  636. llvm::ListSeparator sep;
  637. for (auto node_id : inits) {
  638. out_ << sep;
  639. FormatArg(node_id);
  640. }
  641. out_ << ')';
  642. FormatReturnSlot(return_slot_id);
  643. }
  644. auto FormatInstructionRHS(Call node) -> void {
  645. out_ << " ";
  646. FormatArg(node.callee_id);
  647. llvm::ArrayRef<NodeId> args = semantics_ir_.GetNodeBlock(node.args_id);
  648. bool has_return_slot =
  649. GetInitializingRepresentation(semantics_ir_, node.type_id)
  650. .has_return_slot();
  651. NodeId return_slot_id = NodeId::Invalid;
  652. if (has_return_slot) {
  653. return_slot_id = args.back();
  654. args = args.drop_back();
  655. }
  656. llvm::ListSeparator sep;
  657. out_ << '(';
  658. for (auto node_id : args) {
  659. out_ << sep;
  660. FormatArg(node_id);
  661. }
  662. out_ << ')';
  663. if (has_return_slot) {
  664. FormatReturnSlot(return_slot_id);
  665. }
  666. }
  667. auto FormatInstructionRHS(InitializeFrom node) -> void {
  668. FormatArgs(node.src_id);
  669. FormatReturnSlot(node.dest_id);
  670. }
  671. auto FormatInstructionRHS(CrossReference node) -> void {
  672. // TODO: Figure out a way to make this meaningful. We'll need some way to
  673. // name cross-reference IRs, perhaps by the node ID of the import?
  674. out_ << " " << node.ir_id << "." << node.node_id;
  675. }
  676. auto FormatInstructionRHS(SpliceBlock node) -> void {
  677. FormatArgs(node.result_id);
  678. out_ << " {";
  679. if (!semantics_ir_.GetNodeBlock(node.block_id).empty()) {
  680. out_ << "\n";
  681. indent_ += 2;
  682. FormatCodeBlock(node.block_id);
  683. indent_ -= 2;
  684. Indent();
  685. }
  686. out_ << "}";
  687. }
  688. // StructTypeFields are formatted as part of their StructType.
  689. auto FormatInstruction(NodeId /*node_id*/, StructTypeField /*node*/) -> void {
  690. }
  691. auto FormatInstructionRHS(StructType node) -> void {
  692. out_ << " {";
  693. llvm::ListSeparator sep;
  694. for (auto field_id : semantics_ir_.GetNodeBlock(node.fields_id)) {
  695. out_ << sep << ".";
  696. auto field = semantics_ir_.GetNodeAs<StructTypeField>(field_id);
  697. FormatString(field.name_id);
  698. out_ << ": ";
  699. FormatType(field.field_type_id);
  700. }
  701. out_ << "}";
  702. }
  703. auto FormatArgs() -> void {}
  704. template <typename... Args>
  705. auto FormatArgs(Args... args) -> void {
  706. out_ << ' ';
  707. llvm::ListSeparator sep;
  708. ((out_ << sep, FormatArg(args)), ...);
  709. }
  710. auto FormatArg(BoolValue v) -> void { out_ << v; }
  711. auto FormatArg(BuiltinKind kind) -> void { out_ << kind.label(); }
  712. auto FormatArg(FunctionId id) -> void { FormatFunctionName(id); }
  713. auto FormatArg(ClassId id) -> void { FormatClassName(id); }
  714. auto FormatArg(IntegerId id) -> void {
  715. semantics_ir_.integers().Get(id).print(out_, /*isSigned=*/false);
  716. }
  717. auto FormatArg(MemberIndex index) -> void { out_ << index; }
  718. auto FormatArg(NameScopeId id) -> void {
  719. out_ << '{';
  720. FormatNameScope(id, ", ", ".");
  721. out_ << '}';
  722. }
  723. auto FormatArg(NodeId id) -> void { FormatNodeName(id); }
  724. auto FormatArg(NodeBlockId id) -> void {
  725. out_ << '(';
  726. llvm::ListSeparator sep;
  727. for (auto node_id : semantics_ir_.GetNodeBlock(id)) {
  728. out_ << sep;
  729. FormatArg(node_id);
  730. }
  731. out_ << ')';
  732. }
  733. auto FormatArg(RealId id) -> void {
  734. // TODO: Format with a `.` when the exponent is near zero.
  735. const auto& real = semantics_ir_.reals().Get(id);
  736. real.mantissa.print(out_, /*isSigned=*/false);
  737. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  738. }
  739. auto FormatArg(StringId id) -> void {
  740. out_ << '"';
  741. out_.write_escaped(semantics_ir_.strings().Get(id), /*UseHexEscapes=*/true);
  742. out_ << '"';
  743. }
  744. auto FormatArg(TypeId id) -> void { FormatType(id); }
  745. auto FormatArg(TypeBlockId id) -> void {
  746. out_ << '(';
  747. llvm::ListSeparator sep;
  748. for (auto type_id : semantics_ir_.GetTypeBlock(id)) {
  749. out_ << sep;
  750. FormatArg(type_id);
  751. }
  752. out_ << ')';
  753. }
  754. auto FormatReturnSlot(NodeId dest_id) -> void {
  755. out_ << " to ";
  756. FormatArg(dest_id);
  757. }
  758. auto FormatNodeName(NodeId id) -> void {
  759. out_ << node_namer_.GetNameFor(scope_, id);
  760. }
  761. auto FormatLabel(NodeBlockId id) -> void {
  762. out_ << node_namer_.GetLabelFor(scope_, id);
  763. }
  764. auto FormatString(StringId id) -> void {
  765. out_ << semantics_ir_.strings().Get(id);
  766. }
  767. auto FormatFunctionName(FunctionId id) -> void {
  768. out_ << node_namer_.GetNameFor(id);
  769. }
  770. auto FormatClassName(ClassId id) -> void {
  771. out_ << node_namer_.GetNameFor(id);
  772. }
  773. auto FormatType(TypeId id) -> void {
  774. if (!id.is_valid()) {
  775. out_ << "invalid";
  776. } else {
  777. out_ << semantics_ir_.StringifyType(id, /*in_type_context=*/true);
  778. }
  779. }
  780. private:
  781. const File& semantics_ir_;
  782. llvm::raw_ostream& out_;
  783. NodeNamer node_namer_;
  784. NodeNamer::ScopeIndex scope_ = NodeNamer::ScopeIndex::None;
  785. bool in_terminator_sequence_ = false;
  786. int indent_ = 2;
  787. };
  788. auto FormatFile(const Lex::TokenizedBuffer& tokenized_buffer,
  789. const Parse::Tree& parse_tree, const File& semantics_ir,
  790. llvm::raw_ostream& out) -> void {
  791. Formatter(tokenized_buffer, parse_tree, semantics_ir, out).Format();
  792. }
  793. } // namespace Carbon::SemIR