diagnostic_converter.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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_CONVERTER_H_
  5. #define CARBON_TOOLCHAIN_DIAGNOSTICS_DIAGNOSTIC_CONVERTER_H_
  6. #include "llvm/ADT/Any.h"
  7. #include "toolchain/diagnostics/diagnostic.h"
  8. namespace Carbon {
  9. // An interface that can convert some representation of a location into a
  10. // diagnostic location.
  11. template <typename LocT>
  12. class DiagnosticConverter {
  13. public:
  14. // Callback type used to report context messages from ConvertLoc.
  15. // Note that the first parameter type is DiagnosticLoc rather than
  16. // LocT, because ConvertLoc must not recurse.
  17. using ContextFnT =
  18. llvm::function_ref<void(DiagnosticLoc, const DiagnosticBase<>&)>;
  19. virtual ~DiagnosticConverter() = default;
  20. // Converts a LocT to a DiagnosticLoc. ConvertLoc may invoke
  21. // context_fn to provide context messages.
  22. virtual auto ConvertLoc(LocT loc, ContextFnT context_fn) const
  23. -> DiagnosticLoc = 0;
  24. // Converts arg types as needed. Not all uses require conversion, so the
  25. // default returns the argument unchanged.
  26. virtual auto ConvertArg(llvm::Any arg) const -> llvm::Any { return arg; }
  27. };
  28. // Used by types to indicate a diagnostic type conversion that results in the
  29. // provided StorageType. For example, to convert NameId to a std::string, we
  30. // write:
  31. //
  32. // struct NameId {
  33. // using DiagnosticType = DiagnosticTypeInfo<std::string>;
  34. // };
  35. template <typename StorageTypeT>
  36. struct DiagnosticTypeInfo {
  37. using StorageType = StorageTypeT;
  38. };
  39. namespace Internal {
  40. // Determines whether there's a DiagnosticType member on Arg.
  41. // Used by DiagnosticEmitter.
  42. template <typename Arg>
  43. concept HasDiagnosticType = requires { typename Arg::DiagnosticType; };
  44. // The default implementation with no conversion.
  45. template <typename Arg>
  46. struct DiagnosticTypeForArg : public DiagnosticTypeInfo<Arg> {};
  47. // Exposes a custom conversion for an argument type.
  48. template <typename Arg>
  49. requires HasDiagnosticType<Arg>
  50. struct DiagnosticTypeForArg<Arg> : public Arg::DiagnosticType {};
  51. } // namespace Internal
  52. } // namespace Carbon
  53. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_DIAGNOSTIC_CONVERTER_H_