formatter.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  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/fixed_size_value_store.h"
  12. #include "toolchain/base/kind_switch.h"
  13. #include "toolchain/base/shared_value_stores.h"
  14. #include "toolchain/lex/tokenized_buffer.h"
  15. #include "toolchain/parse/tree.h"
  16. #include "toolchain/parse/tree_and_subtrees.h"
  17. #include "toolchain/sem_ir/builtin_function_kind.h"
  18. #include "toolchain/sem_ir/constant.h"
  19. #include "toolchain/sem_ir/entity_with_params_base.h"
  20. #include "toolchain/sem_ir/expr_info.h"
  21. #include "toolchain/sem_ir/function.h"
  22. #include "toolchain/sem_ir/ids.h"
  23. #include "toolchain/sem_ir/name_scope.h"
  24. #include "toolchain/sem_ir/typed_insts.h"
  25. #include "toolchain/sem_ir/vtable.h"
  26. // TODO: Consider addressing recursion here, although it's not critical because
  27. // the formatter isn't required to work on arbitrary code. Still, it may help
  28. // in the future to debug complex code.
  29. // NOLINTBEGIN(misc-no-recursion)
  30. namespace Carbon::SemIR {
  31. Formatter::Formatter(
  32. const File* sem_ir, int total_ir_count,
  33. Parse::GetTreeAndSubtreesFn get_tree_and_subtrees,
  34. const FixedSizeValueStore<CheckIRId, bool>* include_ir_in_dumps,
  35. bool use_dump_sem_ir_ranges)
  36. : sem_ir_(sem_ir),
  37. inst_namer_(sem_ir_, total_ir_count),
  38. get_tree_and_subtrees_(get_tree_and_subtrees),
  39. include_ir_in_dumps_(include_ir_in_dumps),
  40. use_dump_sem_ir_ranges_(use_dump_sem_ir_ranges),
  41. // Create a placeholder visible chunk and assign it to all instructions
  42. // that don't have a chunk of their own.
  43. tentative_inst_chunks_(sem_ir_->insts(), AddChunkNoFlush(true)) {
  44. if (use_dump_sem_ir_ranges_) {
  45. ComputeNodeParents();
  46. }
  47. // Create empty placeholder chunks for instructions that we output lazily.
  48. for (auto inst_id : llvm::concat<const InstId>(
  49. sem_ir_->constants().array_ref(),
  50. sem_ir_->inst_blocks().Get(InstBlockId::Imports))) {
  51. tentative_inst_chunks_.Set(inst_id, AddChunkNoFlush(false));
  52. }
  53. // Create a real chunk for the start of the output.
  54. AddChunkNoFlush(true);
  55. }
  56. auto Formatter::Format() -> void {
  57. out_ << "--- " << sem_ir_->filename() << "\n";
  58. FormatTopLevelScopeIfUsed(InstNamer::ScopeId::Constants,
  59. sem_ir_->constants().array_ref(),
  60. /*use_tentative_output_scopes=*/true);
  61. FormatTopLevelScopeIfUsed(InstNamer::ScopeId::Imports,
  62. sem_ir_->inst_blocks().Get(InstBlockId::Imports),
  63. /*use_tentative_output_scopes=*/true);
  64. FormatTopLevelScopeIfUsed(
  65. InstNamer::ScopeId::File,
  66. sem_ir_->inst_blocks().GetOrEmpty(sem_ir_->top_inst_block_id()),
  67. /*use_tentative_output_scopes=*/false);
  68. for (const auto& [id, interface] : sem_ir_->interfaces().enumerate()) {
  69. FormatInterface(id, interface);
  70. }
  71. for (const auto& [id, constraint] :
  72. sem_ir_->named_constraints().enumerate()) {
  73. FormatNamedConstraint(id, constraint);
  74. }
  75. for (const auto& [id, require] : sem_ir_->require_impls().enumerate()) {
  76. FormatRequireImpls(id, require);
  77. }
  78. for (const auto& [id, assoc_const] :
  79. sem_ir_->associated_constants().enumerate()) {
  80. FormatAssociatedConstant(id, assoc_const);
  81. }
  82. for (const auto& [id, impl] : sem_ir_->impls().enumerate()) {
  83. FormatImpl(id, impl);
  84. }
  85. for (const auto& [id, class_info] : sem_ir_->classes().enumerate()) {
  86. FormatClass(id, class_info);
  87. }
  88. for (const auto& [id, vtable] : sem_ir_->vtables().enumerate()) {
  89. FormatVtable(id, vtable);
  90. }
  91. for (const auto& [id, function] : sem_ir_->functions().enumerate()) {
  92. FormatFunction(id, function);
  93. }
  94. for (const auto& [id, specific] : sem_ir_->specifics().enumerate()) {
  95. FormatSpecific(id, specific);
  96. }
  97. out_ << "\n";
  98. }
  99. auto Formatter::ComputeNodeParents() -> void {
  100. CARBON_CHECK(!node_parents_);
  101. node_parents_ = NodeParentStore::MakeWithExplicitSize(
  102. IdTag(), sem_ir_->parse_tree().size(), Parse::NodeId::None);
  103. for (auto n : sem_ir_->parse_tree().postorder()) {
  104. for (auto child : get_tree_and_subtrees_().children(n)) {
  105. node_parents_->Set(child, n);
  106. }
  107. }
  108. }
  109. auto Formatter::Write(llvm::raw_ostream& out) -> void {
  110. FlushChunk();
  111. for (const auto& chunk : output_chunks_) {
  112. if (chunk.include_in_output) {
  113. out << chunk.chunk;
  114. }
  115. }
  116. }
  117. auto Formatter::FlushChunk() -> void {
  118. CARBON_CHECK(output_chunks_.back().chunk.empty());
  119. output_chunks_.back().chunk = std::move(buffer_);
  120. buffer_.clear();
  121. }
  122. auto Formatter::AddChunkNoFlush(bool include_in_output) -> size_t {
  123. CARBON_CHECK(buffer_.empty());
  124. output_chunks_.push_back({.include_in_output = include_in_output});
  125. return output_chunks_.size() - 1;
  126. }
  127. auto Formatter::AddChunk(bool include_in_output) -> size_t {
  128. FlushChunk();
  129. return AddChunkNoFlush(include_in_output);
  130. }
  131. auto Formatter::IncludeChunkInOutput(size_t chunk) -> void {
  132. if (chunk == output_chunks_.size() - 1) {
  133. return;
  134. }
  135. if (auto& current_chunk = output_chunks_.back();
  136. !current_chunk.include_in_output) {
  137. current_chunk.dependencies.push_back(chunk);
  138. return;
  139. }
  140. llvm::SmallVector<size_t> to_add = {chunk};
  141. while (!to_add.empty()) {
  142. auto& chunk = output_chunks_[to_add.pop_back_val()];
  143. if (chunk.include_in_output) {
  144. continue;
  145. }
  146. chunk.include_in_output = true;
  147. to_add.append(chunk.dependencies);
  148. chunk.dependencies.clear();
  149. }
  150. }
  151. auto Formatter::ShouldIncludeInstByIR(InstId inst_id) -> bool {
  152. const auto* import_ir = GetCanonicalFileAndInstId(sem_ir_, inst_id).first;
  153. return include_ir_in_dumps_->Get(import_ir->check_ir_id());
  154. }
  155. // Returns true for a `DefinitionStart` node.
  156. static auto IsDefinitionStart(Parse::NodeKind node_kind) -> bool {
  157. switch (node_kind) {
  158. case Parse::NodeKind::BuiltinFunctionDefinitionStart:
  159. case Parse::NodeKind::ChoiceDefinitionStart:
  160. case Parse::NodeKind::ClassDefinitionStart:
  161. case Parse::NodeKind::FunctionDefinitionStart:
  162. case Parse::NodeKind::ImplDefinitionStart:
  163. case Parse::NodeKind::InterfaceDefinitionStart:
  164. case Parse::NodeKind::NamedConstraintDefinitionStart:
  165. return true;
  166. default:
  167. return false;
  168. }
  169. }
  170. auto Formatter::ShouldFormatEntity(InstId decl_id) -> bool {
  171. if (!decl_id.has_value()) {
  172. return true;
  173. }
  174. if (!ShouldIncludeInstByIR(decl_id)) {
  175. return false;
  176. }
  177. if (!use_dump_sem_ir_ranges_) {
  178. return true;
  179. }
  180. // When there are dump ranges, ignore imported instructions.
  181. auto loc_id = sem_ir_->insts().GetCanonicalLocId(decl_id);
  182. if (loc_id.kind() != LocId::Kind::NodeId) {
  183. return false;
  184. }
  185. const auto& tree_and_subtrees = get_tree_and_subtrees_();
  186. // This takes the earliest token from either the node or its first postorder
  187. // child. The first postorder child isn't necessarily the earliest token in
  188. // the subtree (for example, it can miss modifiers), but finding the earliest
  189. // token requires walking *all* children, whereas this approach is
  190. // constant-time.
  191. auto begin_node_id = *tree_and_subtrees.postorder(loc_id.node_id()).begin();
  192. // Non-defining declarations will be associated with a `Decl` node.
  193. // Definitions will have a `DefinitionStart` for which we can use the parent
  194. // to find the `Definition`, giving a range that includes the definition's
  195. // body.
  196. auto end_node_id = loc_id.node_id();
  197. if (IsDefinitionStart(sem_ir_->parse_tree().node_kind(end_node_id))) {
  198. end_node_id = node_parents_->Get(end_node_id);
  199. }
  200. Lex::InclusiveTokenRange range = {
  201. .begin = sem_ir_->parse_tree().node_token(begin_node_id),
  202. .end = sem_ir_->parse_tree().node_token(end_node_id)};
  203. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(range);
  204. }
  205. auto Formatter::ShouldFormatEntity(const EntityWithParamsBase& entity) -> bool {
  206. return ShouldFormatEntity(entity.latest_decl_id());
  207. }
  208. auto Formatter::ShouldFormatInst(InstId inst_id) -> bool {
  209. if (!use_dump_sem_ir_ranges_) {
  210. return true;
  211. }
  212. // When there are dump ranges, ignore imported instructions.
  213. auto loc_id = sem_ir_->insts().GetCanonicalLocId(inst_id);
  214. if (loc_id.kind() != LocId::Kind::NodeId) {
  215. return false;
  216. }
  217. auto token = sem_ir_->parse_tree().node_token(loc_id.node_id());
  218. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(
  219. Lex::InclusiveTokenRange{.begin = token, .end = token});
  220. }
  221. auto Formatter::OpenBrace() -> void {
  222. // Put the constant value of an instruction before any braced block, rather
  223. // than at the end.
  224. FormatPendingConstantValue(AddSpace::After);
  225. // Put the imported-from library name before the definition of the entity.
  226. FormatPendingImportedFrom(AddSpace::After);
  227. out_ << '{';
  228. indent_ += 2;
  229. after_open_brace_ = true;
  230. }
  231. auto Formatter::CloseBrace() -> void {
  232. indent_ -= 2;
  233. if (!after_open_brace_) {
  234. Indent();
  235. }
  236. out_ << '}';
  237. after_open_brace_ = false;
  238. }
  239. auto Formatter::Semicolon() -> void {
  240. FormatPendingImportedFrom(AddSpace::Before);
  241. out_ << ';';
  242. }
  243. auto Formatter::Indent(int offset) -> void {
  244. if (after_open_brace_) {
  245. out_ << '\n';
  246. after_open_brace_ = false;
  247. }
  248. out_.indent(indent_ + offset);
  249. }
  250. auto Formatter::IndentLabel() -> void {
  251. CARBON_CHECK(indent_ >= 2);
  252. if (!after_open_brace_) {
  253. out_ << '\n';
  254. }
  255. Indent(-2);
  256. }
  257. auto Formatter::FormatTopLevelScopeIfUsed(InstNamer::ScopeId scope_id,
  258. llvm::ArrayRef<InstId> block,
  259. bool use_tentative_output_scopes)
  260. -> void {
  261. if (!use_tentative_output_scopes && use_dump_sem_ir_ranges_) {
  262. // Don't format the scope if no instructions are in a dump range.
  263. block = block.drop_while(
  264. [&](InstId inst_id) { return !ShouldFormatInst(inst_id); });
  265. }
  266. if (block.empty()) {
  267. return;
  268. }
  269. llvm::SaveAndRestore scope(scope_, scope_id);
  270. // Note, we don't use OpenBrace() / CloseBrace() here because we always want
  271. // a newline to avoid misformatting if the first instruction is omitted.
  272. out_ << "\n" << inst_namer_.GetScopeName(scope_id) << " {\n";
  273. indent_ += 2;
  274. for (const InstId inst_id : block) {
  275. // Format instructions when needed, but do nothing for elided entries;
  276. // unlike normal code blocks, scopes are non-sequential so skipped
  277. // instructions are assumed to be uninteresting.
  278. if (use_tentative_output_scopes) {
  279. // This is for constants and imports. These use tentative logic to
  280. // determine whether an instruction is printed.
  281. TentativeOutputScope scope(*this, tentative_inst_chunks_.Get(inst_id));
  282. FormatInst(inst_id);
  283. } else if (ShouldFormatInst(inst_id)) {
  284. // This is for the file scope. It uses only the range-based filtering.
  285. FormatInst(inst_id);
  286. }
  287. }
  288. out_ << "}\n";
  289. indent_ -= 2;
  290. }
  291. auto Formatter::FormatClass(ClassId id, const Class& class_info) -> void {
  292. if (!ShouldFormatEntity(class_info)) {
  293. return;
  294. }
  295. PrepareToFormatDecl(class_info.first_owning_decl_id);
  296. FormatEntityStart("class", class_info, id);
  297. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  298. if (class_info.scope_id.has_value()) {
  299. out_ << ' ';
  300. OpenBrace();
  301. FormatCodeBlock(class_info.body_block_id);
  302. Indent();
  303. out_ << "complete_type_witness = ";
  304. FormatName(class_info.complete_type_witness_id);
  305. out_ << "\n";
  306. if (class_info.vtable_decl_id.has_value()) {
  307. Indent();
  308. out_ << "vtable_decl = ";
  309. FormatName(class_info.vtable_decl_id);
  310. out_ << "\n";
  311. }
  312. FormatNameScope(class_info.scope_id, "!members:\n");
  313. CloseBrace();
  314. } else {
  315. Semicolon();
  316. }
  317. out_ << '\n';
  318. FormatEntityEnd(class_info.generic_id);
  319. }
  320. auto Formatter::FormatVtable(VtableId id, const Vtable& vtable_info) -> void {
  321. out_ << '\n';
  322. Indent();
  323. out_ << "vtable ";
  324. FormatName(id);
  325. out_ << ' ';
  326. OpenBrace();
  327. for (auto function_id :
  328. sem_ir_->inst_blocks().Get(vtable_info.virtual_functions_id)) {
  329. Indent();
  330. FormatArg(function_id);
  331. out_ << '\n';
  332. }
  333. CloseBrace();
  334. out_ << '\n';
  335. }
  336. auto Formatter::FormatInterface(InterfaceId id, const Interface& interface_info)
  337. -> void {
  338. if (!ShouldFormatEntity(interface_info)) {
  339. return;
  340. }
  341. PrepareToFormatDecl(interface_info.first_owning_decl_id);
  342. FormatEntityStart("interface", interface_info, id);
  343. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  344. if (interface_info.scope_id.has_value()) {
  345. out_ << ' ';
  346. OpenBrace();
  347. FormatCodeBlock(interface_info.body_block_id);
  348. // Always include the !members label because we always list the witness in
  349. // this section.
  350. IndentLabel();
  351. out_ << "!members:\n";
  352. FormatNameScope(interface_info.scope_id);
  353. Indent();
  354. out_ << "witness = ";
  355. FormatArg(interface_info.associated_entities_id);
  356. out_ << "\n";
  357. FormatRequireImplsBlock(interface_info.require_impls_block_id);
  358. CloseBrace();
  359. } else {
  360. Semicolon();
  361. }
  362. out_ << '\n';
  363. FormatEntityEnd(interface_info.generic_id);
  364. }
  365. auto Formatter::FormatNamedConstraint(NamedConstraintId id,
  366. const NamedConstraint& constraint_info)
  367. -> void {
  368. if (!ShouldFormatEntity(constraint_info)) {
  369. return;
  370. }
  371. PrepareToFormatDecl(constraint_info.first_owning_decl_id);
  372. FormatEntityStart("constraint", constraint_info, id);
  373. llvm::SaveAndRestore constraint_scope(scope_, inst_namer_.GetScopeFor(id));
  374. if (constraint_info.scope_id.has_value()) {
  375. out_ << ' ';
  376. OpenBrace();
  377. FormatCodeBlock(constraint_info.body_block_id);
  378. // Always include the !members label because we always list the witness in
  379. // this section.
  380. IndentLabel();
  381. out_ << "!members:\n";
  382. FormatNameScope(constraint_info.scope_id);
  383. FormatRequireImplsBlock(constraint_info.require_impls_block_id);
  384. CloseBrace();
  385. } else {
  386. Semicolon();
  387. }
  388. out_ << '\n';
  389. FormatEntityEnd(constraint_info.generic_id);
  390. }
  391. auto Formatter::FormatRequireImpls(RequireImplsId /*id*/,
  392. const RequireImpls& require) -> void {
  393. if (!ShouldFormatEntity(require.decl_id)) {
  394. return;
  395. }
  396. PrepareToFormatDecl(require.decl_id);
  397. FormatGenericStart("require", require.generic_id);
  398. FormatGenericEnd();
  399. }
  400. auto Formatter::FormatAssociatedConstant(AssociatedConstantId id,
  401. const AssociatedConstant& assoc_const)
  402. -> void {
  403. if (!ShouldFormatEntity(assoc_const.decl_id)) {
  404. return;
  405. }
  406. PrepareToFormatDecl(assoc_const.decl_id);
  407. FormatEntityStart("assoc_const", assoc_const.generic_id, id);
  408. llvm::SaveAndRestore assoc_const_scope(scope_, inst_namer_.GetScopeFor(id));
  409. out_ << " ";
  410. FormatName(assoc_const.name_id);
  411. out_ << ":! ";
  412. FormatTypeOfInst(assoc_const.decl_id);
  413. if (assoc_const.default_value_id.has_value()) {
  414. out_ << " = ";
  415. FormatArg(assoc_const.default_value_id);
  416. }
  417. out_ << ";\n";
  418. FormatEntityEnd(assoc_const.generic_id);
  419. }
  420. auto Formatter::FormatImpl(ImplId id, const Impl& impl_info) -> void {
  421. if (!ShouldFormatEntity(impl_info)) {
  422. return;
  423. }
  424. PrepareToFormatDecl(impl_info.first_owning_decl_id);
  425. FormatEntityStart("impl", impl_info, id);
  426. llvm::SaveAndRestore impl_scope(scope_, inst_namer_.GetScopeFor(id));
  427. out_ << ": ";
  428. FormatName(impl_info.self_id);
  429. out_ << " as ";
  430. FormatName(impl_info.constraint_id);
  431. if (impl_info.is_complete()) {
  432. out_ << ' ';
  433. OpenBrace();
  434. FormatCodeBlock(impl_info.body_block_id);
  435. // Print the !members label even if the name scope is empty because we
  436. // always list the witness in this section.
  437. IndentLabel();
  438. out_ << "!members:\n";
  439. if (impl_info.scope_id.has_value()) {
  440. FormatNameScope(impl_info.scope_id);
  441. }
  442. Indent();
  443. out_ << "witness = ";
  444. FormatArg(impl_info.witness_id);
  445. out_ << "\n";
  446. CloseBrace();
  447. } else {
  448. Semicolon();
  449. }
  450. out_ << '\n';
  451. FormatEntityEnd(impl_info.generic_id);
  452. }
  453. auto Formatter::FormatFunction(FunctionId id, const Function& fn) -> void {
  454. if (!ShouldFormatEntity(fn)) {
  455. return;
  456. }
  457. std::string function_start;
  458. switch (fn.virtual_modifier) {
  459. case FunctionFields::VirtualModifier::Virtual:
  460. function_start += "virtual ";
  461. break;
  462. case FunctionFields::VirtualModifier::Abstract:
  463. function_start += "abstract ";
  464. break;
  465. case FunctionFields::VirtualModifier::Override:
  466. function_start += "override ";
  467. break;
  468. case FunctionFields::VirtualModifier::None:
  469. break;
  470. }
  471. if (fn.is_extern) {
  472. function_start += "extern ";
  473. }
  474. function_start += "fn";
  475. PrepareToFormatDecl(fn.first_owning_decl_id);
  476. FormatEntityStart(function_start, fn, id);
  477. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  478. auto return_type_info = ReturnTypeInfo::ForFunction(*sem_ir_, fn);
  479. FormatParamList(fn.call_params_id, return_type_info.is_valid() &&
  480. return_type_info.has_return_slot());
  481. if (fn.builtin_function_kind() != BuiltinFunctionKind::None) {
  482. out_ << " = \""
  483. << FormatEscaped(fn.builtin_function_kind().name(),
  484. /*use_hex_escapes=*/true)
  485. << "\"";
  486. }
  487. if (fn.thunk_decl_id().has_value()) {
  488. out_ << " [thunk ";
  489. FormatArg(fn.thunk_decl_id());
  490. out_ << "]";
  491. }
  492. if (!fn.body_block_ids.empty()) {
  493. out_ << ' ';
  494. OpenBrace();
  495. for (auto block_id : fn.body_block_ids) {
  496. IndentLabel();
  497. FormatLabel(block_id);
  498. out_ << ":\n";
  499. FormatCodeBlock(block_id);
  500. }
  501. CloseBrace();
  502. } else {
  503. Semicolon();
  504. }
  505. out_ << '\n';
  506. FormatEntityEnd(fn.generic_id);
  507. }
  508. auto Formatter::FormatSpecificRegion(const Generic& generic,
  509. const Specific& specific,
  510. GenericInstIndex::Region region,
  511. llvm::StringRef region_name) -> void {
  512. if (!specific.GetValueBlock(region).has_value()) {
  513. return;
  514. }
  515. if (!region_name.empty()) {
  516. IndentLabel();
  517. out_ << "!" << region_name << ":\n";
  518. }
  519. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  520. sem_ir_->inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  521. sem_ir_->inst_blocks().GetOrEmpty(specific.GetValueBlock(region)))) {
  522. Indent();
  523. if (generic_inst_id) {
  524. FormatName(*generic_inst_id);
  525. } else {
  526. out_ << "<missing>";
  527. }
  528. out_ << " => ";
  529. if (specific_inst_id) {
  530. FormatName(*specific_inst_id);
  531. } else {
  532. out_ << "<missing>";
  533. }
  534. out_ << "\n";
  535. }
  536. }
  537. auto Formatter::FormatSpecific(SpecificId id, const Specific& specific)
  538. -> void {
  539. const auto& generic = sem_ir_->generics().Get(specific.generic_id);
  540. if (!ShouldFormatEntity(generic.decl_id)) {
  541. // Omit specifics if we also omitted the generic.
  542. return;
  543. }
  544. if (specific.IsUnresolved()) {
  545. // Omit specifics that were never resolved. Such specifics exist only to
  546. // track the way the arguments were spelled, and that information is
  547. // conveyed entirely by the name of the specific. These specifics may also
  548. // not be referenced by any SemIR that we format, so including them adds
  549. // clutter and possibly emits references to instructions we didn't name.
  550. return;
  551. }
  552. llvm::SaveAndRestore generic_scope(
  553. scope_, inst_namer_.GetScopeFor(specific.generic_id));
  554. out_ << "\n";
  555. out_ << "specific ";
  556. FormatName(id);
  557. out_ << " ";
  558. OpenBrace();
  559. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Declaration,
  560. "");
  561. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Definition,
  562. "definition");
  563. CloseBrace();
  564. out_ << "\n";
  565. }
  566. auto Formatter::PrepareToFormatDecl(InstId first_owning_decl_id) -> void {
  567. // If this decl was imported from a different IR, annotate the name of
  568. // that IR in the output before the `{` or `;`.
  569. if (first_owning_decl_id.has_value()) {
  570. auto import_ir_inst_id =
  571. sem_ir_->insts().GetImportSource(first_owning_decl_id);
  572. if (import_ir_inst_id.has_value()) {
  573. auto import_ir_id =
  574. sem_ir_->import_ir_insts().Get(import_ir_inst_id).ir_id();
  575. if (const auto* import_file =
  576. sem_ir_->import_irs().Get(import_ir_id).sem_ir) {
  577. pending_imported_from_ = import_file->filename();
  578. }
  579. }
  580. }
  581. }
  582. auto Formatter::FormatGenericStart(llvm::StringRef entity_kind,
  583. GenericId generic_id) -> void {
  584. const auto& generic = sem_ir_->generics().Get(generic_id);
  585. out_ << "\n";
  586. Indent();
  587. out_ << "generic " << entity_kind << " ";
  588. FormatName(generic_id);
  589. llvm::SaveAndRestore generic_scope(scope_,
  590. inst_namer_.GetScopeFor(generic_id));
  591. FormatParamList(generic.bindings_id);
  592. out_ << " ";
  593. OpenBrace();
  594. FormatCodeBlock(generic.decl_block_id);
  595. if (generic.definition_block_id.has_value()) {
  596. IndentLabel();
  597. out_ << "!definition:\n";
  598. FormatCodeBlock(generic.definition_block_id);
  599. }
  600. }
  601. auto Formatter::FormatEntityEnd(GenericId generic_id) -> void {
  602. if (generic_id.has_value()) {
  603. FormatGenericEnd();
  604. }
  605. }
  606. auto Formatter::FormatGenericEnd() -> void {
  607. CloseBrace();
  608. out_ << '\n';
  609. }
  610. auto Formatter::FormatParamList(InstBlockId params_id, bool has_return_slot)
  611. -> void {
  612. if (!params_id.has_value()) {
  613. // TODO: This happens for imported functions, for which we don't currently
  614. // import the call parameters list.
  615. return;
  616. }
  617. llvm::StringLiteral close = ")";
  618. out_ << "(";
  619. llvm::ListSeparator sep;
  620. for (InstId param_id : sem_ir_->inst_blocks().Get(params_id)) {
  621. auto is_out_param = sem_ir_->insts().Is<OutParam>(param_id);
  622. if (is_out_param) {
  623. // TODO: An input parameter following an output parameter is formatted a
  624. // bit strangely. For example, alternating input and output parameters
  625. // produces:
  626. //
  627. // fn @F(%in1: %t) -> %out1: %t, %in2: %t -> %out2: %t
  628. //
  629. // This doesn't actually happen right now, though.
  630. out_ << std::exchange(close, llvm::StringLiteral(""));
  631. out_ << " -> ";
  632. } else {
  633. out_ << sep;
  634. }
  635. if (!param_id.has_value()) {
  636. out_ << "invalid";
  637. continue;
  638. }
  639. // Don't include the name of the return slot parameter if the function
  640. // doesn't have a return slot; the name won't be used for anything in that
  641. // case.
  642. // TODO: Should the call parameter even exist in that case? There isn't a
  643. // corresponding argument in a `call` instruction.
  644. if (!is_out_param || has_return_slot) {
  645. FormatName(param_id);
  646. out_ << ": ";
  647. }
  648. FormatTypeOfInst(param_id);
  649. }
  650. out_ << close;
  651. }
  652. auto Formatter::FormatCodeBlock(InstBlockId block_id) -> void {
  653. bool elided = false;
  654. for (const InstId inst_id : sem_ir_->inst_blocks().GetOrEmpty(block_id)) {
  655. if (ShouldFormatInst(inst_id)) {
  656. FormatInst(inst_id);
  657. elided = false;
  658. } else if (!elided) {
  659. // When formatting a block, leave a hint that instructions were elided.
  660. Indent();
  661. out_ << "<elided>\n";
  662. elided = true;
  663. }
  664. }
  665. }
  666. auto Formatter::FormatTrailingBlock(InstBlockId block_id) -> void {
  667. out_ << ' ';
  668. OpenBrace();
  669. FormatCodeBlock(block_id);
  670. CloseBrace();
  671. }
  672. auto Formatter::FormatNameScope(NameScopeId id, llvm::StringRef label) -> void {
  673. const auto& scope = sem_ir_->name_scopes().Get(id);
  674. if (scope.entries().empty() && scope.extended_scopes().empty() &&
  675. scope.import_ir_scopes().empty() && !scope.is_cpp_scope() &&
  676. !scope.has_error()) {
  677. // Name scope is empty.
  678. return;
  679. }
  680. if (!label.empty()) {
  681. IndentLabel();
  682. out_ << label;
  683. }
  684. for (auto [name_id, result] : scope.entries()) {
  685. Indent();
  686. out_ << ".";
  687. FormatName(name_id);
  688. switch (result.access_kind()) {
  689. case AccessKind::Public:
  690. break;
  691. case AccessKind::Protected:
  692. out_ << " [protected]";
  693. break;
  694. case AccessKind::Private:
  695. out_ << " [private]";
  696. break;
  697. }
  698. out_ << " = ";
  699. if (result.is_poisoned()) {
  700. out_ << "<poisoned>";
  701. } else {
  702. FormatName(result.is_found() ? result.target_inst_id() : InstId::None);
  703. }
  704. out_ << "\n";
  705. }
  706. for (auto extended_scope_id : scope.extended_scopes()) {
  707. Indent();
  708. out_ << "extend ";
  709. FormatName(extended_scope_id);
  710. out_ << "\n";
  711. }
  712. // This is used to cluster all "Core//prelude/..." imports, but not
  713. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  714. // add or remove an unused prelude file, but is intended to still show the
  715. // existence of indirect imports.
  716. bool has_prelude_components = false;
  717. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  718. auto label = GetImportIRLabel(import_ir_id);
  719. if (label.starts_with("Core//prelude/")) {
  720. if (has_prelude_components) {
  721. // Only print the existence once.
  722. continue;
  723. } else {
  724. has_prelude_components = true;
  725. label = "Core//prelude/...";
  726. }
  727. }
  728. Indent();
  729. out_ << "import " << label << "\n";
  730. }
  731. if (scope.is_cpp_scope()) {
  732. Indent();
  733. out_ << "import Cpp//...\n";
  734. }
  735. if (scope.has_error()) {
  736. Indent();
  737. out_ << "has_error\n";
  738. }
  739. }
  740. auto Formatter::FormatInst(InstId inst_id) -> void {
  741. if (!inst_id.has_value()) {
  742. Indent();
  743. out_ << "none\n";
  744. return;
  745. }
  746. if (!in_terminator_sequence_) {
  747. Indent();
  748. }
  749. auto inst = sem_ir_->insts().GetWithAttachedType(inst_id);
  750. CARBON_KIND_SWITCH(inst) {
  751. case CARBON_KIND(Branch branch): {
  752. out_ << Branch::Kind.ir_name() << " ";
  753. FormatLabel(branch.target_id);
  754. out_ << "\n";
  755. in_terminator_sequence_ = false;
  756. return;
  757. }
  758. case CARBON_KIND(BranchIf branch_if): {
  759. out_ << "if ";
  760. FormatName(branch_if.cond_id);
  761. out_ << " " << Branch::Kind.ir_name() << " ";
  762. FormatLabel(branch_if.target_id);
  763. out_ << " else ";
  764. in_terminator_sequence_ = true;
  765. return;
  766. }
  767. case CARBON_KIND(BranchWithArg branch_with_arg): {
  768. out_ << BranchWithArg::Kind.ir_name() << " ";
  769. FormatLabel(branch_with_arg.target_id);
  770. out_ << "(";
  771. FormatName(branch_with_arg.arg_id);
  772. out_ << ")\n";
  773. in_terminator_sequence_ = false;
  774. return;
  775. }
  776. default: {
  777. FormatInstLhs(inst_id, inst);
  778. out_ << inst.kind().ir_name();
  779. // Add constants for everything except `ImportRefUnloaded`.
  780. if (!inst.Is<ImportRefUnloaded>()) {
  781. pending_constant_value_ =
  782. sem_ir_->constant_values().GetAttached(inst_id);
  783. pending_constant_value_is_self_ =
  784. sem_ir_->constant_values().GetInstIdIfValid(
  785. pending_constant_value_) == inst_id;
  786. }
  787. FormatInstRhs(inst);
  788. // This usually prints the constant, but when `FormatInstRhs` prints it
  789. // first (or for `ImportRefUnloaded`), this does nothing.
  790. FormatPendingConstantValue(AddSpace::Before);
  791. out_ << "\n";
  792. return;
  793. }
  794. }
  795. }
  796. auto Formatter::FormatPendingImportedFrom(AddSpace space_where) -> void {
  797. if (pending_imported_from_.empty()) {
  798. return;
  799. }
  800. if (space_where == AddSpace::Before) {
  801. out_ << ' ';
  802. }
  803. out_ << "[from \"" << FormatEscaped(pending_imported_from_) << "\"]";
  804. if (space_where == AddSpace::After) {
  805. out_ << ' ';
  806. }
  807. pending_imported_from_ = llvm::StringRef();
  808. }
  809. auto Formatter::FormatPendingConstantValue(AddSpace space_where) -> void {
  810. if (pending_constant_value_ == ConstantId::NotConstant) {
  811. return;
  812. }
  813. if (space_where == AddSpace::Before) {
  814. out_ << ' ';
  815. }
  816. out_ << '[';
  817. if (pending_constant_value_.has_value()) {
  818. switch (sem_ir_->constant_values().GetDependence(pending_constant_value_)) {
  819. case ConstantDependence::None:
  820. out_ << "concrete";
  821. break;
  822. case ConstantDependence::PeriodSelf:
  823. out_ << "symbolic_self";
  824. break;
  825. // TODO: Consider renaming this. This will cause a lot of SemIR churn.
  826. case ConstantDependence::Checked:
  827. out_ << "symbolic";
  828. break;
  829. case ConstantDependence::Template:
  830. out_ << "template";
  831. break;
  832. }
  833. if (!pending_constant_value_is_self_) {
  834. out_ << " = ";
  835. FormatConstant(pending_constant_value_);
  836. }
  837. } else {
  838. out_ << pending_constant_value_;
  839. }
  840. out_ << ']';
  841. if (space_where == AddSpace::After) {
  842. out_ << ' ';
  843. }
  844. pending_constant_value_ = ConstantId::NotConstant;
  845. }
  846. auto Formatter::FormatInstLhs(InstId inst_id, Inst inst) -> void {
  847. // Every typed instruction is named, and there are some untyped instructions
  848. // that have names (such as `ImportRefUnloaded`). When there's a typed
  849. // instruction with no name, it means an instruction is incorrectly not named
  850. // -- but should be printed as such.
  851. bool has_name = inst_namer_.has_name(inst_id);
  852. if (!has_name && !inst.kind().has_type()) {
  853. return;
  854. }
  855. FormatName(inst_id);
  856. if (inst.kind().has_type()) {
  857. out_ << ": ";
  858. switch (GetExprCategory(*sem_ir_, inst_id)) {
  859. case ExprCategory::NotExpr:
  860. case ExprCategory::Error:
  861. case ExprCategory::Value:
  862. case ExprCategory::Mixed:
  863. break;
  864. case ExprCategory::DurableRef:
  865. case ExprCategory::EphemeralRef:
  866. out_ << "ref ";
  867. break;
  868. case ExprCategory::Initializing:
  869. out_ << "init ";
  870. break;
  871. }
  872. FormatTypeOfInst(inst_id);
  873. }
  874. out_ << " = ";
  875. }
  876. auto Formatter::FormatInstArgAndKind(Inst::ArgAndKind arg_and_kind) -> void {
  877. GetFormatArgFn(arg_and_kind.kind())(*this, arg_and_kind.value());
  878. }
  879. auto Formatter::FormatInstRhs(Inst inst) -> void {
  880. CARBON_KIND_SWITCH(inst) {
  881. case InstKind::ArrayInit:
  882. case InstKind::StructInit:
  883. case InstKind::TupleInit: {
  884. auto init = inst.As<AnyAggregateInit>();
  885. FormatArgs(init.elements_id);
  886. FormatReturnSlotArg(init.dest_id);
  887. return;
  888. }
  889. case InstKind::ImportRefLoaded:
  890. case InstKind::ImportRefUnloaded:
  891. FormatImportRefRhs(inst.As<AnyImportRef>());
  892. return;
  893. case InstKind::OutParam:
  894. case InstKind::RefParam:
  895. case InstKind::ValueParam: {
  896. auto param = inst.As<AnyParam>();
  897. FormatArgs(param.index);
  898. // Omit pretty_name because it's an implementation detail of
  899. // pretty-printing.
  900. return;
  901. }
  902. case CARBON_KIND(AssociatedConstantDecl decl): {
  903. FormatArgs(decl.assoc_const_id);
  904. llvm::SaveAndRestore scope(scope_,
  905. inst_namer_.GetScopeFor(decl.assoc_const_id));
  906. FormatTrailingBlock(decl.decl_block_id);
  907. return;
  908. }
  909. case CARBON_KIND(SymbolicBinding bind): {
  910. // A SymbolicBinding with no value is a purely symbolic binding, such as
  911. // the `Self` in an interface. Don't print out `none` for the value.
  912. if (bind.value_id.has_value()) {
  913. FormatArgs(bind.entity_name_id, bind.value_id);
  914. } else {
  915. FormatArgs(bind.entity_name_id);
  916. }
  917. return;
  918. }
  919. case CARBON_KIND(BlockArg block): {
  920. out_ << " ";
  921. FormatLabel(block.block_id);
  922. return;
  923. }
  924. case CARBON_KIND(Call call): {
  925. FormatCallRhs(call);
  926. return;
  927. }
  928. case CARBON_KIND(ClassDecl decl): {
  929. FormatDeclRhs(decl.class_id,
  930. sem_ir_->classes().Get(decl.class_id).pattern_block_id,
  931. decl.decl_block_id);
  932. return;
  933. }
  934. case CARBON_KIND(CustomLayoutType type): {
  935. out_ << " {";
  936. auto layout = sem_ir_->custom_layouts().Get(type.layout_id);
  937. out_ << "size=" << layout[CustomLayoutId::SizeIndex]
  938. << ", align=" << layout[CustomLayoutId::AlignIndex];
  939. for (auto [field, offset] : llvm::zip_equal(
  940. sem_ir_->struct_type_fields().Get(type.fields_id),
  941. layout.drop_front(CustomLayoutId::FirstFieldIndex))) {
  942. out_ << ", .";
  943. FormatName(field.name_id);
  944. out_ << "@" << offset << ": ";
  945. FormatInstAsType(field.type_inst_id);
  946. }
  947. out_ << "}";
  948. return;
  949. }
  950. case CARBON_KIND(FloatValue value): {
  951. llvm::SmallVector<char, 16> buffer;
  952. sem_ir_->floats().Get(value.float_id).toString(buffer);
  953. out_ << " " << buffer;
  954. return;
  955. }
  956. case CARBON_KIND(FunctionDecl decl): {
  957. FormatDeclRhs(decl.function_id,
  958. sem_ir_->functions().Get(decl.function_id).pattern_block_id,
  959. decl.decl_block_id);
  960. return;
  961. }
  962. case InstKind::ImportCppDecl: {
  963. FormatImportCppDeclRhs();
  964. return;
  965. }
  966. case CARBON_KIND(ImplDecl decl): {
  967. FormatDeclRhs(decl.impl_id,
  968. sem_ir_->impls().Get(decl.impl_id).pattern_block_id,
  969. decl.decl_block_id);
  970. return;
  971. }
  972. case CARBON_KIND(InitializeFrom init): {
  973. FormatArgs(init.src_id);
  974. FormatReturnSlotArg(init.dest_id);
  975. return;
  976. }
  977. case CARBON_KIND(InstValue inst): {
  978. out_ << ' ';
  979. OpenBrace();
  980. // TODO: Should we use a more compact representation in the case where the
  981. // inst is a SpliceBlock?
  982. FormatInst(inst.inst_id);
  983. CloseBrace();
  984. return;
  985. }
  986. case CARBON_KIND(InterfaceDecl decl): {
  987. FormatDeclRhs(
  988. decl.interface_id,
  989. sem_ir_->interfaces().Get(decl.interface_id).pattern_block_id,
  990. decl.decl_block_id);
  991. return;
  992. }
  993. case CARBON_KIND(IntValue value): {
  994. out_ << " ";
  995. sem_ir_->ints()
  996. .Get(value.int_id)
  997. .print(out_, sem_ir_->types().IsSignedInt(value.type_id));
  998. return;
  999. }
  1000. case CARBON_KIND(NameBindingDecl name): {
  1001. FormatTrailingBlock(name.pattern_block_id);
  1002. return;
  1003. }
  1004. case CARBON_KIND(NamedConstraintDecl decl): {
  1005. FormatDeclRhs(decl.named_constraint_id,
  1006. sem_ir_->named_constraints()
  1007. .Get(decl.named_constraint_id)
  1008. .pattern_block_id,
  1009. decl.decl_block_id);
  1010. return;
  1011. }
  1012. case CARBON_KIND(Namespace ns): {
  1013. if (ns.import_id.has_value()) {
  1014. FormatArgs(ns.import_id, ns.name_scope_id);
  1015. } else {
  1016. FormatArgs(ns.name_scope_id);
  1017. }
  1018. return;
  1019. }
  1020. case CARBON_KIND(RequireImplsDecl decl): {
  1021. FormatArgs(decl.require_impls_id);
  1022. llvm::SaveAndRestore scope(
  1023. scope_, inst_namer_.GetScopeFor(decl.require_impls_id));
  1024. FormatRequireImpls(decl.require_impls_id);
  1025. FormatTrailingBlock(decl.decl_block_id);
  1026. return;
  1027. }
  1028. case CARBON_KIND(ReturnExpr ret): {
  1029. FormatArgs(ret.expr_id);
  1030. if (ret.dest_id.has_value()) {
  1031. FormatReturnSlotArg(ret.dest_id);
  1032. }
  1033. return;
  1034. }
  1035. case CARBON_KIND(ReturnSlot ret): {
  1036. // Omit inst.type_inst_id because it's not semantically significant.
  1037. FormatArgs(ret.storage_id);
  1038. return;
  1039. }
  1040. case InstKind::ReturnSlotPattern:
  1041. // No-op because type_id is the only semantically significant field,
  1042. // and it's handled separately.
  1043. return;
  1044. case CARBON_KIND(SpliceBlock splice): {
  1045. FormatArgs(splice.result_id);
  1046. FormatTrailingBlock(splice.block_id);
  1047. return;
  1048. }
  1049. case CARBON_KIND(StructType struct_type): {
  1050. out_ << " {";
  1051. llvm::ListSeparator sep;
  1052. for (auto field :
  1053. sem_ir_->struct_type_fields().Get(struct_type.fields_id)) {
  1054. out_ << sep << ".";
  1055. FormatName(field.name_id);
  1056. out_ << ": ";
  1057. FormatInstAsType(field.type_inst_id);
  1058. }
  1059. out_ << "}";
  1060. return;
  1061. }
  1062. case CARBON_KIND(WhereExpr where): {
  1063. FormatArgs(where.period_self_id);
  1064. FormatTrailingBlock(where.requirements_id);
  1065. return;
  1066. }
  1067. default:
  1068. FormatInstRhsDefault(inst);
  1069. return;
  1070. }
  1071. }
  1072. auto Formatter::FormatInstRhsDefault(Inst inst) -> void {
  1073. auto arg0 = inst.arg0_and_kind();
  1074. if (arg0.kind() == IdKind::None) {
  1075. return;
  1076. }
  1077. out_ << " ";
  1078. FormatInstArgAndKind(arg0);
  1079. auto arg1 = inst.arg1_and_kind();
  1080. if (arg1.kind() == IdKind::None) {
  1081. return;
  1082. }
  1083. // Several instructions have a second operand that's a specific ID. We
  1084. // don't include it in the argument list if there is no corresponding
  1085. // specific, that is, when we're not in a generic context.
  1086. if (auto arg1_specific_id = arg1.TryAs<SpecificId>();
  1087. arg1_specific_id && !arg1_specific_id->has_value()) {
  1088. return;
  1089. }
  1090. out_ << ", ";
  1091. FormatInstArgAndKind(arg1);
  1092. }
  1093. auto Formatter::FormatCallRhs(Call inst) -> void {
  1094. out_ << " ";
  1095. FormatArg(inst.callee_id);
  1096. if (!inst.args_id.has_value()) {
  1097. out_ << "(<none>)";
  1098. return;
  1099. }
  1100. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  1101. auto return_info = ReturnTypeInfo::ForType(*sem_ir_, inst.type_id);
  1102. if (!return_info.is_valid()) {
  1103. out_ << "(<invalid return info>)";
  1104. return;
  1105. }
  1106. bool has_return_slot = return_info.has_return_slot();
  1107. InstId return_slot_arg_id = InstId::None;
  1108. if (has_return_slot) {
  1109. return_slot_arg_id = args.consume_back();
  1110. }
  1111. llvm::ListSeparator sep;
  1112. out_ << '(';
  1113. for (auto inst_id : args) {
  1114. out_ << sep;
  1115. FormatArg(inst_id);
  1116. }
  1117. out_ << ')';
  1118. if (has_return_slot) {
  1119. FormatReturnSlotArg(return_slot_arg_id);
  1120. }
  1121. }
  1122. auto Formatter::FormatImportCppDeclRhs() -> void {
  1123. out_ << " ";
  1124. OpenBrace();
  1125. for (const Parse::Tree::PackagingNames& import :
  1126. sem_ir_->parse_tree().imports()) {
  1127. if (import.package_id != PackageNameId::Cpp) {
  1128. continue;
  1129. }
  1130. Indent();
  1131. out_ << "import Cpp";
  1132. if (import.library_id.has_value()) {
  1133. out_ << " \""
  1134. << FormatEscaped(
  1135. sem_ir_->string_literal_values().Get(import.library_id))
  1136. << "\"";
  1137. } else if (import.inline_body_id.has_value()) {
  1138. out_ << " inline";
  1139. }
  1140. out_ << "\n";
  1141. }
  1142. CloseBrace();
  1143. }
  1144. auto Formatter::FormatImportRefRhs(AnyImportRef inst) -> void {
  1145. out_ << " ";
  1146. auto import_ir_inst = sem_ir_->import_ir_insts().Get(inst.import_ir_inst_id);
  1147. FormatArg(import_ir_inst.ir_id());
  1148. out_ << ", ";
  1149. if (inst.entity_name_id.has_value()) {
  1150. // Prefer to show the entity name when possible.
  1151. FormatArg(inst.entity_name_id);
  1152. } else {
  1153. // Show a name based on the location when possible, or the numeric
  1154. // instruction as a last resort.
  1155. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  1156. auto loc_id =
  1157. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  1158. switch (loc_id.kind()) {
  1159. case LocId::Kind::None: {
  1160. out_ << import_ir_inst.inst_id() << " [no loc]";
  1161. break;
  1162. }
  1163. case LocId::Kind::ImportIRInstId: {
  1164. // TODO: Probably don't want to format each indirection, but maybe
  1165. // reuse GetCanonicalImportIRInst?
  1166. out_ << import_ir_inst.inst_id() << " [indirect]";
  1167. break;
  1168. }
  1169. case LocId::Kind::NodeId: {
  1170. // Formats a NodeId from the import.
  1171. const auto& tree = import_ir.sem_ir->parse_tree();
  1172. auto token = tree.node_token(loc_id.node_id());
  1173. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1174. << tree.tokens().GetColumnNumber(token);
  1175. break;
  1176. }
  1177. case LocId::Kind::InstId:
  1178. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1179. }
  1180. }
  1181. out_ << ", "
  1182. << (inst.kind == InstKind::ImportRefLoaded ? "loaded" : "unloaded");
  1183. }
  1184. auto Formatter::FormatRequireImpls(RequireImplsId id) -> void {
  1185. out_ << ' ';
  1186. const auto& require = sem_ir_->require_impls().Get(id);
  1187. OpenBrace();
  1188. Indent();
  1189. out_ << "require ";
  1190. FormatArg(require.self_id);
  1191. out_ << " impls ";
  1192. FormatArg(require.facet_type_id);
  1193. out_ << "\n";
  1194. CloseBrace();
  1195. }
  1196. auto Formatter::FormatRequireImplsBlock(RequireImplsBlockId block_id) -> void {
  1197. IndentLabel();
  1198. out_ << "!requires:\n";
  1199. if (!block_id.has_value()) {
  1200. return;
  1201. }
  1202. for (auto require_impls_id : sem_ir_->require_impls_blocks().Get(block_id)) {
  1203. Indent();
  1204. FormatArg(require_impls_id);
  1205. FormatRequireImpls(require_impls_id);
  1206. out_ << "\n";
  1207. }
  1208. }
  1209. auto Formatter::FormatArg(EntityNameId id) -> void {
  1210. if (!id.has_value()) {
  1211. out_ << "_";
  1212. return;
  1213. }
  1214. const auto& info = sem_ir_->entity_names().Get(id);
  1215. FormatName(info.name_id);
  1216. if (info.bind_index().has_value()) {
  1217. out_ << ", " << info.bind_index().index;
  1218. }
  1219. if (info.is_template) {
  1220. out_ << ", template";
  1221. }
  1222. }
  1223. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1224. const auto& info = sem_ir_->facet_types().Get(id);
  1225. // Nothing output to indicate that this is a facet type since this is only
  1226. // used as the argument to a `facet_type` instruction.
  1227. out_ << "<";
  1228. llvm::ListSeparator sep(" & ");
  1229. if (info.extend_constraints.empty() &&
  1230. info.extend_named_constraints.empty()) {
  1231. out_ << "type";
  1232. } else {
  1233. for (auto extend : info.extend_constraints) {
  1234. out_ << sep;
  1235. FormatName(extend.interface_id);
  1236. if (extend.specific_id.has_value()) {
  1237. out_ << ", ";
  1238. FormatName(extend.specific_id);
  1239. }
  1240. }
  1241. for (auto extend : info.extend_named_constraints) {
  1242. out_ << sep;
  1243. FormatName(extend.named_constraint_id);
  1244. if (extend.specific_id.has_value()) {
  1245. out_ << ", ";
  1246. FormatName(extend.specific_id);
  1247. }
  1248. }
  1249. }
  1250. if (info.other_requirements || !info.builtin_constraint_mask.empty() ||
  1251. !info.self_impls_constraints.empty() ||
  1252. !info.rewrite_constraints.empty()) {
  1253. out_ << " where ";
  1254. llvm::ListSeparator and_sep(" and ");
  1255. if (!info.self_impls_constraints.empty() ||
  1256. !info.self_impls_named_constraints.empty()) {
  1257. out_ << and_sep << ".Self impls ";
  1258. llvm::ListSeparator amp_sep(" & ");
  1259. for (auto self_impls : info.self_impls_constraints) {
  1260. out_ << amp_sep;
  1261. FormatName(self_impls.interface_id);
  1262. if (self_impls.specific_id.has_value()) {
  1263. out_ << ", ";
  1264. FormatName(self_impls.specific_id);
  1265. }
  1266. }
  1267. for (auto self_impls : info.self_impls_named_constraints) {
  1268. out_ << amp_sep;
  1269. FormatName(self_impls.named_constraint_id);
  1270. if (self_impls.specific_id.has_value()) {
  1271. out_ << ", ";
  1272. FormatName(self_impls.specific_id);
  1273. }
  1274. }
  1275. }
  1276. for (auto rewrite : info.rewrite_constraints) {
  1277. out_ << and_sep;
  1278. FormatArg(rewrite.lhs_id);
  1279. out_ << " = ";
  1280. FormatArg(rewrite.rhs_id);
  1281. }
  1282. if (info.builtin_constraint_mask.HasAnyOf(
  1283. BuiltinConstraintMask::TypeCanDestroy)) {
  1284. out_ << and_sep << ".Self impls <CanDestroy>";
  1285. }
  1286. if (info.other_requirements) {
  1287. out_ << and_sep << "TODO";
  1288. }
  1289. }
  1290. out_ << ">";
  1291. }
  1292. auto Formatter::FormatArg(ImportIRId id) -> void {
  1293. if (id.has_value()) {
  1294. out_ << GetImportIRLabel(id);
  1295. } else {
  1296. out_ << id;
  1297. }
  1298. }
  1299. auto Formatter::FormatArg(IntId id) -> void {
  1300. // We don't know the signedness to use here. Default to unsigned.
  1301. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  1302. }
  1303. auto Formatter::FormatArg(NameScopeId id) -> void {
  1304. OpenBrace();
  1305. FormatNameScope(id);
  1306. CloseBrace();
  1307. }
  1308. auto Formatter::FormatArg(InstBlockId id) -> void {
  1309. if (!id.has_value()) {
  1310. out_ << "invalid";
  1311. return;
  1312. }
  1313. out_ << '(';
  1314. llvm::ListSeparator sep;
  1315. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1316. out_ << sep;
  1317. FormatArg(inst_id);
  1318. }
  1319. out_ << ')';
  1320. }
  1321. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1322. FormatArg(static_cast<InstBlockId>(id));
  1323. }
  1324. auto Formatter::FormatArg(RealId id) -> void {
  1325. // TODO: Format with a `.` when the exponent is near zero.
  1326. const auto& real = sem_ir_->reals().Get(id);
  1327. real.mantissa.print(out_, /*isSigned=*/false);
  1328. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1329. }
  1330. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1331. out_ << '"'
  1332. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1333. /*use_hex_escapes=*/true)
  1334. << '"';
  1335. }
  1336. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1337. out_ << " to ";
  1338. FormatArg(dest_id);
  1339. }
  1340. auto Formatter::FormatName(NameId id) -> void {
  1341. out_ << sem_ir_->names().GetFormatted(id);
  1342. }
  1343. auto Formatter::FormatName(InstId id) -> void {
  1344. if (id.has_value()) {
  1345. IncludeChunkInOutput(tentative_inst_chunks_.Get(id));
  1346. }
  1347. out_ << inst_namer_.GetNameFor(scope_, id);
  1348. }
  1349. auto Formatter::FormatName(SpecificId id) -> void {
  1350. const auto& specific = sem_ir_->specifics().Get(id);
  1351. FormatName(specific.generic_id);
  1352. FormatArg(specific.args_id);
  1353. }
  1354. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1355. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1356. FormatName(interface.interface_id);
  1357. if (interface.specific_id.has_value()) {
  1358. out_ << ", ";
  1359. FormatArg(interface.specific_id);
  1360. }
  1361. }
  1362. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1363. out_ << inst_namer_.GetLabelFor(scope_, id);
  1364. }
  1365. auto Formatter::FormatConstant(ConstantId id) -> void {
  1366. if (!id.has_value()) {
  1367. out_ << "<not constant>";
  1368. return;
  1369. }
  1370. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1371. FormatName(inst_id);
  1372. // For an attached constant, also list the unattached constant.
  1373. if (id.is_symbolic() && sem_ir_->constant_values()
  1374. .GetSymbolicConstant(id)
  1375. .generic_id.has_value()) {
  1376. // TODO: Skip printing this if it's the same as `inst_id`.
  1377. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1378. out_ << " (";
  1379. FormatName(unattached_inst_id);
  1380. out_ << ")";
  1381. }
  1382. }
  1383. auto Formatter::FormatInstAsType(InstId id) -> void {
  1384. if (!id.has_value()) {
  1385. out_ << "invalid";
  1386. return;
  1387. }
  1388. // Types are formatted in the `constants` scope because they typically refer
  1389. // to constants.
  1390. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1391. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1392. const_id.has_value()) {
  1393. FormatConstant(const_id);
  1394. } else {
  1395. // Type instruction didn't have a constant value. Fall back to printing
  1396. // the instruction name.
  1397. FormatArg(id);
  1398. }
  1399. }
  1400. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1401. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1402. if (!type_id.has_value()) {
  1403. out_ << "invalid";
  1404. return;
  1405. }
  1406. // Types are formatted in the `constants` scope because they typically refer
  1407. // to constants.
  1408. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1409. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1410. }
  1411. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1412. CARBON_CHECK(id.has_value(),
  1413. "Callers are responsible for checking `id.has_value`");
  1414. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1415. CARBON_CHECK(import_ir.library_id().has_value());
  1416. auto package_id = import_ir.package_id();
  1417. llvm::StringRef package_name =
  1418. package_id.AsIdentifierId().has_value()
  1419. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1420. : package_id.AsSpecialName();
  1421. llvm::StringRef library_name =
  1422. (import_ir.library_id() != LibraryNameId::Default)
  1423. ? import_ir.string_literal_values().Get(
  1424. import_ir.library_id().AsStringLiteralValueId())
  1425. : "default";
  1426. return llvm::formatv("{0}//{1}", package_name, library_name);
  1427. }
  1428. } // namespace Carbon::SemIR
  1429. // NOLINTEND(misc-no-recursion)