formatter.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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 <string>
  6. #include <utility>
  7. #include "common/ostream.h"
  8. #include "llvm/ADT/Sequence.h"
  9. #include "llvm/ADT/StringExtras.h"
  10. #include "llvm/Support/SaveAndRestore.h"
  11. #include "toolchain/base/kind_switch.h"
  12. #include "toolchain/base/shared_value_stores.h"
  13. #include "toolchain/lex/tokenized_buffer.h"
  14. #include "toolchain/parse/tree.h"
  15. #include "toolchain/sem_ir/builtin_function_kind.h"
  16. #include "toolchain/sem_ir/constant.h"
  17. #include "toolchain/sem_ir/entity_with_params_base.h"
  18. #include "toolchain/sem_ir/expr_info.h"
  19. #include "toolchain/sem_ir/function.h"
  20. #include "toolchain/sem_ir/ids.h"
  21. #include "toolchain/sem_ir/name_scope.h"
  22. #include "toolchain/sem_ir/typed_insts.h"
  23. // TODO: Consider addressing recursion here, although it's not critical because
  24. // the formatter isn't required to work on arbitrary code. Still, it may help
  25. // in the future to debug complex code.
  26. // NOLINTBEGIN(misc-no-recursion)
  27. namespace Carbon::SemIR {
  28. Formatter::Formatter(const File* sem_ir,
  29. ShouldFormatEntityFn should_format_entity)
  30. : sem_ir_(sem_ir),
  31. inst_namer_(sem_ir_),
  32. should_format_entity_(should_format_entity) {
  33. // Create the first chunk and assign it to all instructions that don't have
  34. // a chunk of their own.
  35. auto first_chunk = AddChunkNoFlush(true);
  36. tentative_inst_chunks_.resize(sem_ir_->insts().size(), first_chunk);
  37. }
  38. auto Formatter::Format() -> void {
  39. out_ << "--- " << sem_ir_->filename() << "\n\n";
  40. FormatScopeIfUsed(InstNamer::ScopeId::Constants,
  41. sem_ir_->constants().array_ref());
  42. FormatScopeIfUsed(InstNamer::ScopeId::ImportRefs,
  43. sem_ir_->inst_blocks().Get(InstBlockId::ImportRefs));
  44. out_ << inst_namer_.GetScopeName(InstNamer::ScopeId::File) << " ";
  45. OpenBrace();
  46. // TODO: Handle the case where there are multiple top-level instruction
  47. // blocks. For example, there may be branching in the initializer of a
  48. // global or a type expression.
  49. if (auto block_id = sem_ir_->top_inst_block_id(); block_id.has_value()) {
  50. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::File);
  51. FormatCodeBlock(block_id);
  52. }
  53. CloseBrace();
  54. out_ << '\n';
  55. for (auto [id, _] : sem_ir_->interfaces().enumerate()) {
  56. FormatInterface(id);
  57. }
  58. for (auto [id, _] : sem_ir_->associated_constants().enumerate()) {
  59. FormatAssociatedConstant(id);
  60. }
  61. for (auto [id, _] : sem_ir_->impls().enumerate()) {
  62. FormatImpl(id);
  63. }
  64. for (auto [id, _] : sem_ir_->classes().enumerate()) {
  65. FormatClass(id);
  66. }
  67. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  68. FormatFunction(id);
  69. }
  70. for (auto [id, _] : sem_ir_->specifics().enumerate()) {
  71. FormatSpecific(id);
  72. }
  73. // End-of-file newline.
  74. out_ << "\n";
  75. }
  76. auto Formatter::Write(llvm::raw_ostream& out) -> void {
  77. FlushChunk();
  78. for (const auto& chunk : output_chunks_) {
  79. if (chunk.include_in_output) {
  80. out << chunk.chunk;
  81. }
  82. }
  83. }
  84. auto Formatter::FlushChunk() -> void {
  85. CARBON_CHECK(output_chunks_.back().chunk.empty());
  86. output_chunks_.back().chunk = std::move(buffer_);
  87. buffer_.clear();
  88. }
  89. auto Formatter::AddChunkNoFlush(bool include_in_output) -> size_t {
  90. CARBON_CHECK(buffer_.empty());
  91. output_chunks_.push_back({.include_in_output = include_in_output});
  92. return output_chunks_.size() - 1;
  93. }
  94. auto Formatter::AddChunk(bool include_in_output) -> size_t {
  95. FlushChunk();
  96. return AddChunkNoFlush(include_in_output);
  97. }
  98. auto Formatter::IncludeChunkInOutput(size_t chunk) -> void {
  99. if (chunk == output_chunks_.size() - 1) {
  100. return;
  101. }
  102. if (auto& current_chunk = output_chunks_.back();
  103. !current_chunk.include_in_output) {
  104. current_chunk.dependencies.push_back(chunk);
  105. return;
  106. }
  107. llvm::SmallVector<size_t> to_add = {chunk};
  108. while (!to_add.empty()) {
  109. auto& chunk = output_chunks_[to_add.pop_back_val()];
  110. if (chunk.include_in_output) {
  111. continue;
  112. }
  113. chunk.include_in_output = true;
  114. to_add.append(chunk.dependencies);
  115. chunk.dependencies.clear();
  116. }
  117. }
  118. auto Formatter::ShouldFormatEntity(InstId decl_id) -> bool {
  119. if (!decl_id.has_value()) {
  120. return true;
  121. }
  122. return should_format_entity_(decl_id);
  123. }
  124. auto Formatter::ShouldFormatEntity(const EntityWithParamsBase& entity) -> bool {
  125. return ShouldFormatEntity(entity.latest_decl_id());
  126. }
  127. auto Formatter::OpenBrace() -> void {
  128. // Put the constant value of an instruction before any braced block, rather
  129. // than at the end.
  130. FormatPendingConstantValue(AddSpace::After);
  131. // Put the imported-from library name before the definition of the entity.
  132. FormatPendingImportedFrom(AddSpace::After);
  133. out_ << '{';
  134. indent_ += 2;
  135. after_open_brace_ = true;
  136. }
  137. auto Formatter::CloseBrace() -> void {
  138. indent_ -= 2;
  139. if (!after_open_brace_) {
  140. Indent();
  141. }
  142. out_ << '}';
  143. after_open_brace_ = false;
  144. }
  145. auto Formatter::Semicolon() -> void {
  146. FormatPendingImportedFrom(AddSpace::Before);
  147. out_ << ';';
  148. }
  149. auto Formatter::Indent(int offset) -> void {
  150. if (after_open_brace_) {
  151. out_ << '\n';
  152. after_open_brace_ = false;
  153. }
  154. out_.indent(indent_ + offset);
  155. }
  156. auto Formatter::IndentLabel() -> void {
  157. CARBON_CHECK(indent_ >= 2);
  158. if (!after_open_brace_) {
  159. out_ << '\n';
  160. }
  161. Indent(-2);
  162. }
  163. auto Formatter::FormatScopeIfUsed(InstNamer::ScopeId scope_id,
  164. llvm::ArrayRef<InstId> block) -> void {
  165. if (block.empty()) {
  166. return;
  167. }
  168. llvm::SaveAndRestore scope(scope_, scope_id);
  169. // Note, we don't use OpenBrace() / CloseBrace() here because we always want
  170. // a newline to avoid misformatting if the first instruction is omitted.
  171. out_ << inst_namer_.GetScopeName(scope_id) << " {\n";
  172. indent_ += 2;
  173. for (const InstId inst_id : block) {
  174. TentativeOutputScope scope(*this);
  175. tentative_inst_chunks_[inst_id.index] = scope.index;
  176. FormatInst(inst_id);
  177. }
  178. out_ << "}\n\n";
  179. indent_ -= 2;
  180. }
  181. auto Formatter::FormatClass(ClassId id) -> void {
  182. const Class& class_info = sem_ir_->classes().Get(id);
  183. if (!ShouldFormatEntity(class_info)) {
  184. return;
  185. }
  186. FormatEntityStart("class", class_info, id);
  187. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  188. if (class_info.scope_id.has_value()) {
  189. out_ << ' ';
  190. OpenBrace();
  191. FormatCodeBlock(class_info.body_block_id);
  192. Indent();
  193. out_ << "complete_type_witness = ";
  194. FormatName(class_info.complete_type_witness_id);
  195. out_ << "\n";
  196. FormatNameScope(class_info.scope_id, "!members:\n");
  197. CloseBrace();
  198. } else {
  199. Semicolon();
  200. }
  201. out_ << '\n';
  202. FormatEntityEnd(class_info.generic_id);
  203. }
  204. auto Formatter::FormatInterface(InterfaceId id) -> void {
  205. const Interface& interface_info = sem_ir_->interfaces().Get(id);
  206. if (!ShouldFormatEntity(interface_info)) {
  207. return;
  208. }
  209. FormatEntityStart("interface", interface_info, id);
  210. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  211. if (interface_info.scope_id.has_value()) {
  212. out_ << ' ';
  213. OpenBrace();
  214. FormatCodeBlock(interface_info.body_block_id);
  215. // Always include the !members label because we always list the witness in
  216. // this section.
  217. IndentLabel();
  218. out_ << "!members:\n";
  219. FormatNameScope(interface_info.scope_id);
  220. Indent();
  221. out_ << "witness = ";
  222. FormatArg(interface_info.associated_entities_id);
  223. out_ << "\n";
  224. CloseBrace();
  225. } else {
  226. Semicolon();
  227. }
  228. out_ << '\n';
  229. FormatEntityEnd(interface_info.generic_id);
  230. }
  231. auto Formatter::FormatAssociatedConstant(AssociatedConstantId id) -> void {
  232. const AssociatedConstant& assoc_const =
  233. sem_ir_->associated_constants().Get(id);
  234. if (!ShouldFormatEntity(assoc_const.decl_id)) {
  235. return;
  236. }
  237. FormatEntityStart("assoc_const", assoc_const.decl_id, assoc_const.generic_id,
  238. id);
  239. llvm::SaveAndRestore assoc_const_scope(scope_, inst_namer_.GetScopeFor(id));
  240. out_ << " ";
  241. FormatName(assoc_const.name_id);
  242. out_ << ":! ";
  243. FormatTypeOfInst(assoc_const.decl_id);
  244. if (assoc_const.default_value_id.has_value()) {
  245. out_ << " = ";
  246. FormatArg(assoc_const.default_value_id);
  247. }
  248. out_ << ";\n";
  249. FormatEntityEnd(assoc_const.generic_id);
  250. }
  251. auto Formatter::FormatImpl(ImplId id) -> void {
  252. const Impl& impl_info = sem_ir_->impls().Get(id);
  253. if (!ShouldFormatEntity(impl_info)) {
  254. return;
  255. }
  256. FormatEntityStart("impl", impl_info, id);
  257. llvm::SaveAndRestore impl_scope(scope_, inst_namer_.GetScopeFor(id));
  258. out_ << ": ";
  259. FormatName(impl_info.self_id);
  260. out_ << " as ";
  261. FormatName(impl_info.constraint_id);
  262. if (impl_info.is_complete()) {
  263. out_ << ' ';
  264. OpenBrace();
  265. FormatCodeBlock(impl_info.body_block_id);
  266. // Print the !members label even if the name scope is empty because we
  267. // always list the witness in this section.
  268. IndentLabel();
  269. out_ << "!members:\n";
  270. if (impl_info.scope_id.has_value()) {
  271. FormatNameScope(impl_info.scope_id);
  272. }
  273. Indent();
  274. out_ << "witness = ";
  275. FormatArg(impl_info.witness_id);
  276. out_ << "\n";
  277. CloseBrace();
  278. } else {
  279. Semicolon();
  280. }
  281. out_ << '\n';
  282. FormatEntityEnd(impl_info.generic_id);
  283. }
  284. auto Formatter::FormatFunction(FunctionId id) -> void {
  285. const Function& fn = sem_ir_->functions().Get(id);
  286. if (!ShouldFormatEntity(fn)) {
  287. return;
  288. }
  289. std::string function_start;
  290. switch (fn.virtual_modifier) {
  291. case FunctionFields::VirtualModifier::Virtual:
  292. function_start += "virtual ";
  293. break;
  294. case FunctionFields::VirtualModifier::Abstract:
  295. function_start += "abstract ";
  296. break;
  297. case FunctionFields::VirtualModifier::Impl:
  298. function_start += "impl ";
  299. break;
  300. case FunctionFields::VirtualModifier::None:
  301. break;
  302. }
  303. if (fn.is_extern) {
  304. function_start += "extern ";
  305. }
  306. function_start += "fn";
  307. FormatEntityStart(function_start, fn, id);
  308. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  309. auto return_type_info = ReturnTypeInfo::ForFunction(*sem_ir_, fn);
  310. FormatParamList(fn.call_params_id, return_type_info.is_valid() &&
  311. return_type_info.has_return_slot());
  312. if (fn.builtin_function_kind != BuiltinFunctionKind::None) {
  313. out_ << " = \""
  314. << FormatEscaped(fn.builtin_function_kind.name(),
  315. /*use_hex_escapes=*/true)
  316. << "\"";
  317. }
  318. if (!fn.body_block_ids.empty()) {
  319. out_ << ' ';
  320. OpenBrace();
  321. for (auto block_id : fn.body_block_ids) {
  322. IndentLabel();
  323. FormatLabel(block_id);
  324. out_ << ":\n";
  325. FormatCodeBlock(block_id);
  326. }
  327. CloseBrace();
  328. } else {
  329. Semicolon();
  330. }
  331. out_ << '\n';
  332. FormatEntityEnd(fn.generic_id);
  333. }
  334. auto Formatter::FormatSpecificRegion(const Generic& generic,
  335. const Specific& specific,
  336. GenericInstIndex::Region region,
  337. llvm::StringRef region_name) -> void {
  338. if (!specific.GetValueBlock(region).has_value()) {
  339. return;
  340. }
  341. if (!region_name.empty()) {
  342. IndentLabel();
  343. out_ << "!" << region_name << ":\n";
  344. }
  345. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  346. sem_ir_->inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  347. sem_ir_->inst_blocks().GetOrEmpty(specific.GetValueBlock(region)))) {
  348. Indent();
  349. if (generic_inst_id) {
  350. FormatName(*generic_inst_id);
  351. } else {
  352. out_ << "<missing>";
  353. }
  354. out_ << " => ";
  355. if (specific_inst_id) {
  356. FormatName(*specific_inst_id);
  357. } else {
  358. out_ << "<missing>";
  359. }
  360. out_ << "\n";
  361. }
  362. }
  363. auto Formatter::FormatSpecific(SpecificId id) -> void {
  364. const auto& specific = sem_ir_->specifics().Get(id);
  365. const auto& generic = sem_ir_->generics().Get(specific.generic_id);
  366. if (!should_format_entity_(generic.decl_id)) {
  367. // Omit specifics if we also omitted the generic.
  368. return;
  369. }
  370. llvm::SaveAndRestore generic_scope(
  371. scope_, inst_namer_.GetScopeFor(specific.generic_id));
  372. out_ << "\n";
  373. out_ << "specific ";
  374. FormatName(id);
  375. out_ << " ";
  376. OpenBrace();
  377. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Declaration,
  378. "");
  379. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Definition,
  380. "definition");
  381. CloseBrace();
  382. out_ << "\n";
  383. }
  384. auto Formatter::FormatGenericStart(llvm::StringRef entity_kind,
  385. GenericId generic_id) -> void {
  386. const auto& generic = sem_ir_->generics().Get(generic_id);
  387. out_ << "\n";
  388. Indent();
  389. out_ << "generic " << entity_kind << " ";
  390. FormatName(generic_id);
  391. llvm::SaveAndRestore generic_scope(scope_,
  392. inst_namer_.GetScopeFor(generic_id));
  393. FormatParamList(generic.bindings_id);
  394. out_ << " ";
  395. OpenBrace();
  396. FormatCodeBlock(generic.decl_block_id);
  397. if (generic.definition_block_id.has_value()) {
  398. IndentLabel();
  399. out_ << "!definition:\n";
  400. FormatCodeBlock(generic.definition_block_id);
  401. }
  402. }
  403. auto Formatter::FormatEntityEnd(GenericId generic_id) -> void {
  404. if (generic_id.has_value()) {
  405. CloseBrace();
  406. out_ << '\n';
  407. }
  408. }
  409. auto Formatter::FormatParamList(InstBlockId params_id, bool has_return_slot)
  410. -> void {
  411. if (!params_id.has_value()) {
  412. // TODO: This happens for imported functions, for which we don't currently
  413. // import the call parameters list.
  414. return;
  415. }
  416. llvm::StringLiteral close = ")";
  417. out_ << "(";
  418. llvm::ListSeparator sep;
  419. for (InstId param_id : sem_ir_->inst_blocks().Get(params_id)) {
  420. auto is_out_param = sem_ir_->insts().Is<OutParam>(param_id);
  421. if (is_out_param) {
  422. // TODO: An input parameter following an output parameter is formatted a
  423. // bit strangely. For example, alternating input and output parameters
  424. // produces:
  425. //
  426. // fn @F(%in1: %t) -> %out1: %t, %in2: %t -> %out2: %t
  427. //
  428. // This doesn't actually happen right now, though.
  429. out_ << std::exchange(close, llvm::StringLiteral(""));
  430. out_ << " -> ";
  431. } else {
  432. out_ << sep;
  433. }
  434. if (!param_id.has_value()) {
  435. out_ << "invalid";
  436. continue;
  437. }
  438. // Don't include the name of the return slot parameter if the function
  439. // doesn't have a return slot; the name won't be used for anything in that
  440. // case.
  441. // TODO: Should the call parameter even exist in that case? There isn't a
  442. // corresponding argument in a `call` instruction.
  443. if (!is_out_param || has_return_slot) {
  444. FormatName(param_id);
  445. out_ << ": ";
  446. }
  447. FormatTypeOfInst(param_id);
  448. }
  449. out_ << close;
  450. }
  451. auto Formatter::FormatCodeBlock(InstBlockId block_id) -> void {
  452. for (const InstId inst_id : sem_ir_->inst_blocks().GetOrEmpty(block_id)) {
  453. FormatInst(inst_id);
  454. }
  455. }
  456. auto Formatter::FormatTrailingBlock(InstBlockId block_id) -> void {
  457. out_ << ' ';
  458. OpenBrace();
  459. FormatCodeBlock(block_id);
  460. CloseBrace();
  461. }
  462. auto Formatter::FormatNameScope(NameScopeId id, llvm::StringRef label) -> void {
  463. const auto& scope = sem_ir_->name_scopes().Get(id);
  464. if (scope.entries().empty() && scope.extended_scopes().empty() &&
  465. scope.import_ir_scopes().empty() && !scope.is_cpp_scope() &&
  466. !scope.has_error()) {
  467. // Name scope is empty.
  468. return;
  469. }
  470. if (!label.empty()) {
  471. IndentLabel();
  472. out_ << label;
  473. }
  474. for (auto [name_id, result] : scope.entries()) {
  475. Indent();
  476. out_ << ".";
  477. FormatName(name_id);
  478. switch (result.access_kind()) {
  479. case AccessKind::Public:
  480. break;
  481. case AccessKind::Protected:
  482. out_ << " [protected]";
  483. break;
  484. case AccessKind::Private:
  485. out_ << " [private]";
  486. break;
  487. }
  488. out_ << " = ";
  489. if (result.is_poisoned()) {
  490. out_ << "<poisoned>";
  491. } else {
  492. FormatName(result.is_found() ? result.target_inst_id() : InstId::None);
  493. }
  494. out_ << "\n";
  495. }
  496. for (auto extended_scope_id : scope.extended_scopes()) {
  497. Indent();
  498. out_ << "extend ";
  499. FormatName(extended_scope_id);
  500. out_ << "\n";
  501. }
  502. // This is used to cluster all "Core//prelude/..." imports, but not
  503. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  504. // add or remove an unused prelude file, but is intended to still show the
  505. // existence of indirect imports.
  506. bool has_prelude_components = false;
  507. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  508. auto label = GetImportIRLabel(import_ir_id);
  509. if (label.starts_with("Core//prelude/")) {
  510. if (has_prelude_components) {
  511. // Only print the existence once.
  512. continue;
  513. } else {
  514. has_prelude_components = true;
  515. label = "Core//prelude/...";
  516. }
  517. }
  518. Indent();
  519. out_ << "import " << label << "\n";
  520. }
  521. if (scope.is_cpp_scope()) {
  522. Indent();
  523. out_ << "import Cpp//...\n";
  524. }
  525. if (scope.has_error()) {
  526. Indent();
  527. out_ << "has_error\n";
  528. }
  529. }
  530. auto Formatter::FormatInst(InstId inst_id, Inst inst) -> void {
  531. CARBON_KIND_SWITCH(inst) {
  532. #define CARBON_SEM_IR_INST_KIND(InstT) \
  533. case CARBON_KIND(InstT typed_inst): { \
  534. FormatInst(inst_id, typed_inst); \
  535. break; \
  536. }
  537. #include "toolchain/sem_ir/inst_kind.def"
  538. }
  539. }
  540. auto Formatter::FormatInst(InstId inst_id, ImportRefUnloaded inst) -> void {
  541. Indent();
  542. FormatInstLhs(inst_id, inst);
  543. out_ << ImportRefUnloaded::Kind.ir_name();
  544. FormatInstRhs(inst);
  545. out_ << "\n";
  546. }
  547. auto Formatter::FormatInst(InstId inst_id) -> void {
  548. if (!inst_id.has_value()) {
  549. Indent();
  550. out_ << "none\n";
  551. return;
  552. }
  553. FormatInst(inst_id, sem_ir_->insts().Get(inst_id));
  554. }
  555. auto Formatter::FormatPendingImportedFrom(AddSpace space_where) -> void {
  556. if (pending_imported_from_.empty()) {
  557. return;
  558. }
  559. if (space_where == AddSpace::Before) {
  560. out_ << ' ';
  561. }
  562. out_ << "[from \"" << FormatEscaped(pending_imported_from_) << "\"]";
  563. if (space_where == AddSpace::After) {
  564. out_ << ' ';
  565. }
  566. pending_imported_from_ = llvm::StringRef();
  567. }
  568. auto Formatter::FormatPendingConstantValue(AddSpace space_where) -> void {
  569. if (pending_constant_value_ == ConstantId::NotConstant) {
  570. return;
  571. }
  572. if (space_where == AddSpace::Before) {
  573. out_ << ' ';
  574. }
  575. out_ << '[';
  576. if (pending_constant_value_.has_value()) {
  577. switch (sem_ir_->constant_values().GetDependence(pending_constant_value_)) {
  578. case ConstantDependence::None:
  579. out_ << "concrete";
  580. break;
  581. case ConstantDependence::PeriodSelf:
  582. out_ << "symbolic_self";
  583. break;
  584. // TODO: Consider renaming this. This will cause a lot of SemIR churn.
  585. case ConstantDependence::Checked:
  586. out_ << "symbolic";
  587. break;
  588. case ConstantDependence::Template:
  589. out_ << "template";
  590. break;
  591. }
  592. if (!pending_constant_value_is_self_) {
  593. out_ << " = ";
  594. FormatConstant(pending_constant_value_);
  595. }
  596. } else {
  597. out_ << pending_constant_value_;
  598. }
  599. out_ << ']';
  600. if (space_where == AddSpace::After) {
  601. out_ << ' ';
  602. }
  603. pending_constant_value_ = ConstantId::NotConstant;
  604. }
  605. auto Formatter::FormatInstLhs(InstId inst_id, Inst inst) -> void {
  606. switch (inst.kind().value_kind()) {
  607. case InstValueKind::Typed:
  608. FormatName(inst_id);
  609. out_ << ": ";
  610. switch (GetExprCategory(*sem_ir_, inst_id)) {
  611. case ExprCategory::NotExpr:
  612. case ExprCategory::Error:
  613. case ExprCategory::Value:
  614. case ExprCategory::Mixed:
  615. break;
  616. case ExprCategory::DurableRef:
  617. case ExprCategory::EphemeralRef:
  618. out_ << "ref ";
  619. break;
  620. case ExprCategory::Initializing:
  621. out_ << "init ";
  622. break;
  623. }
  624. FormatTypeOfInst(inst_id);
  625. out_ << " = ";
  626. break;
  627. case InstValueKind::None:
  628. break;
  629. }
  630. }
  631. auto Formatter::FormatInstLhs(InstId inst_id, ImportCppDecl /*inst*/) -> void {
  632. FormatName(inst_id);
  633. out_ << " = ";
  634. }
  635. auto Formatter::FormatInstLhs(InstId inst_id, ImportDecl /*inst*/) -> void {
  636. FormatName(inst_id);
  637. out_ << " = ";
  638. }
  639. auto Formatter::FormatInstLhs(InstId inst_id, ImportRefUnloaded /*inst*/)
  640. -> void {
  641. FormatName(inst_id);
  642. out_ << " = ";
  643. }
  644. auto Formatter::FormatInstLhs(InstId inst_id, ImplWitnessTable /*inst*/)
  645. -> void {
  646. FormatName(inst_id);
  647. out_ << " = ";
  648. }
  649. auto Formatter::FormatInstRhs(BindSymbolicName inst) -> void {
  650. // A BindSymbolicName with no value is a purely symbolic binding, such as
  651. // the `Self` in an interface. Don't print out `none` for the value.
  652. if (inst.value_id.has_value()) {
  653. FormatArgs(inst.entity_name_id, inst.value_id);
  654. } else {
  655. FormatArgs(inst.entity_name_id);
  656. }
  657. }
  658. auto Formatter::FormatInstRhs(BlockArg inst) -> void {
  659. out_ << " ";
  660. FormatLabel(inst.block_id);
  661. }
  662. auto Formatter::FormatInstRhs(Namespace inst) -> void {
  663. if (inst.import_id.has_value()) {
  664. FormatArgs(inst.import_id, inst.name_scope_id);
  665. } else {
  666. FormatArgs(inst.name_scope_id);
  667. }
  668. }
  669. auto Formatter::FormatInst(InstId /*inst_id*/, BranchIf inst) -> void {
  670. if (!in_terminator_sequence_) {
  671. Indent();
  672. }
  673. out_ << "if ";
  674. FormatName(inst.cond_id);
  675. out_ << " " << Branch::Kind.ir_name() << " ";
  676. FormatLabel(inst.target_id);
  677. out_ << " else ";
  678. in_terminator_sequence_ = true;
  679. }
  680. auto Formatter::FormatInst(InstId /*inst_id*/, BranchWithArg inst) -> void {
  681. if (!in_terminator_sequence_) {
  682. Indent();
  683. }
  684. out_ << BranchWithArg::Kind.ir_name() << " ";
  685. FormatLabel(inst.target_id);
  686. out_ << "(";
  687. FormatName(inst.arg_id);
  688. out_ << ")\n";
  689. in_terminator_sequence_ = false;
  690. }
  691. auto Formatter::FormatInst(InstId /*inst_id*/, Branch inst) -> void {
  692. if (!in_terminator_sequence_) {
  693. Indent();
  694. }
  695. out_ << Branch::Kind.ir_name() << " ";
  696. FormatLabel(inst.target_id);
  697. out_ << "\n";
  698. in_terminator_sequence_ = false;
  699. }
  700. auto Formatter::FormatInstRhs(Call inst) -> void {
  701. out_ << " ";
  702. FormatArg(inst.callee_id);
  703. if (!inst.args_id.has_value()) {
  704. out_ << "(<none>)";
  705. return;
  706. }
  707. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  708. auto return_info = ReturnTypeInfo::ForType(*sem_ir_, inst.type_id);
  709. if (!return_info.is_valid()) {
  710. out_ << "(<invalid return info>)";
  711. return;
  712. }
  713. bool has_return_slot = return_info.has_return_slot();
  714. InstId return_slot_arg_id = InstId::None;
  715. if (has_return_slot) {
  716. return_slot_arg_id = args.back();
  717. args = args.drop_back();
  718. }
  719. llvm::ListSeparator sep;
  720. out_ << '(';
  721. for (auto inst_id : args) {
  722. out_ << sep;
  723. FormatArg(inst_id);
  724. }
  725. out_ << ')';
  726. if (has_return_slot) {
  727. FormatReturnSlotArg(return_slot_arg_id);
  728. }
  729. }
  730. auto Formatter::FormatInstRhs(ArrayInit inst) -> void {
  731. FormatArgs(inst.inits_id);
  732. FormatReturnSlotArg(inst.dest_id);
  733. }
  734. auto Formatter::Formatter::FormatInstRhs(InitializeFrom inst) -> void {
  735. FormatArgs(inst.src_id);
  736. FormatReturnSlotArg(inst.dest_id);
  737. }
  738. auto Formatter::FormatInstRhs(ValueParam inst) -> void {
  739. FormatArgs(inst.index);
  740. // Omit pretty_name because it's an implementation detail of
  741. // pretty-printing.
  742. }
  743. auto Formatter::FormatInstRhs(RefParam inst) -> void {
  744. FormatArgs(inst.index);
  745. // Omit pretty_name because it's an implementation detail of
  746. // pretty-printing.
  747. }
  748. auto Formatter::FormatInstRhs(OutParam inst) -> void {
  749. FormatArgs(inst.index);
  750. // Omit pretty_name because it's an implementation detail of
  751. // pretty-printing.
  752. }
  753. auto Formatter::FormatInstRhs(ReturnExpr ret) -> void {
  754. FormatArgs(ret.expr_id);
  755. if (ret.dest_id.has_value()) {
  756. FormatReturnSlotArg(ret.dest_id);
  757. }
  758. }
  759. auto Formatter::FormatInstRhs(ReturnSlot inst) -> void {
  760. // Omit inst.type_inst_id because it's not semantically significant.
  761. FormatArgs(inst.storage_id);
  762. }
  763. auto Formatter::FormatInstRhs(ReturnSlotPattern /*inst*/) -> void {
  764. // No-op because type_id is the only semantically significant field,
  765. // and it's handled separately.
  766. }
  767. auto Formatter::FormatInstRhs(StructInit init) -> void {
  768. FormatArgs(init.elements_id);
  769. FormatReturnSlotArg(init.dest_id);
  770. }
  771. auto Formatter::FormatInstRhs(TupleInit init) -> void {
  772. FormatArgs(init.elements_id);
  773. FormatReturnSlotArg(init.dest_id);
  774. }
  775. auto Formatter::FormatInstRhs(FunctionDecl inst) -> void {
  776. FormatArgs(inst.function_id);
  777. llvm::SaveAndRestore class_scope(scope_,
  778. inst_namer_.GetScopeFor(inst.function_id));
  779. FormatTrailingBlock(
  780. sem_ir_->functions().Get(inst.function_id).pattern_block_id);
  781. FormatTrailingBlock(inst.decl_block_id);
  782. }
  783. auto Formatter::FormatInstRhs(ClassDecl inst) -> void {
  784. FormatArgs(inst.class_id);
  785. llvm::SaveAndRestore class_scope(scope_,
  786. inst_namer_.GetScopeFor(inst.class_id));
  787. FormatTrailingBlock(sem_ir_->classes().Get(inst.class_id).pattern_block_id);
  788. FormatTrailingBlock(inst.decl_block_id);
  789. }
  790. auto Formatter::FormatInstRhs(ImplDecl inst) -> void {
  791. FormatArgs(inst.impl_id);
  792. llvm::SaveAndRestore class_scope(scope_,
  793. inst_namer_.GetScopeFor(inst.impl_id));
  794. FormatTrailingBlock(sem_ir_->impls().Get(inst.impl_id).pattern_block_id);
  795. FormatTrailingBlock(inst.decl_block_id);
  796. }
  797. auto Formatter::FormatInstRhs(InterfaceDecl inst) -> void {
  798. FormatArgs(inst.interface_id);
  799. llvm::SaveAndRestore class_scope(scope_,
  800. inst_namer_.GetScopeFor(inst.interface_id));
  801. FormatTrailingBlock(
  802. sem_ir_->interfaces().Get(inst.interface_id).pattern_block_id);
  803. FormatTrailingBlock(inst.decl_block_id);
  804. }
  805. auto Formatter::FormatInstRhs(AssociatedConstantDecl inst) -> void {
  806. FormatArgs(inst.assoc_const_id);
  807. llvm::SaveAndRestore assoc_const_scope(
  808. scope_, inst_namer_.GetScopeFor(inst.assoc_const_id));
  809. FormatTrailingBlock(inst.decl_block_id);
  810. }
  811. auto Formatter::FormatInstRhs(IntValue inst) -> void {
  812. out_ << " ";
  813. sem_ir_->ints()
  814. .Get(inst.int_id)
  815. .print(out_, sem_ir_->types().IsSignedInt(inst.type_id));
  816. }
  817. auto Formatter::FormatInstRhs(FloatLiteral inst) -> void {
  818. llvm::SmallVector<char, 16> buffer;
  819. sem_ir_->floats().Get(inst.float_id).toString(buffer);
  820. out_ << " " << buffer;
  821. }
  822. auto Formatter::FormatInstRhs(ImportCppDecl /*inst*/) -> void {
  823. out_ << " ";
  824. OpenBrace();
  825. for (ImportCpp import_cpp : sem_ir_->import_cpps().array_ref()) {
  826. Indent();
  827. out_ << "import Cpp \""
  828. << FormatEscaped(
  829. sem_ir_->string_literal_values().Get(import_cpp.library_id))
  830. << "\"\n";
  831. }
  832. CloseBrace();
  833. }
  834. auto Formatter::FormatImportRefRhs(ImportIRInstId import_ir_inst_id,
  835. EntityNameId entity_name_id,
  836. llvm::StringLiteral loaded_label) -> void {
  837. out_ << " ";
  838. auto import_ir_inst = sem_ir_->import_ir_insts().Get(import_ir_inst_id);
  839. FormatArg(import_ir_inst.ir_id());
  840. out_ << ", ";
  841. if (entity_name_id.has_value()) {
  842. // Prefer to show the entity name when possible.
  843. FormatArg(entity_name_id);
  844. } else {
  845. // Show a name based on the location when possible, or the numeric
  846. // instruction as a last resort.
  847. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  848. auto loc_id =
  849. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  850. switch (loc_id.kind()) {
  851. case LocId::Kind::None: {
  852. out_ << import_ir_inst.inst_id() << " [no loc]";
  853. break;
  854. }
  855. case LocId::Kind::ImportIRInstId: {
  856. // TODO: Probably don't want to format each indirection, but maybe
  857. // reuse GetCanonicalImportIRInst?
  858. out_ << import_ir_inst.inst_id() << " [indirect]";
  859. break;
  860. }
  861. case LocId::Kind::NodeId: {
  862. // Formats a NodeId from the import.
  863. const auto& tree = import_ir.sem_ir->parse_tree();
  864. auto token = tree.node_token(loc_id.node_id());
  865. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  866. << tree.tokens().GetColumnNumber(token);
  867. break;
  868. }
  869. case LocId::Kind::InstId:
  870. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  871. }
  872. }
  873. out_ << ", " << loaded_label;
  874. }
  875. auto Formatter::FormatInstRhs(ImportRefLoaded inst) -> void {
  876. FormatImportRefRhs(inst.import_ir_inst_id, inst.entity_name_id, "loaded");
  877. }
  878. auto Formatter::FormatInstRhs(ImportRefUnloaded inst) -> void {
  879. FormatImportRefRhs(inst.import_ir_inst_id, inst.entity_name_id, "unloaded");
  880. }
  881. auto Formatter::FormatInstRhs(InstValue inst) -> void {
  882. out_ << ' ';
  883. OpenBrace();
  884. // TODO: Should we use a more compact representation in the case where the
  885. // inst is a SpliceBlock?
  886. FormatInst(inst.inst_id);
  887. CloseBrace();
  888. }
  889. auto Formatter::FormatInstRhs(NameBindingDecl inst) -> void {
  890. FormatTrailingBlock(inst.pattern_block_id);
  891. }
  892. auto Formatter::FormatInstRhs(SpliceBlock inst) -> void {
  893. FormatArgs(inst.result_id);
  894. FormatTrailingBlock(inst.block_id);
  895. }
  896. auto Formatter::FormatInstRhs(WhereExpr inst) -> void {
  897. FormatArgs(inst.period_self_id);
  898. FormatTrailingBlock(inst.requirements_id);
  899. }
  900. auto Formatter::FormatInstRhs(StructType inst) -> void {
  901. out_ << " {";
  902. llvm::ListSeparator sep;
  903. for (auto field : sem_ir_->struct_type_fields().Get(inst.fields_id)) {
  904. out_ << sep << ".";
  905. FormatName(field.name_id);
  906. out_ << ": ";
  907. FormatInstAsType(field.type_inst_id);
  908. }
  909. out_ << "}";
  910. }
  911. auto Formatter::FormatArg(EntityNameId id) -> void {
  912. if (!id.has_value()) {
  913. out_ << "_";
  914. return;
  915. }
  916. const auto& info = sem_ir_->entity_names().Get(id);
  917. FormatName(info.name_id);
  918. if (info.bind_index().has_value()) {
  919. out_ << ", " << info.bind_index().index;
  920. }
  921. if (info.is_template) {
  922. out_ << ", template";
  923. }
  924. }
  925. auto Formatter::FormatArg(FacetTypeId id) -> void {
  926. const auto& info = sem_ir_->facet_types().Get(id);
  927. // Nothing output to indicate that this is a facet type since this is only
  928. // used as the argument to a `facet_type` instruction.
  929. out_ << "<";
  930. llvm::ListSeparator sep(" & ");
  931. if (info.extend_constraints.empty()) {
  932. out_ << "type";
  933. } else {
  934. for (auto interface : info.extend_constraints) {
  935. out_ << sep;
  936. FormatName(interface.interface_id);
  937. if (interface.specific_id.has_value()) {
  938. out_ << ", ";
  939. FormatName(interface.specific_id);
  940. }
  941. }
  942. }
  943. if (info.other_requirements || !info.self_impls_constraints.empty() ||
  944. !info.rewrite_constraints.empty()) {
  945. out_ << " where ";
  946. llvm::ListSeparator and_sep(" and ");
  947. if (!info.self_impls_constraints.empty()) {
  948. out_ << and_sep << ".Self impls ";
  949. llvm::ListSeparator amp_sep(" & ");
  950. for (auto interface : info.self_impls_constraints) {
  951. out_ << amp_sep;
  952. FormatName(interface.interface_id);
  953. if (interface.specific_id.has_value()) {
  954. out_ << ", ";
  955. FormatName(interface.specific_id);
  956. }
  957. }
  958. }
  959. for (auto rewrite : info.rewrite_constraints) {
  960. out_ << and_sep;
  961. FormatArg(rewrite.lhs_id);
  962. out_ << " = ";
  963. FormatArg(rewrite.rhs_id);
  964. }
  965. if (info.other_requirements) {
  966. out_ << and_sep << "TODO";
  967. }
  968. }
  969. out_ << ">";
  970. }
  971. auto Formatter::FormatArg(ImportIRId id) -> void {
  972. if (id.has_value()) {
  973. out_ << GetImportIRLabel(id);
  974. } else {
  975. out_ << id;
  976. }
  977. }
  978. auto Formatter::FormatArg(IntId id) -> void {
  979. // We don't know the signedness to use here. Default to unsigned.
  980. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  981. }
  982. auto Formatter::FormatArg(NameScopeId id) -> void {
  983. OpenBrace();
  984. FormatNameScope(id);
  985. CloseBrace();
  986. }
  987. auto Formatter::FormatArg(InstBlockId id) -> void {
  988. if (!id.has_value()) {
  989. out_ << "invalid";
  990. return;
  991. }
  992. out_ << '(';
  993. llvm::ListSeparator sep;
  994. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  995. out_ << sep;
  996. FormatArg(inst_id);
  997. }
  998. out_ << ')';
  999. }
  1000. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1001. FormatArg(static_cast<InstBlockId>(id));
  1002. }
  1003. auto Formatter::FormatArg(RealId id) -> void {
  1004. // TODO: Format with a `.` when the exponent is near zero.
  1005. const auto& real = sem_ir_->reals().Get(id);
  1006. real.mantissa.print(out_, /*isSigned=*/false);
  1007. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1008. }
  1009. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1010. out_ << '"'
  1011. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1012. /*use_hex_escapes=*/true)
  1013. << '"';
  1014. }
  1015. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1016. out_ << " to ";
  1017. FormatArg(dest_id);
  1018. }
  1019. auto Formatter::FormatName(NameId id) -> void {
  1020. out_ << sem_ir_->names().GetFormatted(id);
  1021. }
  1022. auto Formatter::FormatName(InstId id) -> void {
  1023. if (id.has_value()) {
  1024. IncludeChunkInOutput(tentative_inst_chunks_[id.index]);
  1025. }
  1026. out_ << inst_namer_.GetNameFor(scope_, id);
  1027. }
  1028. auto Formatter::FormatName(SpecificId id) -> void {
  1029. const auto& specific = sem_ir_->specifics().Get(id);
  1030. FormatName(specific.generic_id);
  1031. FormatArg(specific.args_id);
  1032. }
  1033. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1034. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1035. FormatName(interface.interface_id);
  1036. if (interface.specific_id.has_value()) {
  1037. out_ << ", ";
  1038. FormatArg(interface.specific_id);
  1039. }
  1040. }
  1041. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1042. out_ << inst_namer_.GetLabelFor(scope_, id);
  1043. }
  1044. auto Formatter::FormatConstant(ConstantId id) -> void {
  1045. if (!id.has_value()) {
  1046. out_ << "<not constant>";
  1047. return;
  1048. }
  1049. // For a symbolic constant in a generic, list the constant value in the
  1050. // generic first, and the canonical constant second.
  1051. if (id.is_symbolic()) {
  1052. const auto& symbolic_constant =
  1053. sem_ir_->constant_values().GetSymbolicConstant(id);
  1054. if (symbolic_constant.generic_id.has_value()) {
  1055. const auto& generic =
  1056. sem_ir_->generics().Get(symbolic_constant.generic_id);
  1057. FormatName(sem_ir_->inst_blocks().Get(generic.GetEvalBlock(
  1058. symbolic_constant.index.region()))[symbolic_constant.index.index()]);
  1059. out_ << " (";
  1060. FormatName(sem_ir_->constant_values().GetInstId(id));
  1061. out_ << ")";
  1062. return;
  1063. }
  1064. }
  1065. FormatName(sem_ir_->constant_values().GetInstId(id));
  1066. }
  1067. auto Formatter::FormatInstAsType(InstId id) -> void {
  1068. if (!id.has_value()) {
  1069. out_ << "invalid";
  1070. return;
  1071. }
  1072. // Types are formatted in the `constants` scope because they typically refer
  1073. // to constants.
  1074. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1075. if (auto const_id = sem_ir_->constant_values().Get(id);
  1076. const_id.has_value()) {
  1077. FormatConstant(const_id);
  1078. } else {
  1079. // Type instruction didn't have a constant value. Fall back to printing
  1080. // the instruction name.
  1081. FormatArg(id);
  1082. }
  1083. }
  1084. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1085. auto type_id = sem_ir_->insts().Get(id).type_id();
  1086. if (!type_id.has_value()) {
  1087. out_ << "invalid";
  1088. return;
  1089. }
  1090. // Types are formatted in the `constants` scope because they typically refer
  1091. // to constants.
  1092. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1093. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1094. }
  1095. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1096. CARBON_CHECK(id.has_value(),
  1097. "Callers are responsible for checking `id.has_value`");
  1098. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1099. CARBON_CHECK(import_ir.library_id().has_value());
  1100. auto package_id = import_ir.package_id();
  1101. llvm::StringRef package_name =
  1102. package_id.AsIdentifierId().has_value()
  1103. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1104. : package_id.AsSpecialName();
  1105. llvm::StringRef library_name =
  1106. (import_ir.library_id() != LibraryNameId::Default)
  1107. ? import_ir.string_literal_values().Get(
  1108. import_ir.library_id().AsStringLiteralValueId())
  1109. : "default";
  1110. return llvm::formatv("{0}//{1}", package_name, library_name);
  1111. }
  1112. } // namespace Carbon::SemIR
  1113. // NOLINTEND(misc-no-recursion)