diagnostic.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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_H_
  5. #define CARBON_TOOLCHAIN_DIAGNOSTICS_DIAGNOSTIC_H_
  6. #include <cstdint>
  7. #include <functional>
  8. #include <string>
  9. #include "common/check.h"
  10. #include "llvm/ADT/Any.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StringRef.h"
  13. #include "toolchain/diagnostics/kind.h"
  14. namespace Carbon::Diagnostics {
  15. enum class Level : int8_t {
  16. // Information about the location of another diagnostic, showing how we
  17. // reached that location. This is currently only used for the "in import"
  18. // message.
  19. LocationInfo,
  20. // A note, not indicating an error on its own, but possibly providing
  21. // additional information for an error or warning.
  22. Note,
  23. // A Context that will be discarded if another Context precedes it in the
  24. // diagnostic, as the Context is assumed to provide better information. Used
  25. // as a fallback for when no better Context is provided.
  26. SoftContext,
  27. // Describes the high level operation being performed. If a diagnostic is
  28. // issued, the first Context message will steal its level and be displayed as
  29. // if it is the top-level diagnostic, and the rest are treated as Note
  30. // messages. The diagnostic message also becomes a Note of the first Context
  31. // message.
  32. Context,
  33. // A warning diagnostic, indicating a likely problem with the program.
  34. Warning,
  35. // An error diagnostic, indicating that the program is not valid.
  36. Error,
  37. };
  38. // Provides a definition of a diagnostic. For example:
  39. // CARBON_DIAGNOSTIC(MyDiagnostic, Error, "invalid code!");
  40. // CARBON_DIAGNOSTIC(MyDiagnostic, Warning, "found {0}, expected {1}",
  41. // std::string, std::string);
  42. //
  43. // Arguments are passed to llvm::formatv; see:
  44. // https://llvm.org/doxygen/FormatVariadic_8h_source.html
  45. //
  46. // See `Diagnostics::Emitter::Emit` for comments about argument lifetimes.
  47. #define CARBON_DIAGNOSTIC(DiagnosticName, LevelValue, Format, ...) \
  48. static constexpr auto DiagnosticName = \
  49. ::Carbon::Diagnostics::DiagnosticBase<__VA_ARGS__>( \
  50. ::Carbon::Diagnostics::Kind::DiagnosticName, \
  51. ::Carbon::Diagnostics::Level::LevelValue, /*is_on_scope=*/false, \
  52. Format)
  53. // Similar to `CARBON_DIAGNOSTIC`, but for diagnostics that are generated on a
  54. // scope; see `Diagnostic::is_on_scope` for details.
  55. #define CARBON_DIAGNOSTIC_ON_SCOPE(DiagnosticName, LevelValue, Format, ...) \
  56. static_assert(::Carbon::Diagnostics::Level::LevelValue == \
  57. ::Carbon::Diagnostics::Level::Warning || \
  58. ::Carbon::Diagnostics::Level::LevelValue == \
  59. ::Carbon::Diagnostics::Level::Error, \
  60. "Only use CARBON_DIAGNOSTIC_ON_SCOPE for the main " \
  61. "diagnostic, not notes"); \
  62. static constexpr auto DiagnosticName = \
  63. ::Carbon::Diagnostics::DiagnosticBase<__VA_ARGS__>( \
  64. ::Carbon::Diagnostics::Kind::DiagnosticName, \
  65. ::Carbon::Diagnostics::Level::LevelValue, /*is_on_scope=*/true, \
  66. Format)
  67. // A location for a diagnostic in a file. The lifetime of a Loc
  68. // is required to be less than SourceBuffer that it refers to due to the
  69. // contained filename and line references.
  70. struct Loc {
  71. // Writes the location to the given stream. It will be formatted as
  72. // `<filename>:<line_number>:<column_number>: ` with parts dropped when
  73. // unknown.
  74. auto FormatLocation(llvm::raw_ostream& out) const -> void;
  75. // Write the source snippet corresponding to this location to the given
  76. // stream.
  77. auto FormatSnippet(llvm::raw_ostream& out, int indent = 0) const -> void;
  78. // Name of the file or buffer that this diagnostic refers to.
  79. llvm::StringRef filename;
  80. // A reference to the line of the error.
  81. llvm::StringRef line;
  82. // A full snippet to print. If non-empty, this is used instead of `line` when
  83. // printing a snippet. Should contain both the quoted text and the caret line.
  84. std::string snippet;
  85. // 1-based line number. -1 indicates unknown; other values are unused.
  86. int32_t line_number = -1;
  87. // 1-based column number. -1 indicates unknown; other values are unused.
  88. int32_t column_number = -1;
  89. // The number of characters corresponding to the location in the line,
  90. // starting at column_number. Should always be at least 1.
  91. int32_t length = 1;
  92. };
  93. // A message composing a diagnostic. This may be the main message, but can also
  94. // be notes providing more information.
  95. struct Message {
  96. // Helper for calling `format_fn`.
  97. auto Format() const -> std::string { return format_fn(*this); }
  98. // The diagnostic's kind.
  99. Kind kind;
  100. // The message's level. This may be different from, but should not be more
  101. // severe than, the diagnostic's level.
  102. Level level;
  103. // The calculated location of the diagnostic.
  104. Loc loc;
  105. // The diagnostic's format string. This, along with format_args, will be
  106. // passed to format_fn.
  107. llvm::StringLiteral format;
  108. // A list of format arguments.
  109. //
  110. // These may be used by non-standard consumers to inspect diagnostic details
  111. // without needing to parse the formatted string; however, it should be
  112. // understood that diagnostic formats are subject to change and the llvm::Any
  113. // offers limited compile-time type safety. Integration tests are required.
  114. llvm::SmallVector<llvm::Any> format_args;
  115. // Returns the formatted string. By default, this uses llvm::formatv.
  116. std::function<auto(const Message&)->std::string> format_fn;
  117. };
  118. // An instance of a single error or warning. Information about the diagnostic
  119. // can be recorded into it for more complex consumers.
  120. struct Diagnostic {
  121. // The diagnostic's level.
  122. Level level;
  123. // Whether a diagnostic should only sort by `last_byte_offset` (which is
  124. // normal), or if it's generated on a scope and should be sorted based on the
  125. // first message's line and column when the `last_byte_offset` is equal.
  126. // This is used by `SortingConsumer`.
  127. bool is_on_scope;
  128. // The byte offset of the final token which is associated with the diagnostic.
  129. // This is used by `SortingConsumer`. This is separate from the
  130. // `Loc` because it must refer to a position in the primary file
  131. // being processed by a consumer, and has no use cross-file or in notes.
  132. //
  133. // This will usually be the start position (not end) of the last lexed token
  134. // processed before the diagnostic; it could also be `-1` when no source code
  135. // needs to be processed for a diagnostic, or an appropriate byte offset when
  136. // we specifically want a different diagnostic ordering than when a diagnostic
  137. // is issued.
  138. int32_t last_byte_offset = -1;
  139. // Messages related to the diagnostic. Only one should be a warning or error;
  140. // other messages provide context.
  141. llvm::SmallVector<Message> messages;
  142. };
  143. // Use the DIAGNOSTIC macro to instantiate this.
  144. // This stores static information about a diagnostic category.
  145. template <typename... Args>
  146. struct DiagnosticBase {
  147. explicit constexpr DiagnosticBase(Kind kind, Level level, bool is_on_scope,
  148. llvm::StringLiteral format)
  149. : Kind(kind), Level(level), IsOnScope(is_on_scope), Format(format) {
  150. static_assert((... && !(std::is_same_v<Args, llvm::StringRef> ||
  151. std::is_same_v<Args, llvm::StringLiteral>)),
  152. "String type disallowed in diagnostics. See "
  153. "https://github.com/carbon-language/carbon-lang/blob/trunk/"
  154. "toolchain/docs/diagnostics.md#diagnostic-parameter-types");
  155. }
  156. // The diagnostic's kind.
  157. Kind Kind;
  158. // The diagnostic's level.
  159. Level Level;
  160. // See `Diagnostic::is_on_scope`.
  161. bool IsOnScope;
  162. // The diagnostic's format for llvm::formatv.
  163. llvm::StringLiteral Format;
  164. };
  165. } // namespace Carbon::Diagnostics
  166. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_DIAGNOSTIC_H_