diagnostic_emitter.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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_DIAGNOSTIC_EMITTER_H_
  5. #define CARBON_TOOLCHAIN_DIAGNOSTICS_DIAGNOSTIC_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/diagnostic.h"
  15. #include "toolchain/diagnostics/diagnostic_consumer.h"
  16. #include "toolchain/diagnostics/diagnostic_kind.h"
  17. namespace Carbon {
  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 DiagnosticAnnotationScope;
  26. // The result of `DiagnosticConvert::ConvertLoc`. This is non-templated to allow
  27. // sharing across converters.
  28. struct ConvertedDiagnosticLoc {
  29. // Becomes DiagnosticMessage::loc.
  30. DiagnosticLoc 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 = DiagnosticTypeInfo<std::string>;
  40. // };
  41. template <typename StorageTypeT>
  42. struct DiagnosticTypeInfo {
  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 DiagnosticEmitter {
  55. public:
  56. // A builder-pattern type to provide a fluent interface for constructing
  57. // a more complex diagnostic. See `DiagnosticEmitter::Build` for the
  58. // expected usage.
  59. // This is nodiscard to protect against accidentally building a diagnostic
  60. // without emitting it.
  61. class [[nodiscard]] DiagnosticBuilder {
  62. public:
  63. // DiagnosticBuilder is move-only and cannot be copied.
  64. DiagnosticBuilder(DiagnosticBuilder&&) noexcept = default;
  65. auto operator=(DiagnosticBuilder&&) noexcept
  66. -> DiagnosticBuilder& = default;
  67. // Adds a note diagnostic attached to the main diagnostic being built.
  68. // The API mirrors the main emission API: `DiagnosticEmitter::Emit`.
  69. // For the expected usage see the builder API: `DiagnosticEmitter::Build`.
  70. template <typename... Args>
  71. auto Note(LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  72. Internal::NoTypeDeduction<Args>... args) -> DiagnosticBuilder&;
  73. // Emits the built diagnostic and its attached notes.
  74. // For the expected usage see the builder API: `DiagnosticEmitter::Build`.
  75. template <typename... Args>
  76. auto Emit() -> void;
  77. // Returns true if this DiagnosticBuilder may emit a diagnostic. Can be used
  78. // to avoid excess work computing notes, etc, if no diagnostic is going to
  79. // be emitted anyway.
  80. explicit operator bool() { return emitter_; }
  81. private:
  82. friend class DiagnosticEmitter<LocT>;
  83. template <typename... Args>
  84. explicit DiagnosticBuilder(DiagnosticEmitter<LocT>* emitter, LocT loc,
  85. const DiagnosticBase<Args...>& diagnostic_base,
  86. llvm::SmallVector<llvm::Any> args);
  87. // Create a null `DiagnosticBuilder` that will not emit anything. Notes will
  88. // be silently ignored.
  89. DiagnosticBuilder() : emitter_(nullptr) {}
  90. // Adds a message to the diagnostic, handling conversion of the location and
  91. // arguments.
  92. template <typename... Args>
  93. auto AddMessage(LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  94. llvm::SmallVector<llvm::Any> args) -> void;
  95. // Adds a message to the diagnostic, handling conversion of the arguments. A
  96. // DiagnosticLoc must be provided instead of a LocT in order to
  97. // avoid potential recursion.
  98. template <typename... Args>
  99. auto AddMessageWithDiagnosticLoc(
  100. DiagnosticLoc loc, const DiagnosticBase<Args...>& diagnostic_base,
  101. llvm::SmallVector<llvm::Any> args) -> void;
  102. // Handles the cast of llvm::Any to Args types for formatv.
  103. // TODO: Custom formatting can be provided with an format_provider, but that
  104. // affects all formatv calls. Consider replacing formatv with a custom call
  105. // that allows diagnostic-specific formatting.
  106. template <typename... Args, size_t... N>
  107. static auto FormatFn(const DiagnosticMessage& message,
  108. std::index_sequence<N...> /*indices*/) -> std::string;
  109. DiagnosticEmitter<LocT>* emitter_;
  110. Diagnostic diagnostic_;
  111. };
  112. // `consumer` is required to outlive the diagnostic emitter.
  113. explicit DiagnosticEmitter(DiagnosticConsumer* consumer)
  114. : consumer_(consumer) {}
  115. virtual ~DiagnosticEmitter() = default;
  116. // Emits an error.
  117. //
  118. // When passing arguments, they may be buffered. As a consequence, lifetimes
  119. // may outlive the `Emit` call.
  120. template <typename... Args>
  121. auto Emit(LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  122. Internal::NoTypeDeduction<Args>... args) -> void;
  123. // A fluent interface for building a diagnostic and attaching notes for added
  124. // context or information. For example:
  125. //
  126. // emitter_.Build(loc1, MyDiagnostic)
  127. // .Note(loc2, MyDiagnosticNote)
  128. // .Emit();
  129. template <typename... Args>
  130. auto Build(LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  131. Internal::NoTypeDeduction<Args>... args) -> DiagnosticBuilder;
  132. // Create a null `DiagnosticBuilder` that will not emit anything. Notes will
  133. // be silently ignored.
  134. auto BuildSuppressed() -> DiagnosticBuilder { return DiagnosticBuilder(); }
  135. protected:
  136. // Callback type used to report context messages from ConvertLoc.
  137. // Note that the first parameter type is DiagnosticLoc rather than
  138. // LocT, because ConvertLoc must not recurse.
  139. using ContextFnT =
  140. llvm::function_ref<auto(DiagnosticLoc, const DiagnosticBase<>&)->void>;
  141. // Converts a LocT to a DiagnosticLoc and its `last_byte_offset` (see
  142. // `DiagnosticMessage`). ConvertLoc may invoke context_fn to provide context
  143. // messages.
  144. virtual auto ConvertLoc(LocT loc, ContextFnT context_fn) const
  145. -> ConvertedDiagnosticLoc = 0;
  146. // Converts arg types as needed. Most children don't customize conversion, so
  147. // the default returns the argument unchanged.
  148. virtual auto ConvertArg(llvm::Any arg) const -> llvm::Any { return arg; }
  149. private:
  150. // Converts an argument to llvm::Any for storage, handling input to storage
  151. // type conversion when needed.
  152. template <typename Arg>
  153. auto MakeAny(Arg arg) -> llvm::Any;
  154. template <typename OtherLocT, typename AnnotateFn>
  155. friend class DiagnosticAnnotationScope;
  156. DiagnosticConsumer* consumer_;
  157. llvm::SmallVector<llvm::function_ref<auto(DiagnosticBuilder& builder)->void>>
  158. annotate_fns_;
  159. };
  160. // This relies on `void*` location handling on `DiagnosticEmitter`.
  161. //
  162. // TODO: Based on how this ends up used or if we get more distinct emitters, it
  163. // might be worth considering having diagnostics specify that they don't apply
  164. // to source-location carrying emitters. For example, this might look like a
  165. // `CARBON_NO_LOC_DIAGNOSTIC` macro, or some other factoring. But it might end
  166. // up being more noise than it is worth.
  167. class NoLocDiagnosticEmitter : public DiagnosticEmitter<void*> {
  168. public:
  169. using DiagnosticEmitter::DiagnosticEmitter;
  170. // Emits an error. This specialization only applies to
  171. // `NoLocDiagnosticEmitter`.
  172. template <typename... Args>
  173. auto Emit(const DiagnosticBase<Args...>& diagnostic_base,
  174. Internal::NoTypeDeduction<Args>... args) -> void {
  175. DiagnosticEmitter::Emit(nullptr, diagnostic_base, args...);
  176. }
  177. protected:
  178. auto ConvertLoc(void* /*loc*/, ContextFnT /*context_fn*/) const
  179. -> ConvertedDiagnosticLoc override {
  180. return {.loc = {.filename = ""}, .last_byte_offset = -1};
  181. }
  182. };
  183. // An RAII object that denotes a scope in which any diagnostic produced should
  184. // be annotated in some way.
  185. //
  186. // This object is given a function `annotate` that will be called with a
  187. // `DiagnosticBuilder& builder` for any diagnostic that is emitted through the
  188. // given emitter. That function can annotate the diagnostic by calling
  189. // `builder.Note` to add notes.
  190. template <typename LocT, typename AnnotateFn>
  191. class DiagnosticAnnotationScope {
  192. public:
  193. DiagnosticAnnotationScope(DiagnosticEmitter<LocT>* emitter,
  194. AnnotateFn annotate)
  195. : emitter_(emitter), annotate_(std::move(annotate)) {
  196. emitter_->annotate_fns_.push_back(annotate_);
  197. }
  198. ~DiagnosticAnnotationScope() { emitter_->annotate_fns_.pop_back(); }
  199. private:
  200. DiagnosticEmitter<LocT>* emitter_;
  201. // Make a copy of the annotation function to ensure that it lives long enough.
  202. AnnotateFn annotate_;
  203. };
  204. template <typename LocT, typename AnnotateFn>
  205. DiagnosticAnnotationScope(DiagnosticEmitter<LocT>* emitter, AnnotateFn annotate)
  206. -> DiagnosticAnnotationScope<LocT, AnnotateFn>;
  207. // ============================================================================
  208. // Only internal implementation details below this point.
  209. // ============================================================================
  210. namespace Internal {
  211. // Determines whether there's a DiagnosticType member on Arg.
  212. // Used by DiagnosticEmitter.
  213. template <typename Arg>
  214. concept HasDiagnosticType = requires { typename Arg::DiagnosticType; };
  215. // The default implementation with no conversion.
  216. template <typename Arg>
  217. struct DiagnosticTypeForArg : public DiagnosticTypeInfo<Arg> {};
  218. // Exposes a custom conversion for an argument type.
  219. template <typename Arg>
  220. requires HasDiagnosticType<Arg>
  221. struct DiagnosticTypeForArg<Arg> : public Arg::DiagnosticType {};
  222. } // namespace Internal
  223. template <typename LocT>
  224. template <typename... Args>
  225. auto DiagnosticEmitter<LocT>::DiagnosticBuilder::Note(
  226. LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  227. Internal::NoTypeDeduction<Args>... args) -> DiagnosticBuilder& {
  228. if (!emitter_) {
  229. return *this;
  230. }
  231. CARBON_CHECK(diagnostic_base.Level == DiagnosticLevel::Note ||
  232. diagnostic_base.Level == DiagnosticLevel::LocationInfo,
  233. "{0}", static_cast<int>(diagnostic_base.Level));
  234. AddMessage(loc, diagnostic_base, {emitter_->MakeAny<Args>(args)...});
  235. return *this;
  236. }
  237. template <typename LocT>
  238. template <typename... Args>
  239. auto DiagnosticEmitter<LocT>::DiagnosticBuilder::Emit() -> void {
  240. if (!emitter_) {
  241. return;
  242. }
  243. for (auto annotate_fn : llvm::reverse(emitter_->annotate_fns_)) {
  244. annotate_fn(*this);
  245. }
  246. emitter_->consumer_->HandleDiagnostic(std::move(diagnostic_));
  247. }
  248. template <typename LocT>
  249. template <typename... Args>
  250. DiagnosticEmitter<LocT>::DiagnosticBuilder::DiagnosticBuilder(
  251. DiagnosticEmitter<LocT>* emitter, LocT loc,
  252. const DiagnosticBase<Args...>& diagnostic_base,
  253. llvm::SmallVector<llvm::Any> args)
  254. : emitter_(emitter), diagnostic_({.level = diagnostic_base.Level}) {
  255. AddMessage(loc, diagnostic_base, std::move(args));
  256. CARBON_CHECK(diagnostic_base.Level != DiagnosticLevel::Note);
  257. }
  258. template <typename LocT>
  259. template <typename... Args>
  260. auto DiagnosticEmitter<LocT>::DiagnosticBuilder::AddMessage(
  261. LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  262. llvm::SmallVector<llvm::Any> args) -> void {
  263. if (!emitter_) {
  264. return;
  265. }
  266. auto converted = emitter_->ConvertLoc(
  267. loc, [&](DiagnosticLoc context_loc,
  268. const DiagnosticBase<>& context_diagnostic_base) {
  269. AddMessageWithDiagnosticLoc(context_loc, context_diagnostic_base, {});
  270. });
  271. // Use the last byte offset from the first message.
  272. if (diagnostic_.messages.empty()) {
  273. diagnostic_.last_byte_offset = converted.last_byte_offset;
  274. }
  275. AddMessageWithDiagnosticLoc(converted.loc, diagnostic_base, args);
  276. }
  277. template <typename LocT>
  278. template <typename... Args>
  279. auto DiagnosticEmitter<LocT>::DiagnosticBuilder::AddMessageWithDiagnosticLoc(
  280. DiagnosticLoc loc, const DiagnosticBase<Args...>& diagnostic_base,
  281. llvm::SmallVector<llvm::Any> args) -> void {
  282. if (!emitter_) {
  283. return;
  284. }
  285. diagnostic_.messages.emplace_back(DiagnosticMessage{
  286. .kind = diagnostic_base.Kind,
  287. .level = diagnostic_base.Level,
  288. .loc = loc,
  289. .format = diagnostic_base.Format,
  290. .format_args = std::move(args),
  291. .format_fn = [](const DiagnosticMessage& message) -> std::string {
  292. return FormatFn<Args...>(message,
  293. std::make_index_sequence<sizeof...(Args)>());
  294. }});
  295. }
  296. template <typename LocT>
  297. template <typename... Args, size_t... N>
  298. auto DiagnosticEmitter<LocT>::DiagnosticBuilder::FormatFn(
  299. const DiagnosticMessage& message, std::index_sequence<N...> /*indices*/)
  300. -> std::string {
  301. static_assert(sizeof...(Args) == sizeof...(N), "Invalid template args");
  302. CARBON_CHECK(message.format_args.size() == sizeof...(Args),
  303. "Argument count mismatch on {0}: {1} != {2}", message.kind,
  304. message.format_args.size(), sizeof...(Args));
  305. return llvm::formatv(
  306. message.format.data(),
  307. llvm::any_cast<
  308. typename Internal::DiagnosticTypeForArg<Args>::StorageType>(
  309. message.format_args[N])...);
  310. }
  311. template <typename LocT>
  312. template <typename... Args>
  313. auto DiagnosticEmitter<LocT>::Emit(
  314. LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  315. Internal::NoTypeDeduction<Args>... args) -> void {
  316. DiagnosticBuilder(this, loc, diagnostic_base, {MakeAny<Args>(args)...})
  317. .Emit();
  318. }
  319. template <typename LocT>
  320. template <typename... Args>
  321. auto DiagnosticEmitter<LocT>::Build(
  322. LocT loc, const DiagnosticBase<Args...>& diagnostic_base,
  323. Internal::NoTypeDeduction<Args>... args) -> DiagnosticBuilder {
  324. return DiagnosticBuilder(this, loc, diagnostic_base,
  325. {MakeAny<Args>(args)...});
  326. }
  327. template <typename LocT>
  328. template <typename Arg>
  329. auto DiagnosticEmitter<LocT>::MakeAny(Arg arg) -> llvm::Any {
  330. llvm::Any converted = ConvertArg(arg);
  331. using Storage = Internal::DiagnosticTypeForArg<Arg>::StorageType;
  332. CARBON_CHECK(llvm::any_cast<Storage>(&converted),
  333. "Failed to convert argument of type {0} to its storage type {1}",
  334. typeid(Arg).name(), typeid(Storage).name());
  335. return converted;
  336. }
  337. } // namespace Carbon
  338. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_DIAGNOSTIC_EMITTER_H_