format_providers.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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_FORMAT_PROVIDERS_H_
  5. #define CARBON_TOOLCHAIN_DIAGNOSTICS_FORMAT_PROVIDERS_H_
  6. #include "common/ostream.h"
  7. #include "llvm/Support/FormatVariadicDetails.h"
  8. namespace Carbon::Diagnostics {
  9. // Selects a formatv string based on the value.
  10. //
  11. // Supported format styles are:
  12. // - None, as in `{0}`. This uses standard integer formatting.
  13. // - Selector, as in `{0:true|false}`. The output string used is separated by a
  14. // `|`, with the true case first. the example would yield standard bool
  15. // formatting.
  16. struct BoolAsSelect {
  17. explicit(false) BoolAsSelect(bool value) : value(value) {}
  18. bool value;
  19. };
  20. // Selects a formatv string based on the value.
  21. //
  22. // Supported format styles are:
  23. // - None, as in `{0}`. This uses standard integer formatting.
  24. // - Selector, as in `{0:=0:zero|:default}`. This is detailed below.
  25. // - Plural `s`, as in `{0:s}`. This outputs an `s` when the value is not 1,
  26. // equivalent to `{0:=1:|:s}`.
  27. //
  28. // The style is a series of match cases, separated by `|`. Each case is a pair
  29. // formatted as `<selector>:<output string>`.
  30. //
  31. // Supported selectors are:
  32. // - `=<value>`: Matches when the value is correct.
  33. // - Empty for the default. This is optional, although it's a fatal error to not
  34. // handle a value. If provided, it must be last.
  35. //
  36. // For example, `{0:=0:zero|=1:one|:other}` breaks down into:
  37. // - `=0` -> `zero`
  38. // - `=1` -> `one`
  39. // - default -> `other`
  40. //
  41. // As another example, `{0:=1:is|:are}` is a way to handle plural-based output.
  42. struct IntAsSelect {
  43. explicit(false) IntAsSelect(int value) : value(value) {}
  44. int value;
  45. };
  46. } // namespace Carbon::Diagnostics
  47. // See Diagnostics::BoolAsSelect.
  48. template <>
  49. struct llvm::format_provider<Carbon::Diagnostics::BoolAsSelect> {
  50. static auto format(const Carbon::Diagnostics::BoolAsSelect& wrapper,
  51. raw_ostream& out, StringRef style) -> void;
  52. };
  53. // See Diagnostics::IntAsSelect.
  54. template <>
  55. struct llvm::format_provider<Carbon::Diagnostics::IntAsSelect> {
  56. static auto format(const Carbon::Diagnostics::IntAsSelect& wrapper,
  57. raw_ostream& out, StringRef style) -> void;
  58. };
  59. #endif // CARBON_TOOLCHAIN_DIAGNOSTICS_FORMAT_PROVIDERS_H_