formatter.h 18 KB

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