diagnostic_emitter.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 "llvm/ADT/Any.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StringRef.h"
  13. #include "llvm/Support/FormatVariadic.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. #include "toolchain/diagnostics/diagnostic_kind.h"
  16. namespace Carbon {
  17. enum class DiagnosticLevel : int8_t {
  18. // A warning diagnostic, indicating a likely problem with the program.
  19. Warning,
  20. // An error diagnostic, indicating that the program is not valid.
  21. Error,
  22. };
  23. // Provides a definition of a diagnostic. For example:
  24. // CARBON_DIAGNOSTIC(MyDiagnostic, Error, "Invalid code!");
  25. // CARBON_DIAGNOSTIC(MyDiagnostic, Warning, "Found {0}, expected {1}.",
  26. // llvm::StringRef, llvm::StringRef);
  27. //
  28. // Arguments are passed to llvm::formatv; see:
  29. // https://llvm.org/doxygen/FormatVariadic_8h_source.html
  30. //
  31. // See `DiagnosticEmitter::Emit` for comments about argument lifetimes.
  32. #define CARBON_DIAGNOSTIC(DiagnosticName, Level, Format, ...) \
  33. static constexpr auto DiagnosticName = \
  34. Internal::DiagnosticBase<__VA_ARGS__>( \
  35. ::Carbon::DiagnosticKind::DiagnosticName, \
  36. ::Carbon::DiagnosticLevel::Level, Format)
  37. struct DiagnosticLocation {
  38. // Name of the file or buffer that this diagnostic refers to.
  39. // TODO: Move this out of DiagnosticLocation, as part of an expectation that
  40. // files will be compiled separately, so storing the file's path
  41. // per-diagnostic is wasteful.
  42. std::string file_name;
  43. // 1-based line number.
  44. int32_t line_number;
  45. // 1-based column number.
  46. int32_t column_number;
  47. };
  48. // An instance of a single error or warning. Information about the diagnostic
  49. // can be recorded into it for more complex consumers.
  50. struct Diagnostic {
  51. // The diagnostic's kind.
  52. DiagnosticKind kind;
  53. // The diagnostic's level.
  54. DiagnosticLevel level;
  55. // The calculated location of the diagnostic.
  56. DiagnosticLocation location;
  57. // The diagnostic's format string. This, along with format_args, will be
  58. // passed to format_fn.
  59. llvm::StringLiteral format;
  60. // A list of format arguments.
  61. //
  62. // These may be used by non-standard consumers to inspect diagnostic details
  63. // without needing to parse the formatted string; however, it should be
  64. // understood that diagnostic formats are subject to change and the llvm::Any
  65. // offers limited compile-time type safety. Integration tests are required.
  66. llvm::SmallVector<llvm::Any, 0> format_args;
  67. // Returns the formatted string. By default, this uses llvm::formatv.
  68. std::function<std::string(const Diagnostic&)> format_fn;
  69. };
  70. // Receives diagnostics as they are emitted.
  71. class DiagnosticConsumer {
  72. public:
  73. virtual ~DiagnosticConsumer() = default;
  74. // Handle a diagnostic.
  75. virtual auto HandleDiagnostic(const Diagnostic& diagnostic) -> void = 0;
  76. // Flushes any buffered input.
  77. virtual auto Flush() -> void {}
  78. };
  79. // An interface that can translate some representation of a location into a
  80. // diagnostic location.
  81. //
  82. // TODO: Revisit this once the diagnostics machinery is more complete and see
  83. // if we can turn it into a `std::function`.
  84. template <typename LocationT>
  85. class DiagnosticLocationTranslator {
  86. public:
  87. virtual ~DiagnosticLocationTranslator() = default;
  88. [[nodiscard]] virtual auto GetLocation(LocationT loc)
  89. -> DiagnosticLocation = 0;
  90. };
  91. namespace Internal {
  92. // Use the DIAGNOSTIC macro to instantiate this.
  93. // This stores static information about a diagnostic category.
  94. template <typename... Args>
  95. struct DiagnosticBase {
  96. constexpr DiagnosticBase(DiagnosticKind kind, DiagnosticLevel level,
  97. llvm::StringLiteral format)
  98. : Kind(kind), Level(level), Format(format) {}
  99. // Calls formatv with the diagnostic's arguments.
  100. auto FormatFn(const Diagnostic& diagnostic) const -> std::string {
  101. return FormatFnImpl(diagnostic,
  102. std::make_index_sequence<sizeof...(Args)>());
  103. };
  104. // The diagnostic's kind.
  105. DiagnosticKind Kind;
  106. // The diagnostic's level.
  107. DiagnosticLevel Level;
  108. // The diagnostic's format for llvm::formatv.
  109. llvm::StringLiteral Format;
  110. private:
  111. // Handles the cast of llvm::Any to Args types for formatv.
  112. template <std::size_t... N>
  113. inline auto FormatFnImpl(const Diagnostic& diagnostic,
  114. std::index_sequence<N...> /*indices*/) const
  115. -> std::string {
  116. assert(diagnostic.format_args.size() == sizeof...(Args));
  117. return llvm::formatv(diagnostic.format.data(),
  118. llvm::any_cast<Args>(diagnostic.format_args[N])...);
  119. }
  120. };
  121. } // namespace Internal
  122. // Manages the creation of reports, the testing if diagnostics are enabled, and
  123. // the collection of reports.
  124. //
  125. // This class is parameterized by a location type, allowing different
  126. // diagnostic clients to provide location information in whatever form is most
  127. // convenient for them, such as a position within a buffer when lexing, a token
  128. // when parsing, or a parse tree node when type-checking, and to allow unit
  129. // tests to be decoupled from any concrete location representation.
  130. template <typename LocationT>
  131. class DiagnosticEmitter {
  132. public:
  133. // The `translator` and `consumer` are required to outlive the diagnostic
  134. // emitter.
  135. explicit DiagnosticEmitter(
  136. DiagnosticLocationTranslator<LocationT>& translator,
  137. DiagnosticConsumer& consumer)
  138. : translator_(&translator), consumer_(&consumer) {}
  139. ~DiagnosticEmitter() = default;
  140. // Emits an error.
  141. //
  142. // When passing arguments, they may be buffered. As a consequence, lifetimes
  143. // may outlive the `Emit` call.
  144. template <typename... Args>
  145. void Emit(LocationT location,
  146. const Internal::DiagnosticBase<Args...>& diagnostic_base,
  147. // Disable type deduction based on `args`; the type of
  148. // `diagnostic_base` determines the diagnostic's parameter types.
  149. typename std::common_type_t<Args>... args) {
  150. consumer_->HandleDiagnostic({
  151. .kind = diagnostic_base.Kind,
  152. .level = diagnostic_base.Level,
  153. .location = translator_->GetLocation(location),
  154. .format = diagnostic_base.Format,
  155. .format_args = {std::move(args)...},
  156. .format_fn = [&diagnostic_base](const Diagnostic& diagnostic)
  157. -> std::string { return diagnostic_base.FormatFn(diagnostic); },
  158. });
  159. }
  160. private:
  161. DiagnosticLocationTranslator<LocationT>* translator_;
  162. DiagnosticConsumer* consumer_;
  163. };
  164. inline auto ConsoleDiagnosticConsumer() -> DiagnosticConsumer& {
  165. struct Consumer : DiagnosticConsumer {
  166. auto HandleDiagnostic(const Diagnostic& diagnostic) -> void override {
  167. llvm::errs() << diagnostic.location.file_name << ":"
  168. << diagnostic.location.line_number << ":"
  169. << diagnostic.location.column_number << ": "
  170. << diagnostic.format_fn(diagnostic) << "\n";
  171. }
  172. };
  173. static auto* consumer = new Consumer;
  174. return *consumer;
  175. }
  176. // Diagnostic consumer adaptor that tracks whether any errors have been
  177. // produced.
  178. class ErrorTrackingDiagnosticConsumer : public DiagnosticConsumer {
  179. public:
  180. explicit ErrorTrackingDiagnosticConsumer(DiagnosticConsumer& next_consumer)
  181. : next_consumer_(&next_consumer) {}
  182. auto HandleDiagnostic(const Diagnostic& diagnostic) -> void override {
  183. seen_error_ |= diagnostic.level == DiagnosticLevel::Error;
  184. next_consumer_->HandleDiagnostic(diagnostic);
  185. }
  186. // Reset whether we've seen an error.
  187. auto Reset() -> void { seen_error_ = false; }
  188. // Returns whether we've seen an error since the last reset.
  189. auto seen_error() const -> bool { return seen_error_; }
  190. private:
  191. DiagnosticConsumer* next_consumer_;
  192. bool seen_error_ = false;
  193. };
  194. } // namespace Carbon
  195. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_DIAGNOSTIC_EMITTER_H_