diagnostic_emitter.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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 <functional>
  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/ADT/StringRef.h"
  14. #include "llvm/Support/FormatVariadic.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. #include "toolchain/diagnostics/diagnostic_kind.h"
  17. namespace Carbon {
  18. enum class DiagnosticLevel : int8_t {
  19. // A note, not indicating an error on its own, but possibly providing context
  20. // for an error.
  21. Note,
  22. // A warning diagnostic, indicating a likely problem with the program.
  23. Warning,
  24. // An error diagnostic, indicating that the program is not valid.
  25. Error,
  26. };
  27. // Provides a definition of a diagnostic. For example:
  28. // CARBON_DIAGNOSTIC(MyDiagnostic, Error, "Invalid code!");
  29. // CARBON_DIAGNOSTIC(MyDiagnostic, Warning, "Found {0}, expected {1}.",
  30. // llvm::StringRef, llvm::StringRef);
  31. //
  32. // Arguments are passed to llvm::formatv; see:
  33. // https://llvm.org/doxygen/FormatVariadic_8h_source.html
  34. //
  35. // See `DiagnosticEmitter::Emit` for comments about argument lifetimes.
  36. #define CARBON_DIAGNOSTIC(DiagnosticName, Level, Format, ...) \
  37. static constexpr auto DiagnosticName = \
  38. Internal::DiagnosticBase<__VA_ARGS__>( \
  39. ::Carbon::DiagnosticKind::DiagnosticName, \
  40. ::Carbon::DiagnosticLevel::Level, Format)
  41. struct DiagnosticLocation {
  42. // Name of the file or buffer that this diagnostic refers to.
  43. // TODO: Move this out of DiagnosticLocation, as part of an expectation that
  44. // files will be compiled separately, so storing the file's path
  45. // per-diagnostic is wasteful.
  46. std::string file_name;
  47. // 1-based line number.
  48. int32_t line_number;
  49. // 1-based column number.
  50. int32_t column_number;
  51. };
  52. // A message composing a diagnostic. This may be the main message, but can also
  53. // be notes providing more information.
  54. struct DiagnosticMessage {
  55. explicit DiagnosticMessage(
  56. DiagnosticKind kind, DiagnosticLocation location,
  57. llvm::StringLiteral format, llvm::SmallVector<llvm::Any, 0> format_args,
  58. std::function<std::string(const DiagnosticMessage&)> format_fn)
  59. : kind(kind),
  60. location(std::move(location)),
  61. format(format),
  62. format_args(std::move(format_args)),
  63. format_fn(std::move(format_fn)) {}
  64. // The diagnostic's kind.
  65. DiagnosticKind kind;
  66. // The calculated location of the diagnostic.
  67. DiagnosticLocation location;
  68. // The diagnostic's format string. This, along with format_args, will be
  69. // passed to format_fn.
  70. llvm::StringLiteral format;
  71. // A list of format arguments.
  72. //
  73. // These may be used by non-standard consumers to inspect diagnostic details
  74. // without needing to parse the formatted string; however, it should be
  75. // understood that diagnostic formats are subject to change and the llvm::Any
  76. // offers limited compile-time type safety. Integration tests are required.
  77. llvm::SmallVector<llvm::Any, 0> format_args;
  78. // Returns the formatted string. By default, this uses llvm::formatv.
  79. std::function<std::string(const DiagnosticMessage&)> format_fn;
  80. };
  81. // An instance of a single error or warning. Information about the diagnostic
  82. // can be recorded into it for more complex consumers.
  83. struct Diagnostic {
  84. // The diagnostic's level.
  85. DiagnosticLevel level;
  86. // The main error or warning.
  87. DiagnosticMessage message;
  88. // Notes that add context or supplemental information to the diagnostic.
  89. llvm::SmallVector<DiagnosticMessage> notes;
  90. };
  91. // Receives diagnostics as they are emitted.
  92. class DiagnosticConsumer {
  93. public:
  94. virtual ~DiagnosticConsumer() = default;
  95. // Handle a diagnostic.
  96. //
  97. // This relies on moves of the Diagnostic. At present, diagnostics are
  98. // allocated on the stack, so their lifetime is that of HandleDiagnostic.
  99. // However, SortingDiagnosticConsumer needs a longer lifetime, until all
  100. // diagnostics have been produced. As a consequence, it needs to either copy
  101. // or move the Diagnostic, and right now we're moving due to the overhead of
  102. // notes.
  103. //
  104. // At present, there is no persistent storage of diagnostics because IDEs
  105. // would be fine with diagnostics being printed immediately and discarded,
  106. // without SortingDiagnosticConsumer. If this becomes a performance issue, we
  107. // may want to investigate alternative ownership models that address both IDE
  108. // and CLI user needs.
  109. virtual auto HandleDiagnostic(Diagnostic diagnostic) -> void = 0;
  110. // Flushes any buffered input.
  111. virtual auto Flush() -> void {}
  112. };
  113. // An interface that can translate some representation of a location into a
  114. // diagnostic location.
  115. //
  116. // TODO: Revisit this once the diagnostics machinery is more complete and see
  117. // if we can turn it into a `std::function`.
  118. template <typename LocationT>
  119. class DiagnosticLocationTranslator {
  120. public:
  121. virtual ~DiagnosticLocationTranslator() = default;
  122. [[nodiscard]] virtual auto GetLocation(LocationT loc)
  123. -> DiagnosticLocation = 0;
  124. };
  125. namespace Internal {
  126. // Use the DIAGNOSTIC macro to instantiate this.
  127. // This stores static information about a diagnostic category.
  128. template <typename... Args>
  129. struct DiagnosticBase {
  130. explicit constexpr DiagnosticBase(DiagnosticKind kind, DiagnosticLevel level,
  131. llvm::StringLiteral format)
  132. : Kind(kind), Level(level), Format(format) {}
  133. // Calls formatv with the diagnostic's arguments.
  134. auto FormatFn(const DiagnosticMessage& message) const -> std::string {
  135. return FormatFnImpl(message, std::make_index_sequence<sizeof...(Args)>());
  136. };
  137. // The diagnostic's kind.
  138. DiagnosticKind Kind;
  139. // The diagnostic's level.
  140. DiagnosticLevel Level;
  141. // The diagnostic's format for llvm::formatv.
  142. llvm::StringLiteral Format;
  143. private:
  144. // Handles the cast of llvm::Any to Args types for formatv.
  145. // TODO: Custom formatting can be provided with an format_provider, but that
  146. // affects all formatv calls. Consider replacing formatv with a custom call
  147. // that allows diagnostic-specific formatting.
  148. template <std::size_t... N>
  149. inline auto FormatFnImpl(const DiagnosticMessage& message,
  150. std::index_sequence<N...> /*indices*/) const
  151. -> std::string {
  152. assert(message.format_args.size() == sizeof...(Args));
  153. return llvm::formatv(message.format.data(),
  154. llvm::any_cast<Args>(message.format_args[N])...);
  155. }
  156. };
  157. // Disable type deduction based on `args`; the type of `diagnostic_base`
  158. // determines the diagnostic's parameter types.
  159. template <typename Arg>
  160. using NoTypeDeduction = std::common_type_t<Arg>;
  161. } // namespace Internal
  162. // Manages the creation of reports, the testing if diagnostics are enabled, and
  163. // the collection of reports.
  164. //
  165. // This class is parameterized by a location type, allowing different
  166. // diagnostic clients to provide location information in whatever form is most
  167. // convenient for them, such as a position within a buffer when lexing, a token
  168. // when parsing, or a parse tree node when type-checking, and to allow unit
  169. // tests to be decoupled from any concrete location representation.
  170. template <typename LocationT>
  171. class DiagnosticEmitter {
  172. public:
  173. // A builder-pattern type to provide a fluent interface for constructing
  174. // a more complex diagnostic. See `DiagnosticEmitter::Build` for the
  175. // expected usage.
  176. class DiagnosticBuilder {
  177. public:
  178. // Adds a note diagnostic attached to the main diagnostic being built.
  179. // The API mirrors the main emission API: `DiagnosticEmitter::Emit`.
  180. // For the expected usage see the builder API: `DiagnosticEmitter::Build`.
  181. template <typename... Args>
  182. auto Note(LocationT location,
  183. const Internal::DiagnosticBase<Args...>& diagnostic_base,
  184. Internal::NoTypeDeduction<Args>... args) -> DiagnosticBuilder& {
  185. CARBON_CHECK(diagnostic_base.Level == DiagnosticLevel::Note)
  186. << static_cast<int>(diagnostic_base.Level);
  187. diagnostic_.notes.push_back(
  188. MakeMessage(location, diagnostic_base, std::move(args)...));
  189. return *this;
  190. }
  191. // Emits the built diagnostic and its attached notes.
  192. // For the expected usage see the builder API: `DiagnosticEmitter::Build`.
  193. template <typename... Args>
  194. auto Emit() -> void {
  195. emitter_->consumer_->HandleDiagnostic(std::move(diagnostic_));
  196. }
  197. private:
  198. friend class DiagnosticEmitter<LocationT>;
  199. template <typename... Args>
  200. explicit DiagnosticBuilder(
  201. DiagnosticEmitter<LocationT>* emitter, LocationT location,
  202. const Internal::DiagnosticBase<Args...>& diagnostic_base,
  203. Internal::NoTypeDeduction<Args>... args)
  204. : emitter_(emitter),
  205. diagnostic_({.level = diagnostic_base.Level,
  206. .message = MakeMessage(location, diagnostic_base,
  207. std::move(args)...)}) {
  208. CARBON_CHECK(diagnostic_base.Level != DiagnosticLevel::Note);
  209. }
  210. template <typename... Args>
  211. auto MakeMessage(LocationT location,
  212. const Internal::DiagnosticBase<Args...>& diagnostic_base,
  213. Internal::NoTypeDeduction<Args>... args)
  214. -> DiagnosticMessage {
  215. return DiagnosticMessage(
  216. diagnostic_base.Kind, emitter_->translator_->GetLocation(location),
  217. diagnostic_base.Format, {std::move(args)...},
  218. [&diagnostic_base](const DiagnosticMessage& message) -> std::string {
  219. return diagnostic_base.FormatFn(message);
  220. });
  221. }
  222. DiagnosticEmitter<LocationT>* emitter_;
  223. Diagnostic diagnostic_;
  224. };
  225. // The `translator` and `consumer` are required to outlive the diagnostic
  226. // emitter.
  227. explicit DiagnosticEmitter(
  228. DiagnosticLocationTranslator<LocationT>& translator,
  229. DiagnosticConsumer& consumer)
  230. : translator_(&translator), consumer_(&consumer) {}
  231. ~DiagnosticEmitter() = default;
  232. // Emits an error.
  233. //
  234. // When passing arguments, they may be buffered. As a consequence, lifetimes
  235. // may outlive the `Emit` call.
  236. template <typename... Args>
  237. auto Emit(LocationT location,
  238. const Internal::DiagnosticBase<Args...>& diagnostic_base,
  239. Internal::NoTypeDeduction<Args>... args) -> void {
  240. DiagnosticBuilder(this, location, diagnostic_base, std::move(args)...)
  241. .Emit();
  242. }
  243. // A fluent interface for building a diagnostic and attaching notes for added
  244. // context or information. For example:
  245. //
  246. // emitter_.Build(location1, MyDiagnostic)
  247. // .Note(location2, MyDiagnosticNote)
  248. // .Emit();
  249. template <typename... Args>
  250. auto Build(LocationT location,
  251. const Internal::DiagnosticBase<Args...>& diagnostic_base,
  252. Internal::NoTypeDeduction<Args>... args) -> DiagnosticBuilder {
  253. return DiagnosticBuilder(this, location, diagnostic_base,
  254. std::move(args)...);
  255. }
  256. private:
  257. DiagnosticLocationTranslator<LocationT>* translator_;
  258. DiagnosticConsumer* consumer_;
  259. };
  260. inline auto ConsoleDiagnosticConsumer() -> DiagnosticConsumer& {
  261. class Consumer : public DiagnosticConsumer {
  262. auto HandleDiagnostic(Diagnostic diagnostic) -> void override {
  263. Print(diagnostic.message);
  264. for (const auto& note : diagnostic.notes) {
  265. Print(note);
  266. }
  267. }
  268. auto Print(const DiagnosticMessage& message) -> void {
  269. llvm::errs() << message.location.file_name << ":"
  270. << message.location.line_number << ":"
  271. << message.location.column_number << ": "
  272. << message.format_fn(message) << "\n";
  273. }
  274. };
  275. static auto* consumer = new Consumer;
  276. return *consumer;
  277. }
  278. // Diagnostic consumer adaptor that tracks whether any errors have been
  279. // produced.
  280. class ErrorTrackingDiagnosticConsumer : public DiagnosticConsumer {
  281. public:
  282. explicit ErrorTrackingDiagnosticConsumer(DiagnosticConsumer& next_consumer)
  283. : next_consumer_(&next_consumer) {}
  284. auto HandleDiagnostic(Diagnostic diagnostic) -> void override {
  285. seen_error_ |= diagnostic.level == DiagnosticLevel::Error;
  286. next_consumer_->HandleDiagnostic(std::move(diagnostic));
  287. }
  288. // Reset whether we've seen an error.
  289. auto Reset() -> void { seen_error_ = false; }
  290. // Returns whether we've seen an error since the last reset.
  291. auto seen_error() const -> bool { return seen_error_; }
  292. private:
  293. DiagnosticConsumer* next_consumer_;
  294. bool seen_error_ = false;
  295. };
  296. } // namespace Carbon
  297. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_DIAGNOSTIC_EMITTER_H_