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