formatter.h 17 KB

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