formatter.h 18 KB

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