emitter.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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_DIAGNOSTICS_EMITTER_H_
  5. #define CARBON_TOOLCHAIN_DIAGNOSTICS_EMITTER_H_
  6. #include <cstdint>
  7. #include <string>
  8. #include <type_traits>
  9. #include <utility>
  10. #include "common/check.h"
  11. #include "llvm/ADT/Any.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/Support/FormatVariadic.h"
  14. #include "toolchain/diagnostics/consumer.h"
  15. #include "toolchain/diagnostics/diagnostic.h"
  16. #include "toolchain/diagnostics/kind.h"
  17. namespace Carbon::Diagnostics {
  18. namespace Internal {
  19. // Disable type deduction based on `args`; the type of `diagnostic_base`
  20. // determines the diagnostic's parameter types.
  21. template <typename Arg>
  22. using NoTypeDeduction = std::type_identity_t<Arg>;
  23. } // namespace Internal
  24. template <typename LocT, typename AnnotateFn>
  25. class AnnotationScope;
  26. // The result of `DiagnosticConvert::ConvertLoc`. This is non-templated to allow
  27. // sharing across converters.
  28. struct ConvertedLoc {
  29. // Becomes Message::loc.
  30. Loc loc;
  31. // Becomes Diagnostic::last_byte_offset.
  32. int32_t last_byte_offset;
  33. };
  34. // Used by types to indicate a diagnostic type conversion that results in the
  35. // provided StorageType. For example, to convert NameId to a std::string, we
  36. // write:
  37. //
  38. // struct NameId {
  39. // using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  40. // };
  41. template <typename StorageTypeT>
  42. struct TypeInfo {
  43. using StorageType = StorageTypeT;
  44. };
  45. // Manages the creation of reports, the testing if diagnostics are enabled, and
  46. // the collection of reports.
  47. //
  48. // This class is parameterized by a location type, allowing different
  49. // diagnostic clients to provide location information in whatever form is most
  50. // convenient for them, such as a position within a buffer when lexing, a token
  51. // when parsing, or a parse tree node when type-checking, and to allow unit
  52. // tests to be decoupled from any concrete location representation.
  53. template <typename LocT>
  54. class Emitter {
  55. public:
  56. // A builder-pattern type to provide a fluent interface for constructing
  57. // a more complex diagnostic. See `Emitter::Build` for the
  58. // expected usage.
  59. // This is nodiscard to protect against accidentally building a diagnostic
  60. // without emitting it.
  61. class [[nodiscard]] Builder {
  62. public:
  63. // Builder is move-only and cannot be copied.
  64. Builder(Builder&&) noexcept = default;
  65. auto operator=(Builder&&) noexcept -> Builder& = default;
  66. // Overrides the snippet for the most recently added diagnostic or note with
  67. // the given text. The provided override should include the caret text as
  68. // well as the source snippet. An empty snippet restores the default
  69. // behavior of printing the original source line.
  70. auto OverrideSnippet(llvm::StringRef snippet) -> Builder&;
  71. // Adds a note diagnostic attached to the main diagnostic being built.
  72. // The API mirrors the main emission API: `Emitter::Emit`.
  73. // For the expected usage see the builder API: `Emitter::Build`.
  74. template <typename... Args>
  75. auto Note(LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  76. Internal::NoTypeDeduction<Args>... args) -> Builder&;
  77. // Emits the built diagnostic and its attached notes.
  78. // For the expected usage see the builder API: `Emitter::Build`.
  79. template <typename... Args>
  80. auto Emit() & -> void;
  81. // Prevent trivial uses of the builder; always `static_assert`s.
  82. template <typename... Args>
  83. auto Emit() && -> void;
  84. // Returns true if this Builder may emit a diagnostic. Can be used
  85. // to avoid excess work computing notes, etc, if no diagnostic is going to
  86. // be emitted anyway.
  87. explicit operator bool() { return emitter_; }
  88. private:
  89. friend class Emitter<LocT>;
  90. template <typename... Args>
  91. explicit Builder(Emitter<LocT>* emitter, LocT loc,
  92. const DiagnosticBase<Args...>& diagnostic_base,
  93. llvm::SmallVector<llvm::Any> args);
  94. // Create a null `Builder` that will not emit anything. Notes will
  95. // be silently ignored.
  96. Builder() : emitter_(nullptr) {}
  97. // Adds a message to the diagnostic, handling conversion of the location and
  98. // arguments.
  99. template <typename... Args>
  100. auto AddMessage(LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  101. llvm::SmallVector<llvm::Any> args) -> void;
  102. // Adds a message to the diagnostic, handling conversion of the arguments. A
  103. // Loc must be provided instead of a LocT in order to
  104. // avoid potential recursion.
  105. template <typename... Args>
  106. auto AddMessageWithLoc(Loc loc,
  107. const DiagnosticBase<Args...>& diagnostic_base,
  108. llvm::SmallVector<llvm::Any> args) -> void;
  109. // Handles the cast of llvm::Any to Args types for formatv.
  110. // TODO: Custom formatting can be provided with an format_provider, but that
  111. // affects all formatv calls. Consider replacing formatv with a custom call
  112. // that allows diagnostic-specific formatting.
  113. template <typename... Args, size_t... N>
  114. static auto FormatFn(const Message& message,
  115. std::index_sequence<N...> /*indices*/) -> std::string;
  116. Emitter<LocT>* emitter_;
  117. Diagnostic diagnostic_;
  118. };
  119. // `consumer` is required to outlive the diagnostic emitter.
  120. explicit Emitter(Consumer* consumer) : consumer_(consumer) {}
  121. virtual ~Emitter() { Flush(); }
  122. // Emits an error.
  123. //
  124. // When passing arguments, they may be buffered. As a consequence, lifetimes
  125. // may outlive the `Emit` call.
  126. template <typename... Args>
  127. auto Emit(LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  128. Internal::NoTypeDeduction<Args>... args) -> void;
  129. // A fluent interface for building a diagnostic and attaching notes for added
  130. // context or information. For example:
  131. //
  132. // emitter_.Build(loc1, MyDiagnostic)
  133. // .Note(loc2, MyDiagnosticNote)
  134. // .Emit();
  135. template <typename... Args>
  136. auto Build(LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  137. Internal::NoTypeDeduction<Args>... args) -> Builder;
  138. // Create a null `Builder` that will not emit anything. Notes will
  139. // be silently ignored.
  140. auto BuildSuppressed() -> Builder { return Builder(); }
  141. // Adds a flush function to flush pending diagnostics that might be enqueued
  142. // and not yet emitted. The flush function will be called whenever `Flush` is
  143. // called.
  144. //
  145. // No mechanism is provided to unregister a flush function, so the function
  146. // must ensure that it remains callable until the emitter is destroyed.
  147. //
  148. // This is used to register a handler to flush diagnostics from Clang.
  149. auto AddFlushFn(std::function<auto()->void> flush_fn) -> void {
  150. flush_fns_.push_back(std::move(flush_fn));
  151. }
  152. // Flush all pending diagnostics that are queued externally, such as Clang
  153. // diagnostics. This should not be called when the external source might be in
  154. // the middle of producing a diagnostic, such as between Clang producing an
  155. // error and producing the attached notes.
  156. //
  157. // This is called automatically before any diagnostic annotator is added or
  158. // removed, to flush any pending diagnostics with suitable notes attached, and
  159. // when the emitter is destroyed.
  160. auto Flush() -> void {
  161. for (auto& flush_fn : flush_fns_) {
  162. flush_fn();
  163. }
  164. }
  165. protected:
  166. // Callback type used to report context messages from ConvertLoc.
  167. // Note that the first parameter type is Loc rather than
  168. // LocT, because ConvertLoc must not recurse.
  169. using ContextFnT =
  170. llvm::function_ref<auto(Loc, const DiagnosticBase<>&)->void>;
  171. // Converts a LocT to a Loc and its `last_byte_offset` (see
  172. // `Message`). ConvertLoc may invoke context_fn to provide context
  173. // messages.
  174. virtual auto ConvertLoc(LocT loc, ContextFnT context_fn) const
  175. -> ConvertedLoc = 0;
  176. // Converts arg types as needed. Most children don't customize conversion, so
  177. // the default returns the argument unchanged.
  178. virtual auto ConvertArg(llvm::Any arg) const -> llvm::Any { return arg; }
  179. private:
  180. // Converts an argument to llvm::Any for storage, handling input to storage
  181. // type conversion when needed.
  182. template <typename Arg>
  183. auto MakeAny(Arg arg) -> llvm::Any;
  184. template <typename OtherLocT, typename AnnotateFn>
  185. friend class AnnotationScope;
  186. friend class NoLocEmitter;
  187. Consumer* consumer_;
  188. llvm::SmallVector<std::function<auto()->void>, 1> flush_fns_;
  189. llvm::SmallVector<llvm::function_ref<auto(Builder& builder)->void>>
  190. annotate_fns_;
  191. };
  192. // This relies on `void*` location handling on `Emitter`.
  193. //
  194. // TODO: Based on how this ends up used or if we get more distinct emitters, it
  195. // might be worth considering having diagnostics specify that they don't apply
  196. // to source-location carrying emitters. For example, this might look like a
  197. // `CARBON_NO_LOC_DIAGNOSTIC` macro, or some other factoring. But it might end
  198. // up being more noise than it is worth.
  199. class NoLocEmitter : public Emitter<void*> {
  200. public:
  201. using Emitter::Emitter;
  202. template <typename LocT>
  203. explicit NoLocEmitter(const Emitter<LocT>& emitter)
  204. : Emitter(emitter.consumer_) {}
  205. // Emits an error. This specialization only applies to
  206. // `NoLocEmitter`.
  207. template <typename... Args>
  208. auto Emit(const DiagnosticBase<Args...>& diagnostic_base,
  209. Internal::NoTypeDeduction<Args>... args) -> void {
  210. Emitter::Emit(nullptr, diagnostic_base, args...);
  211. }
  212. protected:
  213. auto ConvertLoc(void* /*loc*/, ContextFnT /*context_fn*/) const
  214. -> ConvertedLoc override {
  215. return {.loc = {.filename = ""}, .last_byte_offset = -1};
  216. }
  217. };
  218. // An RAII object that denotes a scope in which any diagnostic produced should
  219. // be annotated in some way.
  220. //
  221. // This object is given a function `annotate` that will be called with a
  222. // `Builder& builder` for any diagnostic that is emitted through the
  223. // given emitter. That function can annotate the diagnostic by calling
  224. // `builder.Note` to add notes.
  225. template <typename LocT, typename AnnotateFn>
  226. class AnnotationScope {
  227. public:
  228. AnnotationScope(Emitter<LocT>* emitter, AnnotateFn annotate)
  229. : emitter_(emitter), annotate_(std::move(annotate)) {
  230. emitter_->Flush();
  231. emitter_->annotate_fns_.push_back(annotate_);
  232. }
  233. ~AnnotationScope() {
  234. emitter_->Flush();
  235. emitter_->annotate_fns_.pop_back();
  236. }
  237. private:
  238. Emitter<LocT>* emitter_;
  239. // Make a copy of the annotation function to ensure that it lives long enough.
  240. AnnotateFn annotate_;
  241. };
  242. template <typename LocT, typename AnnotateFn>
  243. AnnotationScope(Emitter<LocT>* emitter, AnnotateFn annotate)
  244. -> AnnotationScope<LocT, AnnotateFn>;
  245. // ============================================================================
  246. // Only internal implementation details below this point.
  247. // ============================================================================
  248. namespace Internal {
  249. // Determines whether there's a DiagnosticType member on Arg.
  250. // Used by Emitter.
  251. template <typename Arg>
  252. concept HasDiagnosticType = requires { typename Arg::DiagnosticType; };
  253. // The default implementation with no conversion.
  254. template <typename Arg>
  255. struct DiagnosticTypeForArg : public TypeInfo<Arg> {};
  256. // Exposes a custom conversion for an argument type.
  257. template <typename Arg>
  258. requires HasDiagnosticType<Arg>
  259. struct DiagnosticTypeForArg<Arg> : public Arg::DiagnosticType {};
  260. } // namespace Internal
  261. template <typename LocT>
  262. auto Emitter<LocT>::Builder::OverrideSnippet(llvm::StringRef snippet)
  263. -> Builder& {
  264. if (!emitter_) {
  265. return *this;
  266. }
  267. diagnostic_.messages.back().loc.snippet = snippet;
  268. return *this;
  269. }
  270. template <typename LocT>
  271. template <typename... Args>
  272. auto Emitter<LocT>::Builder::Note(
  273. LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  274. Internal::NoTypeDeduction<Args>... args) -> Builder& {
  275. if (!emitter_) {
  276. return *this;
  277. }
  278. CARBON_CHECK(diagnostic_base.Level == Level::Note ||
  279. diagnostic_base.Level == Level::LocationInfo,
  280. "{0}", static_cast<int>(diagnostic_base.Level));
  281. AddMessage(LocT(loc), diagnostic_base, {emitter_->MakeAny<Args>(args)...});
  282. return *this;
  283. }
  284. template <typename LocT>
  285. template <typename... Args>
  286. auto Emitter<LocT>::Builder::Emit() & -> void {
  287. if (!emitter_) {
  288. return;
  289. }
  290. for (auto annotate_fn : llvm::reverse(emitter_->annotate_fns_)) {
  291. annotate_fn(*this);
  292. }
  293. emitter_->consumer_->HandleDiagnostic(std::move(diagnostic_));
  294. }
  295. namespace Internal {
  296. template <typename LocT>
  297. concept AlwaysFalse = false;
  298. } // namespace Internal
  299. template <typename LocT>
  300. template <typename... Args>
  301. auto Emitter<LocT>::Builder::Emit() && -> void {
  302. // TODO: This is required by clang-16, but `false` may work in newer clang
  303. // versions. Replace when possible.
  304. static_assert(Internal::AlwaysFalse<LocT>,
  305. "Use `emitter.Emit(...)` or "
  306. "`emitter.Build(...).Note(...).Emit(...)` "
  307. "instead of `emitter.Build(...).Emit(...)`");
  308. }
  309. template <typename LocT>
  310. template <typename... Args>
  311. Emitter<LocT>::Builder::Builder(Emitter<LocT>* emitter, LocT loc,
  312. const DiagnosticBase<Args...>& diagnostic_base,
  313. llvm::SmallVector<llvm::Any> args)
  314. : emitter_(emitter), diagnostic_({.level = diagnostic_base.Level}) {
  315. AddMessage(LocT(loc), diagnostic_base, std::move(args));
  316. CARBON_CHECK(diagnostic_base.Level != Level::Note);
  317. }
  318. template <typename LocT>
  319. template <typename... Args>
  320. auto Emitter<LocT>::Builder::AddMessage(
  321. LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  322. llvm::SmallVector<llvm::Any> args) -> void {
  323. if (!emitter_) {
  324. return;
  325. }
  326. auto converted = emitter_->ConvertLoc(
  327. loc,
  328. [&](Loc context_loc, const DiagnosticBase<>& context_diagnostic_base) {
  329. AddMessageWithLoc(context_loc, context_diagnostic_base, {});
  330. });
  331. // Use the last byte offset from the first message.
  332. if (diagnostic_.messages.empty()) {
  333. diagnostic_.last_byte_offset = converted.last_byte_offset;
  334. }
  335. AddMessageWithLoc(converted.loc, diagnostic_base, args);
  336. }
  337. template <typename LocT>
  338. template <typename... Args>
  339. auto Emitter<LocT>::Builder::AddMessageWithLoc(
  340. Loc loc, const DiagnosticBase<Args...>& diagnostic_base,
  341. llvm::SmallVector<llvm::Any> args) -> void {
  342. if (!emitter_) {
  343. return;
  344. }
  345. diagnostic_.messages.emplace_back(
  346. Message{.kind = diagnostic_base.Kind,
  347. .level = diagnostic_base.Level,
  348. .loc = loc,
  349. .format = diagnostic_base.Format,
  350. .format_args = std::move(args),
  351. .format_fn = [](const Message& message) -> std::string {
  352. return FormatFn<Args...>(
  353. message, std::make_index_sequence<sizeof...(Args)>());
  354. }});
  355. }
  356. template <typename LocT>
  357. template <typename... Args, size_t... N>
  358. auto Emitter<LocT>::Builder::FormatFn(const Message& message,
  359. std::index_sequence<N...> /*indices*/)
  360. -> std::string {
  361. static_assert(sizeof...(Args) == sizeof...(N), "Invalid template args");
  362. CARBON_CHECK(message.format_args.size() == sizeof...(Args),
  363. "Argument count mismatch on {0}: {1} != {2}", message.kind,
  364. message.format_args.size(), sizeof...(Args));
  365. return llvm::formatv(
  366. message.format.data(),
  367. llvm::any_cast<
  368. typename Internal::DiagnosticTypeForArg<Args>::StorageType>(
  369. message.format_args[N])...);
  370. }
  371. template <typename LocT>
  372. template <typename... Args>
  373. auto Emitter<LocT>::Emit(LocT loc,
  374. const DiagnosticBase<Args...>& diagnostic_base,
  375. Internal::NoTypeDeduction<Args>... args) -> void {
  376. Builder builder(this, loc, diagnostic_base, {MakeAny<Args>(args)...});
  377. builder.Emit();
  378. }
  379. template <typename LocT>
  380. template <typename... Args>
  381. auto Emitter<LocT>::Build(LocT loc,
  382. const DiagnosticBase<Args...>& diagnostic_base,
  383. Internal::NoTypeDeduction<Args>... args) -> Builder {
  384. return Builder(this, loc, diagnostic_base, {MakeAny<Args>(args)...});
  385. }
  386. template <typename LocT>
  387. template <typename Arg>
  388. auto Emitter<LocT>::MakeAny(Arg arg) -> llvm::Any {
  389. llvm::Any converted = ConvertArg(arg);
  390. using Storage = Internal::DiagnosticTypeForArg<Arg>::StorageType;
  391. CARBON_CHECK(llvm::any_cast<Storage>(&converted),
  392. "Failed to convert argument of type {0} to its storage type {1}",
  393. typeid(Arg).name(), typeid(Storage).name());
  394. return converted;
  395. }
  396. } // namespace Carbon::Diagnostics
  397. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_EMITTER_H_