formatter.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. #ifndef CARBON_TOOLCHAIN_SEM_IR_FORMATTER_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_FORMATTER_H_
  6. #include <concepts>
  7. #include "llvm/Support/raw_ostream.h"
  8. #include "toolchain/parse/tree_and_subtrees.h"
  9. #include "toolchain/sem_ir/file.h"
  10. #include "toolchain/sem_ir/inst_namer.h"
  11. namespace Carbon::SemIR {
  12. // Formatter for printing textual Semantics IR.
  13. class Formatter {
  14. public:
  15. explicit Formatter(const File* sem_ir,
  16. Parse::GetTreeAndSubtreesFn get_tree_and_subtrees,
  17. llvm::ArrayRef<bool> include_ir_in_dumps,
  18. bool use_dump_sem_ir_ranges);
  19. // Prints the SemIR into an internal buffer. Must only be called once.
  20. //
  21. // We first print top-level scopes (constants, imports, and file) then
  22. // entities (types and functions). The ordering is based on references:
  23. //
  24. // - constants can have internal references.
  25. // - imports can refer to constants.
  26. // - file can refer to constants and imports, and also entities.
  27. // - Entities are difficult to order (forward declarations may lead to
  28. // circular references), and so are simply grouped by type.
  29. //
  30. // When formatting constants and imports, we use `OutputChunks` to only print
  31. // entities which are referenced. For example, imports speculatively create
  32. // constants which may never be referenced, or for which the referencing
  33. // instruction may be hidden and we normally hide those. See `OutputChunk` for
  34. // additional information.
  35. //
  36. // Beyond `OutputChunk`, `ShouldFormatEntity` and `ShouldFormatInst` can also
  37. // hide instructions. These interact because an hidden instruction means its
  38. // references are unused for `OutputChunk` visibility.
  39. auto Format() -> void;
  40. // Write buffered output to the given stream. `Format` must be called first.
  41. auto Write(llvm::raw_ostream& out) -> void;
  42. private:
  43. enum class AddSpace : bool { Before, After };
  44. // A chunk of the buffered output. Constants and imports are buffered as
  45. // `OutputChunk`s until we reach the end of formatting so that we can decide
  46. // whether to include them based on whether they are referenced.
  47. //
  48. // When `FormatName` is called for an instruction, it's considered referenced;
  49. // if that instruction is in an `OutputChunk`, it and all of its dependencies
  50. // will be marked for printing by `Write`. If that doesn't occur by the end,
  51. // it will be omitted.
  52. struct OutputChunk {
  53. // Whether this chunk is known to be included in the output.
  54. bool include_in_output;
  55. // The textual contents of this chunk.
  56. std::string chunk = std::string();
  57. // Indices in `ouput_chunks_` that should be included in the output if this
  58. // one is.
  59. llvm::SmallVector<size_t> dependencies = {};
  60. };
  61. // All formatted output within the scope of this object is redirected to a
  62. // new tentative `OutputChunk`. The new chunk will depend on
  63. // `parent_chunk_index`.
  64. struct TentativeOutputScope {
  65. explicit TentativeOutputScope(Formatter& f, size_t parent_chunk_index)
  66. : formatter(f) {
  67. // If our parent is not known to be included, create a new chunk and
  68. // include it only if the parent is later found to be used.
  69. if (!f.output_chunks_[parent_chunk_index].include_in_output) {
  70. index = formatter.AddChunk(false);
  71. f.output_chunks_[parent_chunk_index].dependencies.push_back(index);
  72. }
  73. }
  74. ~TentativeOutputScope() {
  75. auto next_index = formatter.AddChunk(true);
  76. CARBON_CHECK(next_index == index + 1, "Nested TentativeOutputScope");
  77. }
  78. Formatter& formatter;
  79. size_t index;
  80. };
  81. // Fills `node_parents_` with parent information. Called at most once during
  82. // construction.
  83. auto ComputeNodeParents() -> void;
  84. // Flushes the buffered output to the current chunk.
  85. auto FlushChunk() -> void;
  86. // Adds a new chunk to the output. Does not flush existing output, so should
  87. // only be called if there is no buffered output.
  88. auto AddChunkNoFlush(bool include_in_output) -> size_t;
  89. // Flushes the current chunk and add a new chunk to the output.
  90. auto AddChunk(bool include_in_output) -> size_t;
  91. // Marks the given chunk as being included in the output if the current chunk
  92. // is.
  93. auto IncludeChunkInOutput(size_t chunk) -> void;
  94. // Returns true if the instruction should be included according to its
  95. // originating IR. Typically `ShouldFormatEntity` should be used instead.
  96. auto ShouldIncludeInstByIR(InstId inst_id) -> bool;
  97. // Determines whether the specified entity should be included in the formatted
  98. // output. `is_definition_start` should indicate whether, if `decl_id`'s
  99. // `LocId` is a `NodeId`, it is expected to be a `DefinitionStart` kind.
  100. auto ShouldFormatEntity(InstId decl_id, bool is_definition_start) -> bool;
  101. auto ShouldFormatEntity(const EntityWithParamsBase& entity) -> bool;
  102. // Determines whether a single instruction should be included in the
  103. // formatted output.
  104. auto ShouldFormatInst(InstId inst_id) -> bool;
  105. // Begins a braced block. Writes an open brace, and prepares to insert a
  106. // newline after it if the braced block is non-empty.
  107. auto OpenBrace() -> void;
  108. // Ends a braced block by writing a close brace.
  109. auto CloseBrace() -> void;
  110. auto Semicolon() -> void;
  111. // Adds beginning-of-line indentation. If we're at the start of a braced
  112. // block, first starts a new line.
  113. auto Indent(int offset = 0) -> void;
  114. // Adds beginning-of-label indentation. This is one level less than normal
  115. // indentation. Labels also get a preceding blank line unless they're at the
  116. // start of a block.
  117. auto IndentLabel() -> void;
  118. // Formats a top-level scope, and any of the instructions in that scope that
  119. // are used.
  120. auto FormatScopeIfUsed(InstNamer::ScopeId scope_id,
  121. llvm::ArrayRef<InstId> block) -> void;
  122. // Formats a full class.
  123. auto FormatClass(ClassId id) -> void;
  124. // Formats a full interface.
  125. auto FormatInterface(InterfaceId id) -> void;
  126. // Formats an associated constant entity.
  127. auto FormatAssociatedConstant(AssociatedConstantId id) -> void;
  128. // Formats a full impl.
  129. auto FormatImpl(ImplId id) -> void;
  130. // Formats a full function.
  131. auto FormatFunction(FunctionId id) -> void;
  132. // Helper for FormatSpecific to print regions.
  133. auto FormatSpecificRegion(const Generic& generic, const Specific& specific,
  134. GenericInstIndex::Region region,
  135. llvm::StringRef region_name) -> void;
  136. // Formats a full specific.
  137. auto FormatSpecific(SpecificId id) -> void;
  138. // Handles generic-specific setup for FormatEntityStart.
  139. auto FormatGenericStart(llvm::StringRef entity_kind, GenericId generic_id)
  140. -> void;
  141. // Provides common formatting for entities, paired with FormatEntityEnd.
  142. template <typename IdT>
  143. auto FormatEntityStart(llvm::StringRef entity_kind,
  144. InstId first_owning_decl_id, GenericId generic_id,
  145. IdT entity_id) -> void;
  146. template <typename IdT>
  147. auto FormatEntityStart(llvm::StringRef entity_kind,
  148. const EntityWithParamsBase& entity, IdT entity_id)
  149. -> void;
  150. // Provides common formatting for entities, paired with FormatEntityStart.
  151. auto FormatEntityEnd(GenericId generic_id) -> void;
  152. // Formats parameters, eliding them completely if they're empty. Wraps input
  153. // parameters in parentheses. Formats output parameter as a return type.
  154. auto FormatParamList(InstBlockId params_id, bool has_return_slot = false)
  155. -> void;
  156. // Prints instructions for a code block.
  157. auto FormatCodeBlock(InstBlockId block_id) -> void;
  158. // Prints a code block with braces, intended to be used trailing after other
  159. // content on the same line. If non-empty, instructions are on separate lines.
  160. auto FormatTrailingBlock(InstBlockId block_id) -> void;
  161. // Prints the contents of a name scope, with an optional label.
  162. auto FormatNameScope(NameScopeId id, llvm::StringRef label = "") -> void;
  163. auto FormatInst(InstId inst_id, Inst inst) -> void;
  164. // Don't print a constant for ImportRefUnloaded.
  165. auto FormatInst(InstId inst_id, ImportRefUnloaded inst) -> void;
  166. // Prints a single instruction. This typically dispatches to one of the
  167. // `FormatInst` overloads, based on a specific instruction type.
  168. //
  169. // While there is default formatting behavior, we do have overloads when
  170. // special behavior is required, although typically of functions called by
  171. // `FormatInst` rather than `FormatInst` itself. For example, `FormatInstRhs`
  172. // is frequently overloaded because the default argument formatting often
  173. // isn't what we want for instructions.
  174. auto FormatInst(InstId inst_id) -> void;
  175. template <typename InstT>
  176. auto FormatInst(InstId inst_id, InstT inst) -> void;
  177. // If there is a pending library name that the current instruction was
  178. // imported from, print it now and clear it out.
  179. auto FormatPendingImportedFrom(AddSpace space_where) -> void;
  180. // If there is a pending constant value attached to the current instruction,
  181. // print it now and clear it out. The constant value gets printed before the
  182. // first braced block argument, or at the end of the instruction if there are
  183. // no such arguments.
  184. auto FormatPendingConstantValue(AddSpace space_where) -> void;
  185. auto FormatInstLhs(InstId inst_id, Inst inst) -> void;
  186. // Format ImportCppDecl name.
  187. auto FormatInstLhs(InstId inst_id, ImportCppDecl inst) -> void;
  188. // Format ImportDecl with its name.
  189. auto FormatInstLhs(InstId inst_id, ImportDecl inst) -> void;
  190. // Print ImportRefUnloaded with type-like semantics even though it lacks a
  191. // type_id.
  192. auto FormatInstLhs(InstId inst_id, ImportRefUnloaded inst) -> void;
  193. // Format ImplWitnessTable with its name even though it lacks a type_id.
  194. auto FormatInstLhs(InstId inst_id, ImplWitnessTable inst) -> void;
  195. template <typename InstT>
  196. auto FormatInstRhs(InstT inst) -> void;
  197. auto FormatInstRhs(BindSymbolicName inst) -> void;
  198. auto FormatInstRhs(BlockArg inst) -> void;
  199. auto FormatInstRhs(Namespace inst) -> void;
  200. auto FormatInst(InstId inst_id, BranchIf inst) -> void;
  201. auto FormatInst(InstId inst_id, BranchWithArg inst) -> void;
  202. auto FormatInst(InstId inst_id, Branch inst) -> void;
  203. auto FormatInstRhs(Call inst) -> void;
  204. auto FormatInstRhs(ArrayInit inst) -> void;
  205. auto FormatInstRhs(InitializeFrom inst) -> void;
  206. auto FormatInstRhs(ValueParam inst) -> void;
  207. auto FormatInstRhs(RefParam inst) -> void;
  208. auto FormatInstRhs(OutParam inst) -> void;
  209. auto FormatInstRhs(ReturnExpr ret) -> void;
  210. auto FormatInstRhs(ReturnSlot inst) -> void;
  211. auto FormatInstRhs(ReturnSlotPattern inst) -> void;
  212. auto FormatInstRhs(StructInit init) -> void;
  213. auto FormatInstRhs(TupleInit init) -> void;
  214. auto FormatInstRhs(FunctionDecl inst) -> void;
  215. auto FormatInstRhs(ClassDecl inst) -> void;
  216. auto FormatInstRhs(ImplDecl inst) -> void;
  217. auto FormatInstRhs(InterfaceDecl inst) -> void;
  218. auto FormatInstRhs(AssociatedConstantDecl inst) -> void;
  219. auto FormatInstRhs(IntValue inst) -> void;
  220. auto FormatInstRhs(FloatLiteral inst) -> void;
  221. // Format the metadata in File for `import Cpp`.
  222. auto FormatInstRhs(ImportCppDecl inst) -> void;
  223. auto FormatImportRefRhs(ImportIRInstId import_ir_inst_id,
  224. EntityNameId entity_name_id,
  225. llvm::StringLiteral loaded_label) -> void;
  226. auto FormatInstRhs(ImportRefLoaded inst) -> void;
  227. auto FormatInstRhs(ImportRefUnloaded inst) -> void;
  228. auto FormatInstRhs(InstValue inst) -> void;
  229. auto FormatInstRhs(NameBindingDecl inst) -> void;
  230. auto FormatInstRhs(SpliceBlock inst) -> void;
  231. auto FormatInstRhs(WhereExpr inst) -> void;
  232. auto FormatInstRhs(StructType inst) -> void;
  233. auto FormatArgs() -> void {}
  234. template <typename... Args>
  235. auto FormatArgs(Args... args) -> void {
  236. out_ << ' ';
  237. llvm::ListSeparator sep;
  238. ((out_ << sep, FormatArg(args)), ...);
  239. }
  240. // FormatArg variants handling printing instruction arguments. Several things
  241. // provide equivalent behavior with `FormatName`, so we provide that as the
  242. // default.
  243. template <typename IdT>
  244. auto FormatArg(IdT id) -> void {
  245. FormatName(id);
  246. }
  247. auto FormatArg(BoolValue v) -> void { out_ << v; }
  248. auto FormatArg(EntityNameId id) -> void;
  249. auto FormatArg(FacetTypeId id) -> void;
  250. auto FormatArg(IntKind k) -> void { k.Print(out_); }
  251. auto FormatArg(FloatKind k) -> void { k.Print(out_); }
  252. auto FormatArg(ImportIRId id) -> void;
  253. auto FormatArg(IntId id) -> void;
  254. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  255. auto FormatArg(CallParamIndex index) -> void { out_ << index; }
  256. auto FormatArg(NameScopeId id) -> void;
  257. auto FormatArg(InstBlockId id) -> void;
  258. auto FormatArg(AbsoluteInstBlockId id) -> void;
  259. auto FormatArg(RealId id) -> void;
  260. auto FormatArg(StringLiteralValueId id) -> void;
  261. auto FormatReturnSlotArg(InstId dest_id) -> void;
  262. // `FormatName` is used when we need the name from an id. Most id types use
  263. // equivalent name formatting from InstNamer, although there are a few special
  264. // formats below.
  265. template <typename IdT>
  266. // Force `InstId` children to use the `InstId` overload.
  267. requires(!std::derived_from<IdT, InstId>)
  268. auto FormatName(IdT id) -> void {
  269. out_ << inst_namer_.GetNameFor(id);
  270. }
  271. auto FormatName(NameId id) -> void;
  272. auto FormatName(InstId id) -> void;
  273. auto FormatName(SpecificId id) -> void;
  274. auto FormatName(SpecificInterfaceId id) -> void;
  275. auto FormatLabel(InstBlockId id) -> void;
  276. auto FormatConstant(ConstantId id) -> void;
  277. auto FormatInstAsType(InstId id) -> void;
  278. auto FormatTypeOfInst(InstId id) -> void;
  279. // Returns the label for the indicated IR.
  280. auto GetImportIRLabel(ImportIRId id) -> std::string;
  281. const File* sem_ir_;
  282. InstNamer inst_namer_;
  283. Parse::GetTreeAndSubtreesFn get_tree_and_subtrees_;
  284. // For each CheckIRId, whether entities from it should be formatted.
  285. llvm::ArrayRef<bool> include_ir_in_dumps_;
  286. // Whether to use ranges when dumping, or to dump the full SemIR.
  287. bool use_dump_sem_ir_ranges_;
  288. // The output stream buffer.
  289. std::string buffer_;
  290. // The output stream.
  291. llvm::raw_string_ostream out_ = llvm::raw_string_ostream(buffer_);
  292. // Chunks of output text that we have created so far.
  293. llvm::SmallVector<OutputChunk> output_chunks_;
  294. // The current scope that we are formatting within. References to names in
  295. // this scope will not have a `@scope.` prefix added.
  296. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  297. // Whether we are formatting in a terminator sequence, that is, a sequence of
  298. // branches at the end of a block. The entirety of a terminator sequence is
  299. // formatted on a single line, despite being multiple instructions.
  300. bool in_terminator_sequence_ = false;
  301. // The indent depth to use for new instructions.
  302. int indent_ = 0;
  303. // Whether we are currently formatting immediately after an open brace. If so,
  304. // a newline will be inserted before the next line indent.
  305. bool after_open_brace_ = false;
  306. // The constant value of the current instruction, if it has one that has not
  307. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  308. // there is nothing to print.
  309. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  310. // Whether `pending_constant_value_`'s instruction is the same as the
  311. // instruction currently being printed. If true, only the phase of the
  312. // constant is printed, and the value is omitted.
  313. bool pending_constant_value_is_self_ = false;
  314. // The name of the IR file from which the current entity was imported, if it
  315. // was imported and no file has been printed yet. This is printed before the
  316. // first open brace or the semicolon in the entity declaration.
  317. llvm::StringRef pending_imported_from_;
  318. // Indexes of chunks of output that should be included when an instruction is
  319. // referenced, indexed by the instruction's index. This is resized in advance
  320. // to the correct size.
  321. llvm::SmallVector<size_t, 0> tentative_inst_chunks_;
  322. // Maps nodes to their parents. Only set when dump ranges are in use, because
  323. // the parents aren't used otherwise.
  324. llvm::SmallVector<Parse::NodeId> node_parents_;
  325. };
  326. template <typename IdT>
  327. auto Formatter::FormatEntityStart(llvm::StringRef entity_kind,
  328. InstId first_owning_decl_id,
  329. GenericId generic_id, IdT entity_id) -> void {
  330. // If this entity was imported from a different IR, annotate the name of
  331. // that IR in the output before the `{` or `;`.
  332. if (first_owning_decl_id.has_value()) {
  333. auto import_ir_inst_id =
  334. sem_ir_->insts().GetImportSource(first_owning_decl_id);
  335. if (import_ir_inst_id.has_value()) {
  336. auto import_ir_id =
  337. sem_ir_->import_ir_insts().Get(import_ir_inst_id).ir_id();
  338. const auto* import_file = sem_ir_->import_irs().Get(import_ir_id).sem_ir;
  339. pending_imported_from_ = import_file->filename();
  340. }
  341. }
  342. if (generic_id.has_value()) {
  343. FormatGenericStart(entity_kind, generic_id);
  344. }
  345. out_ << "\n";
  346. after_open_brace_ = false;
  347. Indent();
  348. out_ << entity_kind;
  349. // If there's a generic, it will have attached the name. Otherwise, add the
  350. // name here.
  351. if (!generic_id.has_value()) {
  352. out_ << " ";
  353. FormatName(entity_id);
  354. }
  355. }
  356. template <typename IdT>
  357. auto Formatter::FormatEntityStart(llvm::StringRef entity_kind,
  358. const EntityWithParamsBase& entity,
  359. IdT entity_id) -> void {
  360. FormatEntityStart(entity_kind, entity.first_owning_decl_id, entity.generic_id,
  361. entity_id);
  362. }
  363. template <typename InstT>
  364. auto Formatter::FormatInst(InstId inst_id, InstT inst) -> void {
  365. Indent();
  366. FormatInstLhs(inst_id, inst);
  367. out_ << InstT::Kind.ir_name();
  368. pending_constant_value_ = sem_ir_->constant_values().GetAttached(inst_id);
  369. pending_constant_value_is_self_ = sem_ir_->constant_values().GetInstIdIfValid(
  370. pending_constant_value_) == inst_id;
  371. FormatInstRhs(inst);
  372. FormatPendingConstantValue(AddSpace::Before);
  373. out_ << "\n";
  374. }
  375. template <typename InstT>
  376. auto Formatter::FormatInstRhs(InstT inst) -> void {
  377. // By default, an instruction has a comma-separated argument list.
  378. using Info = Internal::InstLikeTypeInfo<InstT>;
  379. if constexpr (Info::NumArgs == 2) {
  380. // Several instructions have a second operand that's a specific ID. We
  381. // don't include it in the argument list if there is no corresponding
  382. // specific, that is, when we're not in a generic context.
  383. if constexpr (std::is_same_v<typename Info::template ArgType<1>,
  384. SpecificId>) {
  385. if (!Info::template Get<1>(inst).has_value()) {
  386. FormatArgs(Info::template Get<0>(inst));
  387. return;
  388. }
  389. }
  390. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  391. } else if constexpr (Info::NumArgs == 1) {
  392. FormatArgs(Info::template Get<0>(inst));
  393. } else {
  394. FormatArgs();
  395. }
  396. }
  397. } // namespace Carbon::SemIR
  398. #endif // CARBON_TOOLCHAIN_SEM_IR_FORMATTER_H_