format_providers.h 2.3 KB

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