You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3323 lines
109 KiB

  1. // Formatting library for C++ - the core API for char/UTF-8
  2. //
  3. // Copyright (c) 2012 - present, Victor Zverovich
  4. // All rights reserved.
  5. //
  6. // For the license information refer to format.h.
  7. #ifndef FMT_CORE_H_
  8. #define FMT_CORE_H_
  9. #include <cstddef> // std::byte
  10. #include <cstdio> // std::FILE
  11. #include <cstring> // std::strlen
  12. #include <iterator>
  13. #include <limits>
  14. #include <string>
  15. #include <type_traits>
  16. // The fmt library version in the form major * 10000 + minor * 100 + patch.
  17. #define FMT_VERSION 90100
  18. #if defined(__clang__) && !defined(__ibmxl__)
  19. # define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
  20. #else
  21. # define FMT_CLANG_VERSION 0
  22. #endif
  23. #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && \
  24. !defined(__NVCOMPILER)
  25. # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  26. #else
  27. # define FMT_GCC_VERSION 0
  28. #endif
  29. #ifndef FMT_GCC_PRAGMA
  30. // Workaround _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884.
  31. # if FMT_GCC_VERSION >= 504
  32. # define FMT_GCC_PRAGMA(arg) _Pragma(arg)
  33. # else
  34. # define FMT_GCC_PRAGMA(arg)
  35. # endif
  36. #endif
  37. #ifdef __ICL
  38. # define FMT_ICC_VERSION __ICL
  39. #elif defined(__INTEL_COMPILER)
  40. # define FMT_ICC_VERSION __INTEL_COMPILER
  41. #else
  42. # define FMT_ICC_VERSION 0
  43. #endif
  44. #ifdef _MSC_VER
  45. # define FMT_MSC_VERSION _MSC_VER
  46. # define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__))
  47. #else
  48. # define FMT_MSC_VERSION 0
  49. # define FMT_MSC_WARNING(...)
  50. #endif
  51. #ifdef _MSVC_LANG
  52. # define FMT_CPLUSPLUS _MSVC_LANG
  53. #else
  54. # define FMT_CPLUSPLUS __cplusplus
  55. #endif
  56. #ifdef __has_feature
  57. # define FMT_HAS_FEATURE(x) __has_feature(x)
  58. #else
  59. # define FMT_HAS_FEATURE(x) 0
  60. #endif
  61. #if (defined(__has_include) || FMT_ICC_VERSION >= 1600 || \
  62. FMT_MSC_VERSION > 1900) && \
  63. !defined(__INTELLISENSE__)
  64. # define FMT_HAS_INCLUDE(x) __has_include(x)
  65. #else
  66. # define FMT_HAS_INCLUDE(x) 0
  67. #endif
  68. #ifdef __has_cpp_attribute
  69. # define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
  70. #else
  71. # define FMT_HAS_CPP_ATTRIBUTE(x) 0
  72. #endif
  73. #define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
  74. (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
  75. #define FMT_HAS_CPP17_ATTRIBUTE(attribute) \
  76. (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))
  77. // Check if relaxed C++14 constexpr is supported.
  78. // GCC doesn't allow throw in constexpr until version 6 (bug 67371).
  79. #ifndef FMT_USE_CONSTEXPR
  80. # if (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912 || \
  81. (FMT_GCC_VERSION >= 600 && FMT_CPLUSPLUS >= 201402L)) && \
  82. !FMT_ICC_VERSION && !defined(__NVCC__)
  83. # define FMT_USE_CONSTEXPR 1
  84. # else
  85. # define FMT_USE_CONSTEXPR 0
  86. # endif
  87. #endif
  88. #if FMT_USE_CONSTEXPR
  89. # define FMT_CONSTEXPR constexpr
  90. #else
  91. # define FMT_CONSTEXPR
  92. #endif
  93. #if ((FMT_CPLUSPLUS >= 202002L) && \
  94. (!defined(_GLIBCXX_RELEASE) || _GLIBCXX_RELEASE > 9)) || \
  95. (FMT_CPLUSPLUS >= 201709L && FMT_GCC_VERSION >= 1002)
  96. # define FMT_CONSTEXPR20 constexpr
  97. #else
  98. # define FMT_CONSTEXPR20
  99. #endif
  100. // Check if constexpr std::char_traits<>::{compare,length} are supported.
  101. #if defined(__GLIBCXX__)
  102. # if FMT_CPLUSPLUS >= 201703L && defined(_GLIBCXX_RELEASE) && \
  103. _GLIBCXX_RELEASE >= 7 // GCC 7+ libstdc++ has _GLIBCXX_RELEASE.
  104. # define FMT_CONSTEXPR_CHAR_TRAITS constexpr
  105. # endif
  106. #elif defined(_LIBCPP_VERSION) && FMT_CPLUSPLUS >= 201703L && \
  107. _LIBCPP_VERSION >= 4000
  108. # define FMT_CONSTEXPR_CHAR_TRAITS constexpr
  109. #elif FMT_MSC_VERSION >= 1914 && FMT_CPLUSPLUS >= 201703L
  110. # define FMT_CONSTEXPR_CHAR_TRAITS constexpr
  111. #endif
  112. #ifndef FMT_CONSTEXPR_CHAR_TRAITS
  113. # define FMT_CONSTEXPR_CHAR_TRAITS
  114. #endif
  115. // Check if exceptions are disabled.
  116. #ifndef FMT_EXCEPTIONS
  117. # if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \
  118. (FMT_MSC_VERSION && !_HAS_EXCEPTIONS)
  119. # define FMT_EXCEPTIONS 0
  120. # else
  121. # define FMT_EXCEPTIONS 1
  122. # endif
  123. #endif
  124. #ifndef FMT_DEPRECATED
  125. # if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VERSION >= 1900
  126. # define FMT_DEPRECATED [[deprecated]]
  127. # else
  128. # if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__)
  129. # define FMT_DEPRECATED __attribute__((deprecated))
  130. # elif FMT_MSC_VERSION
  131. # define FMT_DEPRECATED __declspec(deprecated)
  132. # else
  133. # define FMT_DEPRECATED /* deprecated */
  134. # endif
  135. # endif
  136. #endif
  137. // [[noreturn]] is disabled on MSVC and NVCC because of bogus unreachable code
  138. // warnings.
  139. #if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && \
  140. !defined(__NVCC__)
  141. # define FMT_NORETURN [[noreturn]]
  142. #else
  143. # define FMT_NORETURN
  144. #endif
  145. #if FMT_HAS_CPP17_ATTRIBUTE(fallthrough)
  146. # define FMT_FALLTHROUGH [[fallthrough]]
  147. #elif defined(__clang__)
  148. # define FMT_FALLTHROUGH [[clang::fallthrough]]
  149. #elif FMT_GCC_VERSION >= 700 && \
  150. (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)
  151. # define FMT_FALLTHROUGH [[gnu::fallthrough]]
  152. #else
  153. # define FMT_FALLTHROUGH
  154. #endif
  155. #ifndef FMT_NODISCARD
  156. # if FMT_HAS_CPP17_ATTRIBUTE(nodiscard)
  157. # define FMT_NODISCARD [[nodiscard]]
  158. # else
  159. # define FMT_NODISCARD
  160. # endif
  161. #endif
  162. #ifndef FMT_USE_FLOAT
  163. # define FMT_USE_FLOAT 1
  164. #endif
  165. #ifndef FMT_USE_DOUBLE
  166. # define FMT_USE_DOUBLE 1
  167. #endif
  168. #ifndef FMT_USE_LONG_DOUBLE
  169. # define FMT_USE_LONG_DOUBLE 1
  170. #endif
  171. #ifndef FMT_INLINE
  172. # if FMT_GCC_VERSION || FMT_CLANG_VERSION
  173. # define FMT_INLINE inline __attribute__((always_inline))
  174. # else
  175. # define FMT_INLINE inline
  176. # endif
  177. #endif
  178. // An inline std::forward replacement.
  179. #define FMT_FORWARD(...) static_cast<decltype(__VA_ARGS__)&&>(__VA_ARGS__)
  180. #ifdef _MSC_VER
  181. # define FMT_UNCHECKED_ITERATOR(It) \
  182. using _Unchecked_type = It // Mark iterator as checked.
  183. #else
  184. # define FMT_UNCHECKED_ITERATOR(It) using unchecked_type = It
  185. #endif
  186. #ifndef FMT_BEGIN_NAMESPACE
  187. # define FMT_BEGIN_NAMESPACE \
  188. namespace fmt { \
  189. inline namespace v9 {
  190. # define FMT_END_NAMESPACE \
  191. } \
  192. }
  193. #endif
  194. #ifndef FMT_MODULE_EXPORT
  195. # define FMT_MODULE_EXPORT
  196. # define FMT_MODULE_EXPORT_BEGIN
  197. # define FMT_MODULE_EXPORT_END
  198. # define FMT_BEGIN_DETAIL_NAMESPACE namespace detail {
  199. # define FMT_END_DETAIL_NAMESPACE }
  200. #endif
  201. #if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
  202. # define FMT_CLASS_API FMT_MSC_WARNING(suppress : 4275)
  203. # ifdef FMT_EXPORT
  204. # define FMT_API __declspec(dllexport)
  205. # elif defined(FMT_SHARED)
  206. # define FMT_API __declspec(dllimport)
  207. # endif
  208. #else
  209. # define FMT_CLASS_API
  210. # if defined(FMT_EXPORT) || defined(FMT_SHARED)
  211. # if defined(__GNUC__) || defined(__clang__)
  212. # define FMT_API __attribute__((visibility("default")))
  213. # endif
  214. # endif
  215. #endif
  216. #ifndef FMT_API
  217. # define FMT_API
  218. #endif
  219. // libc++ supports string_view in pre-c++17.
  220. #if FMT_HAS_INCLUDE(<string_view>) && \
  221. (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION))
  222. # include <string_view>
  223. # define FMT_USE_STRING_VIEW
  224. #elif FMT_HAS_INCLUDE("experimental/string_view") && FMT_CPLUSPLUS >= 201402L
  225. # include <experimental/string_view>
  226. # define FMT_USE_EXPERIMENTAL_STRING_VIEW
  227. #endif
  228. #ifndef FMT_UNICODE
  229. # define FMT_UNICODE !FMT_MSC_VERSION
  230. #endif
  231. #ifndef FMT_CONSTEVAL
  232. # if ((FMT_GCC_VERSION >= 1000 || FMT_CLANG_VERSION >= 1101) && \
  233. FMT_CPLUSPLUS >= 202002L && !defined(__apple_build_version__)) || \
  234. (defined(__cpp_consteval) && \
  235. (!FMT_MSC_VERSION || _MSC_FULL_VER >= 193030704))
  236. // consteval is broken in MSVC before VS2022 and Apple clang 13.
  237. # define FMT_CONSTEVAL consteval
  238. # define FMT_HAS_CONSTEVAL
  239. # else
  240. # define FMT_CONSTEVAL
  241. # endif
  242. #endif
  243. #ifndef FMT_USE_NONTYPE_TEMPLATE_ARGS
  244. # if defined(__cpp_nontype_template_args) && \
  245. ((FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L) || \
  246. __cpp_nontype_template_args >= 201911L) && \
  247. !defined(__NVCOMPILER)
  248. # define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
  249. # else
  250. # define FMT_USE_NONTYPE_TEMPLATE_ARGS 0
  251. # endif
  252. #endif
  253. // Enable minimal optimizations for more compact code in debug mode.
  254. FMT_GCC_PRAGMA("GCC push_options")
  255. #if !defined(__OPTIMIZE__) && !defined(__NVCOMPILER)
  256. FMT_GCC_PRAGMA("GCC optimize(\"Og\")")
  257. #endif
  258. FMT_BEGIN_NAMESPACE
  259. FMT_MODULE_EXPORT_BEGIN
  260. // Implementations of enable_if_t and other metafunctions for older systems.
  261. template <bool B, typename T = void>
  262. using enable_if_t = typename std::enable_if<B, T>::type;
  263. template <bool B, typename T, typename F>
  264. using conditional_t = typename std::conditional<B, T, F>::type;
  265. template <bool B> using bool_constant = std::integral_constant<bool, B>;
  266. template <typename T>
  267. using remove_reference_t = typename std::remove_reference<T>::type;
  268. template <typename T>
  269. using remove_const_t = typename std::remove_const<T>::type;
  270. template <typename T>
  271. using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
  272. template <typename T> struct type_identity { using type = T; };
  273. template <typename T> using type_identity_t = typename type_identity<T>::type;
  274. template <typename T>
  275. using underlying_t = typename std::underlying_type<T>::type;
  276. template <typename...> struct disjunction : std::false_type {};
  277. template <typename P> struct disjunction<P> : P {};
  278. template <typename P1, typename... Pn>
  279. struct disjunction<P1, Pn...>
  280. : conditional_t<bool(P1::value), P1, disjunction<Pn...>> {};
  281. template <typename...> struct conjunction : std::true_type {};
  282. template <typename P> struct conjunction<P> : P {};
  283. template <typename P1, typename... Pn>
  284. struct conjunction<P1, Pn...>
  285. : conditional_t<bool(P1::value), conjunction<Pn...>, P1> {};
  286. struct monostate {
  287. constexpr monostate() {}
  288. };
  289. // An enable_if helper to be used in template parameters which results in much
  290. // shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed
  291. // to workaround a bug in MSVC 2019 (see #1140 and #1186).
  292. #ifdef FMT_DOC
  293. # define FMT_ENABLE_IF(...)
  294. #else
  295. # define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0
  296. #endif
  297. FMT_BEGIN_DETAIL_NAMESPACE
  298. // Suppresses "unused variable" warnings with the method described in
  299. // https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/.
  300. // (void)var does not work on many Intel compilers.
  301. template <typename... T> FMT_CONSTEXPR void ignore_unused(const T&...) {}
  302. constexpr FMT_INLINE auto is_constant_evaluated(
  303. bool default_value = false) noexcept -> bool {
  304. #ifdef __cpp_lib_is_constant_evaluated
  305. ignore_unused(default_value);
  306. return std::is_constant_evaluated();
  307. #else
  308. return default_value;
  309. #endif
  310. }
  311. // Suppresses "conditional expression is constant" warnings.
  312. template <typename T> constexpr FMT_INLINE auto const_check(T value) -> T {
  313. return value;
  314. }
  315. FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
  316. const char* message);
  317. #ifndef FMT_ASSERT
  318. # ifdef NDEBUG
  319. // FMT_ASSERT is not empty to avoid -Wempty-body.
  320. # define FMT_ASSERT(condition, message) \
  321. ::fmt::detail::ignore_unused((condition), (message))
  322. # else
  323. # define FMT_ASSERT(condition, message) \
  324. ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
  325. ? (void)0 \
  326. : ::fmt::detail::assert_fail(__FILE__, __LINE__, (message)))
  327. # endif
  328. #endif
  329. #if defined(FMT_USE_STRING_VIEW)
  330. template <typename Char> using std_string_view = std::basic_string_view<Char>;
  331. #elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW)
  332. template <typename Char>
  333. using std_string_view = std::experimental::basic_string_view<Char>;
  334. #else
  335. template <typename T> struct std_string_view {};
  336. #endif
  337. #ifdef FMT_USE_INT128
  338. // Do nothing.
  339. #elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \
  340. !(FMT_CLANG_VERSION && FMT_MSC_VERSION)
  341. # define FMT_USE_INT128 1
  342. using int128_opt = __int128_t; // An optional native 128-bit integer.
  343. using uint128_opt = __uint128_t;
  344. template <typename T> inline auto convert_for_visit(T value) -> T {
  345. return value;
  346. }
  347. #else
  348. # define FMT_USE_INT128 0
  349. #endif
  350. #if !FMT_USE_INT128
  351. enum class int128_opt {};
  352. enum class uint128_opt {};
  353. // Reduce template instantiations.
  354. template <typename T> auto convert_for_visit(T) -> monostate { return {}; }
  355. #endif
  356. // Casts a nonnegative integer to unsigned.
  357. template <typename Int>
  358. FMT_CONSTEXPR auto to_unsigned(Int value) ->
  359. typename std::make_unsigned<Int>::type {
  360. FMT_ASSERT(std::is_unsigned<Int>::value || value >= 0, "negative value");
  361. return static_cast<typename std::make_unsigned<Int>::type>(value);
  362. }
  363. FMT_MSC_WARNING(suppress : 4566) constexpr unsigned char micro[] = "\u00B5";
  364. constexpr auto is_utf8() -> bool {
  365. // Avoid buggy sign extensions in MSVC's constant evaluation mode (#2297).
  366. using uchar = unsigned char;
  367. return FMT_UNICODE || (sizeof(micro) == 3 && uchar(micro[0]) == 0xC2 &&
  368. uchar(micro[1]) == 0xB5);
  369. }
  370. FMT_END_DETAIL_NAMESPACE
  371. /**
  372. An implementation of ``std::basic_string_view`` for pre-C++17. It provides a
  373. subset of the API. ``fmt::basic_string_view`` is used for format strings even
  374. if ``std::string_view`` is available to prevent issues when a library is
  375. compiled with a different ``-std`` option than the client code (which is not
  376. recommended).
  377. */
  378. template <typename Char> class basic_string_view {
  379. private:
  380. const Char* data_;
  381. size_t size_;
  382. public:
  383. using value_type = Char;
  384. using iterator = const Char*;
  385. constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {}
  386. /** Constructs a string reference object from a C string and a size. */
  387. constexpr basic_string_view(const Char* s, size_t count) noexcept
  388. : data_(s), size_(count) {}
  389. /**
  390. \rst
  391. Constructs a string reference object from a C string computing
  392. the size with ``std::char_traits<Char>::length``.
  393. \endrst
  394. */
  395. FMT_CONSTEXPR_CHAR_TRAITS
  396. FMT_INLINE
  397. basic_string_view(const Char* s)
  398. : data_(s),
  399. size_(detail::const_check(std::is_same<Char, char>::value &&
  400. !detail::is_constant_evaluated(true))
  401. ? std::strlen(reinterpret_cast<const char*>(s))
  402. : std::char_traits<Char>::length(s)) {}
  403. /** Constructs a string reference from a ``std::basic_string`` object. */
  404. template <typename Traits, typename Alloc>
  405. FMT_CONSTEXPR basic_string_view(
  406. const std::basic_string<Char, Traits, Alloc>& s) noexcept
  407. : data_(s.data()), size_(s.size()) {}
  408. template <typename S, FMT_ENABLE_IF(std::is_same<
  409. S, detail::std_string_view<Char>>::value)>
  410. FMT_CONSTEXPR basic_string_view(S s) noexcept
  411. : data_(s.data()), size_(s.size()) {}
  412. /** Returns a pointer to the string data. */
  413. constexpr auto data() const noexcept -> const Char* { return data_; }
  414. /** Returns the string size. */
  415. constexpr auto size() const noexcept -> size_t { return size_; }
  416. constexpr auto begin() const noexcept -> iterator { return data_; }
  417. constexpr auto end() const noexcept -> iterator { return data_ + size_; }
  418. constexpr auto operator[](size_t pos) const noexcept -> const Char& {
  419. return data_[pos];
  420. }
  421. FMT_CONSTEXPR void remove_prefix(size_t n) noexcept {
  422. data_ += n;
  423. size_ -= n;
  424. }
  425. // Lexicographically compare this string reference to other.
  426. FMT_CONSTEXPR_CHAR_TRAITS auto compare(basic_string_view other) const -> int {
  427. size_t str_size = size_ < other.size_ ? size_ : other.size_;
  428. int result = std::char_traits<Char>::compare(data_, other.data_, str_size);
  429. if (result == 0)
  430. result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
  431. return result;
  432. }
  433. FMT_CONSTEXPR_CHAR_TRAITS friend auto operator==(basic_string_view lhs,
  434. basic_string_view rhs)
  435. -> bool {
  436. return lhs.compare(rhs) == 0;
  437. }
  438. friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool {
  439. return lhs.compare(rhs) != 0;
  440. }
  441. friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool {
  442. return lhs.compare(rhs) < 0;
  443. }
  444. friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool {
  445. return lhs.compare(rhs) <= 0;
  446. }
  447. friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool {
  448. return lhs.compare(rhs) > 0;
  449. }
  450. friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool {
  451. return lhs.compare(rhs) >= 0;
  452. }
  453. };
  454. using string_view = basic_string_view<char>;
  455. /** Specifies if ``T`` is a character type. Can be specialized by users. */
  456. template <typename T> struct is_char : std::false_type {};
  457. template <> struct is_char<char> : std::true_type {};
  458. FMT_BEGIN_DETAIL_NAMESPACE
  459. // A base class for compile-time strings.
  460. struct compile_string {};
  461. template <typename S>
  462. struct is_compile_string : std::is_base_of<compile_string, S> {};
  463. // Returns a string view of `s`.
  464. template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
  465. FMT_INLINE auto to_string_view(const Char* s) -> basic_string_view<Char> {
  466. return s;
  467. }
  468. template <typename Char, typename Traits, typename Alloc>
  469. inline auto to_string_view(const std::basic_string<Char, Traits, Alloc>& s)
  470. -> basic_string_view<Char> {
  471. return s;
  472. }
  473. template <typename Char>
  474. constexpr auto to_string_view(basic_string_view<Char> s)
  475. -> basic_string_view<Char> {
  476. return s;
  477. }
  478. template <typename Char,
  479. FMT_ENABLE_IF(!std::is_empty<std_string_view<Char>>::value)>
  480. inline auto to_string_view(std_string_view<Char> s) -> basic_string_view<Char> {
  481. return s;
  482. }
  483. template <typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
  484. constexpr auto to_string_view(const S& s)
  485. -> basic_string_view<typename S::char_type> {
  486. return basic_string_view<typename S::char_type>(s);
  487. }
  488. void to_string_view(...);
  489. // Specifies whether S is a string type convertible to fmt::basic_string_view.
  490. // It should be a constexpr function but MSVC 2017 fails to compile it in
  491. // enable_if and MSVC 2015 fails to compile it as an alias template.
  492. // ADL invocation of to_string_view is DEPRECATED!
  493. template <typename S>
  494. struct is_string : std::is_class<decltype(to_string_view(std::declval<S>()))> {
  495. };
  496. template <typename S, typename = void> struct char_t_impl {};
  497. template <typename S> struct char_t_impl<S, enable_if_t<is_string<S>::value>> {
  498. using result = decltype(to_string_view(std::declval<S>()));
  499. using type = typename result::value_type;
  500. };
  501. enum class type {
  502. none_type,
  503. // Integer types should go first,
  504. int_type,
  505. uint_type,
  506. long_long_type,
  507. ulong_long_type,
  508. int128_type,
  509. uint128_type,
  510. bool_type,
  511. char_type,
  512. last_integer_type = char_type,
  513. // followed by floating-point types.
  514. float_type,
  515. double_type,
  516. long_double_type,
  517. last_numeric_type = long_double_type,
  518. cstring_type,
  519. string_type,
  520. pointer_type,
  521. custom_type
  522. };
  523. // Maps core type T to the corresponding type enum constant.
  524. template <typename T, typename Char>
  525. struct type_constant : std::integral_constant<type, type::custom_type> {};
  526. #define FMT_TYPE_CONSTANT(Type, constant) \
  527. template <typename Char> \
  528. struct type_constant<Type, Char> \
  529. : std::integral_constant<type, type::constant> {}
  530. FMT_TYPE_CONSTANT(int, int_type);
  531. FMT_TYPE_CONSTANT(unsigned, uint_type);
  532. FMT_TYPE_CONSTANT(long long, long_long_type);
  533. FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
  534. FMT_TYPE_CONSTANT(int128_opt, int128_type);
  535. FMT_TYPE_CONSTANT(uint128_opt, uint128_type);
  536. FMT_TYPE_CONSTANT(bool, bool_type);
  537. FMT_TYPE_CONSTANT(Char, char_type);
  538. FMT_TYPE_CONSTANT(float, float_type);
  539. FMT_TYPE_CONSTANT(double, double_type);
  540. FMT_TYPE_CONSTANT(long double, long_double_type);
  541. FMT_TYPE_CONSTANT(const Char*, cstring_type);
  542. FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
  543. FMT_TYPE_CONSTANT(const void*, pointer_type);
  544. constexpr bool is_integral_type(type t) {
  545. return t > type::none_type && t <= type::last_integer_type;
  546. }
  547. constexpr bool is_arithmetic_type(type t) {
  548. return t > type::none_type && t <= type::last_numeric_type;
  549. }
  550. FMT_NORETURN FMT_API void throw_format_error(const char* message);
  551. struct error_handler {
  552. constexpr error_handler() = default;
  553. constexpr error_handler(const error_handler&) = default;
  554. // This function is intentionally not constexpr to give a compile-time error.
  555. FMT_NORETURN void on_error(const char* message) {
  556. throw_format_error(message);
  557. }
  558. };
  559. FMT_END_DETAIL_NAMESPACE
  560. /** String's character type. */
  561. template <typename S> using char_t = typename detail::char_t_impl<S>::type;
  562. /**
  563. \rst
  564. Parsing context consisting of a format string range being parsed and an
  565. argument counter for automatic indexing.
  566. You can use the ``format_parse_context`` type alias for ``char`` instead.
  567. \endrst
  568. */
  569. template <typename Char, typename ErrorHandler = detail::error_handler>
  570. class basic_format_parse_context : private ErrorHandler {
  571. private:
  572. basic_string_view<Char> format_str_;
  573. int next_arg_id_;
  574. FMT_CONSTEXPR void do_check_arg_id(int id);
  575. public:
  576. using char_type = Char;
  577. using iterator = typename basic_string_view<Char>::iterator;
  578. explicit constexpr basic_format_parse_context(
  579. basic_string_view<Char> format_str, ErrorHandler eh = {},
  580. int next_arg_id = 0)
  581. : ErrorHandler(eh), format_str_(format_str), next_arg_id_(next_arg_id) {}
  582. /**
  583. Returns an iterator to the beginning of the format string range being
  584. parsed.
  585. */
  586. constexpr auto begin() const noexcept -> iterator {
  587. return format_str_.begin();
  588. }
  589. /**
  590. Returns an iterator past the end of the format string range being parsed.
  591. */
  592. constexpr auto end() const noexcept -> iterator { return format_str_.end(); }
  593. /** Advances the begin iterator to ``it``. */
  594. FMT_CONSTEXPR void advance_to(iterator it) {
  595. format_str_.remove_prefix(detail::to_unsigned(it - begin()));
  596. }
  597. /**
  598. Reports an error if using the manual argument indexing; otherwise returns
  599. the next argument index and switches to the automatic indexing.
  600. */
  601. FMT_CONSTEXPR auto next_arg_id() -> int {
  602. if (next_arg_id_ < 0) {
  603. on_error("cannot switch from manual to automatic argument indexing");
  604. return 0;
  605. }
  606. int id = next_arg_id_++;
  607. do_check_arg_id(id);
  608. return id;
  609. }
  610. /**
  611. Reports an error if using the automatic argument indexing; otherwise
  612. switches to the manual indexing.
  613. */
  614. FMT_CONSTEXPR void check_arg_id(int id) {
  615. if (next_arg_id_ > 0) {
  616. on_error("cannot switch from automatic to manual argument indexing");
  617. return;
  618. }
  619. next_arg_id_ = -1;
  620. do_check_arg_id(id);
  621. }
  622. FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {}
  623. FMT_CONSTEXPR void check_dynamic_spec(int arg_id);
  624. FMT_CONSTEXPR void on_error(const char* message) {
  625. ErrorHandler::on_error(message);
  626. }
  627. constexpr auto error_handler() const -> ErrorHandler { return *this; }
  628. };
  629. using format_parse_context = basic_format_parse_context<char>;
  630. FMT_BEGIN_DETAIL_NAMESPACE
  631. // A parse context with extra data used only in compile-time checks.
  632. template <typename Char, typename ErrorHandler = detail::error_handler>
  633. class compile_parse_context
  634. : public basic_format_parse_context<Char, ErrorHandler> {
  635. private:
  636. int num_args_;
  637. const type* types_;
  638. using base = basic_format_parse_context<Char, ErrorHandler>;
  639. public:
  640. explicit FMT_CONSTEXPR compile_parse_context(
  641. basic_string_view<Char> format_str, int num_args, const type* types,
  642. ErrorHandler eh = {}, int next_arg_id = 0)
  643. : base(format_str, eh, next_arg_id), num_args_(num_args), types_(types) {}
  644. constexpr auto num_args() const -> int { return num_args_; }
  645. constexpr auto arg_type(int id) const -> type { return types_[id]; }
  646. FMT_CONSTEXPR auto next_arg_id() -> int {
  647. int id = base::next_arg_id();
  648. if (id >= num_args_) this->on_error("argument not found");
  649. return id;
  650. }
  651. FMT_CONSTEXPR void check_arg_id(int id) {
  652. base::check_arg_id(id);
  653. if (id >= num_args_) this->on_error("argument not found");
  654. }
  655. using base::check_arg_id;
  656. FMT_CONSTEXPR void check_dynamic_spec(int arg_id) {
  657. if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id]))
  658. this->on_error("width/precision is not integer");
  659. }
  660. };
  661. FMT_END_DETAIL_NAMESPACE
  662. template <typename Char, typename ErrorHandler>
  663. FMT_CONSTEXPR void
  664. basic_format_parse_context<Char, ErrorHandler>::do_check_arg_id(int id) {
  665. // Argument id is only checked at compile-time during parsing because
  666. // formatting has its own validation.
  667. if (detail::is_constant_evaluated() && FMT_GCC_VERSION >= 1200) {
  668. using context = detail::compile_parse_context<Char, ErrorHandler>;
  669. if (id >= static_cast<context*>(this)->num_args())
  670. on_error("argument not found");
  671. }
  672. }
  673. template <typename Char, typename ErrorHandler>
  674. FMT_CONSTEXPR void
  675. basic_format_parse_context<Char, ErrorHandler>::check_dynamic_spec(int arg_id) {
  676. if (detail::is_constant_evaluated()) {
  677. using context = detail::compile_parse_context<Char, ErrorHandler>;
  678. static_cast<context*>(this)->check_dynamic_spec(arg_id);
  679. }
  680. }
  681. template <typename Context> class basic_format_arg;
  682. template <typename Context> class basic_format_args;
  683. template <typename Context> class dynamic_format_arg_store;
  684. // A formatter for objects of type T.
  685. template <typename T, typename Char = char, typename Enable = void>
  686. struct formatter {
  687. // A deleted default constructor indicates a disabled formatter.
  688. formatter() = delete;
  689. };
  690. // Specifies if T has an enabled formatter specialization. A type can be
  691. // formattable even if it doesn't have a formatter e.g. via a conversion.
  692. template <typename T, typename Context>
  693. using has_formatter =
  694. std::is_constructible<typename Context::template formatter_type<T>>;
  695. // Checks whether T is a container with contiguous storage.
  696. template <typename T> struct is_contiguous : std::false_type {};
  697. template <typename Char>
  698. struct is_contiguous<std::basic_string<Char>> : std::true_type {};
  699. class appender;
  700. FMT_BEGIN_DETAIL_NAMESPACE
  701. template <typename Context, typename T>
  702. constexpr auto has_const_formatter_impl(T*)
  703. -> decltype(typename Context::template formatter_type<T>().format(
  704. std::declval<const T&>(), std::declval<Context&>()),
  705. true) {
  706. return true;
  707. }
  708. template <typename Context>
  709. constexpr auto has_const_formatter_impl(...) -> bool {
  710. return false;
  711. }
  712. template <typename T, typename Context>
  713. constexpr auto has_const_formatter() -> bool {
  714. return has_const_formatter_impl<Context>(static_cast<T*>(nullptr));
  715. }
  716. // Extracts a reference to the container from back_insert_iterator.
  717. template <typename Container>
  718. inline auto get_container(std::back_insert_iterator<Container> it)
  719. -> Container& {
  720. using base = std::back_insert_iterator<Container>;
  721. struct accessor : base {
  722. accessor(base b) : base(b) {}
  723. using base::container;
  724. };
  725. return *accessor(it).container;
  726. }
  727. template <typename Char, typename InputIt, typename OutputIt>
  728. FMT_CONSTEXPR auto copy_str(InputIt begin, InputIt end, OutputIt out)
  729. -> OutputIt {
  730. while (begin != end) *out++ = static_cast<Char>(*begin++);
  731. return out;
  732. }
  733. template <typename Char, typename T, typename U,
  734. FMT_ENABLE_IF(
  735. std::is_same<remove_const_t<T>, U>::value&& is_char<U>::value)>
  736. FMT_CONSTEXPR auto copy_str(T* begin, T* end, U* out) -> U* {
  737. if (is_constant_evaluated()) return copy_str<Char, T*, U*>(begin, end, out);
  738. auto size = to_unsigned(end - begin);
  739. memcpy(out, begin, size * sizeof(U));
  740. return out + size;
  741. }
  742. /**
  743. \rst
  744. A contiguous memory buffer with an optional growing ability. It is an internal
  745. class and shouldn't be used directly, only via `~fmt::basic_memory_buffer`.
  746. \endrst
  747. */
  748. template <typename T> class buffer {
  749. private:
  750. T* ptr_;
  751. size_t size_;
  752. size_t capacity_;
  753. protected:
  754. // Don't initialize ptr_ since it is not accessed to save a few cycles.
  755. FMT_MSC_WARNING(suppress : 26495)
  756. buffer(size_t sz) noexcept : size_(sz), capacity_(sz) {}
  757. FMT_CONSTEXPR20 buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) noexcept
  758. : ptr_(p), size_(sz), capacity_(cap) {}
  759. FMT_CONSTEXPR20 ~buffer() = default;
  760. buffer(buffer&&) = default;
  761. /** Sets the buffer data and capacity. */
  762. FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept {
  763. ptr_ = buf_data;
  764. capacity_ = buf_capacity;
  765. }
  766. /** Increases the buffer capacity to hold at least *capacity* elements. */
  767. virtual FMT_CONSTEXPR20 void grow(size_t capacity) = 0;
  768. public:
  769. using value_type = T;
  770. using const_reference = const T&;
  771. buffer(const buffer&) = delete;
  772. void operator=(const buffer&) = delete;
  773. auto begin() noexcept -> T* { return ptr_; }
  774. auto end() noexcept -> T* { return ptr_ + size_; }
  775. auto begin() const noexcept -> const T* { return ptr_; }
  776. auto end() const noexcept -> const T* { return ptr_ + size_; }
  777. /** Returns the size of this buffer. */
  778. constexpr auto size() const noexcept -> size_t { return size_; }
  779. /** Returns the capacity of this buffer. */
  780. constexpr auto capacity() const noexcept -> size_t { return capacity_; }
  781. /** Returns a pointer to the buffer data. */
  782. FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; }
  783. /** Returns a pointer to the buffer data. */
  784. FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; }
  785. /** Clears this buffer. */
  786. void clear() { size_ = 0; }
  787. // Tries resizing the buffer to contain *count* elements. If T is a POD type
  788. // the new elements may not be initialized.
  789. FMT_CONSTEXPR20 void try_resize(size_t count) {
  790. try_reserve(count);
  791. size_ = count <= capacity_ ? count : capacity_;
  792. }
  793. // Tries increasing the buffer capacity to *new_capacity*. It can increase the
  794. // capacity by a smaller amount than requested but guarantees there is space
  795. // for at least one additional element either by increasing the capacity or by
  796. // flushing the buffer if it is full.
  797. FMT_CONSTEXPR20 void try_reserve(size_t new_capacity) {
  798. if (new_capacity > capacity_) grow(new_capacity);
  799. }
  800. FMT_CONSTEXPR20 void push_back(const T& value) {
  801. try_reserve(size_ + 1);
  802. ptr_[size_++] = value;
  803. }
  804. /** Appends data to the end of the buffer. */
  805. template <typename U> void append(const U* begin, const U* end);
  806. template <typename Idx> FMT_CONSTEXPR auto operator[](Idx index) -> T& {
  807. return ptr_[index];
  808. }
  809. template <typename Idx>
  810. FMT_CONSTEXPR auto operator[](Idx index) const -> const T& {
  811. return ptr_[index];
  812. }
  813. };
  814. struct buffer_traits {
  815. explicit buffer_traits(size_t) {}
  816. auto count() const -> size_t { return 0; }
  817. auto limit(size_t size) -> size_t { return size; }
  818. };
  819. class fixed_buffer_traits {
  820. private:
  821. size_t count_ = 0;
  822. size_t limit_;
  823. public:
  824. explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}
  825. auto count() const -> size_t { return count_; }
  826. auto limit(size_t size) -> size_t {
  827. size_t n = limit_ > count_ ? limit_ - count_ : 0;
  828. count_ += size;
  829. return size < n ? size : n;
  830. }
  831. };
  832. // A buffer that writes to an output iterator when flushed.
  833. template <typename OutputIt, typename T, typename Traits = buffer_traits>
  834. class iterator_buffer final : public Traits, public buffer<T> {
  835. private:
  836. OutputIt out_;
  837. enum { buffer_size = 256 };
  838. T data_[buffer_size];
  839. protected:
  840. FMT_CONSTEXPR20 void grow(size_t) override {
  841. if (this->size() == buffer_size) flush();
  842. }
  843. void flush() {
  844. auto size = this->size();
  845. this->clear();
  846. out_ = copy_str<T>(data_, data_ + this->limit(size), out_);
  847. }
  848. public:
  849. explicit iterator_buffer(OutputIt out, size_t n = buffer_size)
  850. : Traits(n), buffer<T>(data_, 0, buffer_size), out_(out) {}
  851. iterator_buffer(iterator_buffer&& other)
  852. : Traits(other), buffer<T>(data_, 0, buffer_size), out_(other.out_) {}
  853. ~iterator_buffer() { flush(); }
  854. auto out() -> OutputIt {
  855. flush();
  856. return out_;
  857. }
  858. auto count() const -> size_t { return Traits::count() + this->size(); }
  859. };
  860. template <typename T>
  861. class iterator_buffer<T*, T, fixed_buffer_traits> final
  862. : public fixed_buffer_traits,
  863. public buffer<T> {
  864. private:
  865. T* out_;
  866. enum { buffer_size = 256 };
  867. T data_[buffer_size];
  868. protected:
  869. FMT_CONSTEXPR20 void grow(size_t) override {
  870. if (this->size() == this->capacity()) flush();
  871. }
  872. void flush() {
  873. size_t n = this->limit(this->size());
  874. if (this->data() == out_) {
  875. out_ += n;
  876. this->set(data_, buffer_size);
  877. }
  878. this->clear();
  879. }
  880. public:
  881. explicit iterator_buffer(T* out, size_t n = buffer_size)
  882. : fixed_buffer_traits(n), buffer<T>(out, 0, n), out_(out) {}
  883. iterator_buffer(iterator_buffer&& other)
  884. : fixed_buffer_traits(other),
  885. buffer<T>(std::move(other)),
  886. out_(other.out_) {
  887. if (this->data() != out_) {
  888. this->set(data_, buffer_size);
  889. this->clear();
  890. }
  891. }
  892. ~iterator_buffer() { flush(); }
  893. auto out() -> T* {
  894. flush();
  895. return out_;
  896. }
  897. auto count() const -> size_t {
  898. return fixed_buffer_traits::count() + this->size();
  899. }
  900. };
  901. template <typename T> class iterator_buffer<T*, T> final : public buffer<T> {
  902. protected:
  903. FMT_CONSTEXPR20 void grow(size_t) override {}
  904. public:
  905. explicit iterator_buffer(T* out, size_t = 0) : buffer<T>(out, 0, ~size_t()) {}
  906. auto out() -> T* { return &*this->end(); }
  907. };
  908. // A buffer that writes to a container with the contiguous storage.
  909. template <typename Container>
  910. class iterator_buffer<std::back_insert_iterator<Container>,
  911. enable_if_t<is_contiguous<Container>::value,
  912. typename Container::value_type>>
  913. final : public buffer<typename Container::value_type> {
  914. private:
  915. Container& container_;
  916. protected:
  917. FMT_CONSTEXPR20 void grow(size_t capacity) override {
  918. container_.resize(capacity);
  919. this->set(&container_[0], capacity);
  920. }
  921. public:
  922. explicit iterator_buffer(Container& c)
  923. : buffer<typename Container::value_type>(c.size()), container_(c) {}
  924. explicit iterator_buffer(std::back_insert_iterator<Container> out, size_t = 0)
  925. : iterator_buffer(get_container(out)) {}
  926. auto out() -> std::back_insert_iterator<Container> {
  927. return std::back_inserter(container_);
  928. }
  929. };
  930. // A buffer that counts the number of code units written discarding the output.
  931. template <typename T = char> class counting_buffer final : public buffer<T> {
  932. private:
  933. enum { buffer_size = 256 };
  934. T data_[buffer_size];
  935. size_t count_ = 0;
  936. protected:
  937. FMT_CONSTEXPR20 void grow(size_t) override {
  938. if (this->size() != buffer_size) return;
  939. count_ += this->size();
  940. this->clear();
  941. }
  942. public:
  943. counting_buffer() : buffer<T>(data_, 0, buffer_size) {}
  944. auto count() -> size_t { return count_ + this->size(); }
  945. };
  946. template <typename T>
  947. using buffer_appender = conditional_t<std::is_same<T, char>::value, appender,
  948. std::back_insert_iterator<buffer<T>>>;
  949. // Maps an output iterator to a buffer.
  950. template <typename T, typename OutputIt>
  951. auto get_buffer(OutputIt out) -> iterator_buffer<OutputIt, T> {
  952. return iterator_buffer<OutputIt, T>(out);
  953. }
  954. template <typename Buffer>
  955. auto get_iterator(Buffer& buf) -> decltype(buf.out()) {
  956. return buf.out();
  957. }
  958. template <typename T> auto get_iterator(buffer<T>& buf) -> buffer_appender<T> {
  959. return buffer_appender<T>(buf);
  960. }
  961. template <typename T, typename Char = char, typename Enable = void>
  962. struct fallback_formatter {
  963. fallback_formatter() = delete;
  964. };
  965. // Specifies if T has an enabled fallback_formatter specialization.
  966. template <typename T, typename Char>
  967. using has_fallback_formatter =
  968. #ifdef FMT_DEPRECATED_OSTREAM
  969. std::is_constructible<fallback_formatter<T, Char>>;
  970. #else
  971. std::false_type;
  972. #endif
  973. struct view {};
  974. template <typename Char, typename T> struct named_arg : view {
  975. const Char* name;
  976. const T& value;
  977. named_arg(const Char* n, const T& v) : name(n), value(v) {}
  978. };
  979. template <typename Char> struct named_arg_info {
  980. const Char* name;
  981. int id;
  982. };
  983. template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
  984. struct arg_data {
  985. // args_[0].named_args points to named_args_ to avoid bloating format_args.
  986. // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
  987. T args_[1 + (NUM_ARGS != 0 ? NUM_ARGS : +1)];
  988. named_arg_info<Char> named_args_[NUM_NAMED_ARGS];
  989. template <typename... U>
  990. arg_data(const U&... init) : args_{T(named_args_, NUM_NAMED_ARGS), init...} {}
  991. arg_data(const arg_data& other) = delete;
  992. auto args() const -> const T* { return args_ + 1; }
  993. auto named_args() -> named_arg_info<Char>* { return named_args_; }
  994. };
  995. template <typename T, typename Char, size_t NUM_ARGS>
  996. struct arg_data<T, Char, NUM_ARGS, 0> {
  997. // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
  998. T args_[NUM_ARGS != 0 ? NUM_ARGS : +1];
  999. template <typename... U>
  1000. FMT_CONSTEXPR FMT_INLINE arg_data(const U&... init) : args_{init...} {}
  1001. FMT_CONSTEXPR FMT_INLINE auto args() const -> const T* { return args_; }
  1002. FMT_CONSTEXPR FMT_INLINE auto named_args() -> std::nullptr_t {
  1003. return nullptr;
  1004. }
  1005. };
  1006. template <typename Char>
  1007. inline void init_named_args(named_arg_info<Char>*, int, int) {}
  1008. template <typename T> struct is_named_arg : std::false_type {};
  1009. template <typename T> struct is_statically_named_arg : std::false_type {};
  1010. template <typename T, typename Char>
  1011. struct is_named_arg<named_arg<Char, T>> : std::true_type {};
  1012. template <typename Char, typename T, typename... Tail,
  1013. FMT_ENABLE_IF(!is_named_arg<T>::value)>
  1014. void init_named_args(named_arg_info<Char>* named_args, int arg_count,
  1015. int named_arg_count, const T&, const Tail&... args) {
  1016. init_named_args(named_args, arg_count + 1, named_arg_count, args...);
  1017. }
  1018. template <typename Char, typename T, typename... Tail,
  1019. FMT_ENABLE_IF(is_named_arg<T>::value)>
  1020. void init_named_args(named_arg_info<Char>* named_args, int arg_count,
  1021. int named_arg_count, const T& arg, const Tail&... args) {
  1022. named_args[named_arg_count++] = {arg.name, arg_count};
  1023. init_named_args(named_args, arg_count + 1, named_arg_count, args...);
  1024. }
  1025. template <typename... Args>
  1026. FMT_CONSTEXPR FMT_INLINE void init_named_args(std::nullptr_t, int, int,
  1027. const Args&...) {}
  1028. template <bool B = false> constexpr auto count() -> size_t { return B ? 1 : 0; }
  1029. template <bool B1, bool B2, bool... Tail> constexpr auto count() -> size_t {
  1030. return (B1 ? 1 : 0) + count<B2, Tail...>();
  1031. }
  1032. template <typename... Args> constexpr auto count_named_args() -> size_t {
  1033. return count<is_named_arg<Args>::value...>();
  1034. }
  1035. template <typename... Args>
  1036. constexpr auto count_statically_named_args() -> size_t {
  1037. return count<is_statically_named_arg<Args>::value...>();
  1038. }
  1039. struct unformattable {};
  1040. struct unformattable_char : unformattable {};
  1041. struct unformattable_const : unformattable {};
  1042. struct unformattable_pointer : unformattable {};
  1043. template <typename Char> struct string_value {
  1044. const Char* data;
  1045. size_t size;
  1046. };
  1047. template <typename Char> struct named_arg_value {
  1048. const named_arg_info<Char>* data;
  1049. size_t size;
  1050. };
  1051. template <typename Context> struct custom_value {
  1052. using parse_context = typename Context::parse_context_type;
  1053. void* value;
  1054. void (*format)(void* arg, parse_context& parse_ctx, Context& ctx);
  1055. };
  1056. // A formatting argument value.
  1057. template <typename Context> class value {
  1058. public:
  1059. using char_type = typename Context::char_type;
  1060. union {
  1061. monostate no_value;
  1062. int int_value;
  1063. unsigned uint_value;
  1064. long long long_long_value;
  1065. unsigned long long ulong_long_value;
  1066. int128_opt int128_value;
  1067. uint128_opt uint128_value;
  1068. bool bool_value;
  1069. char_type char_value;
  1070. float float_value;
  1071. double double_value;
  1072. long double long_double_value;
  1073. const void* pointer;
  1074. string_value<char_type> string;
  1075. custom_value<Context> custom;
  1076. named_arg_value<char_type> named_args;
  1077. };
  1078. constexpr FMT_INLINE value() : no_value() {}
  1079. constexpr FMT_INLINE value(int val) : int_value(val) {}
  1080. constexpr FMT_INLINE value(unsigned val) : uint_value(val) {}
  1081. constexpr FMT_INLINE value(long long val) : long_long_value(val) {}
  1082. constexpr FMT_INLINE value(unsigned long long val) : ulong_long_value(val) {}
  1083. FMT_INLINE value(int128_opt val) : int128_value(val) {}
  1084. FMT_INLINE value(uint128_opt val) : uint128_value(val) {}
  1085. constexpr FMT_INLINE value(float val) : float_value(val) {}
  1086. constexpr FMT_INLINE value(double val) : double_value(val) {}
  1087. FMT_INLINE value(long double val) : long_double_value(val) {}
  1088. constexpr FMT_INLINE value(bool val) : bool_value(val) {}
  1089. constexpr FMT_INLINE value(char_type val) : char_value(val) {}
  1090. FMT_CONSTEXPR FMT_INLINE value(const char_type* val) {
  1091. string.data = val;
  1092. if (is_constant_evaluated()) string.size = {};
  1093. }
  1094. FMT_CONSTEXPR FMT_INLINE value(basic_string_view<char_type> val) {
  1095. string.data = val.data();
  1096. string.size = val.size();
  1097. }
  1098. FMT_INLINE value(const void* val) : pointer(val) {}
  1099. FMT_INLINE value(const named_arg_info<char_type>* args, size_t size)
  1100. : named_args{args, size} {}
  1101. template <typename T> FMT_CONSTEXPR FMT_INLINE value(T& val) {
  1102. using value_type = remove_cvref_t<T>;
  1103. custom.value = const_cast<value_type*>(&val);
  1104. // Get the formatter type through the context to allow different contexts
  1105. // have different extension points, e.g. `formatter<T>` for `format` and
  1106. // `printf_formatter<T>` for `printf`.
  1107. custom.format = format_custom_arg<
  1108. value_type,
  1109. conditional_t<has_formatter<value_type, Context>::value,
  1110. typename Context::template formatter_type<value_type>,
  1111. fallback_formatter<value_type, char_type>>>;
  1112. }
  1113. value(unformattable);
  1114. value(unformattable_char);
  1115. value(unformattable_const);
  1116. value(unformattable_pointer);
  1117. private:
  1118. // Formats an argument of a custom type, such as a user-defined class.
  1119. template <typename T, typename Formatter>
  1120. static void format_custom_arg(void* arg,
  1121. typename Context::parse_context_type& parse_ctx,
  1122. Context& ctx) {
  1123. auto f = Formatter();
  1124. parse_ctx.advance_to(f.parse(parse_ctx));
  1125. using qualified_type =
  1126. conditional_t<has_const_formatter<T, Context>(), const T, T>;
  1127. ctx.advance_to(f.format(*static_cast<qualified_type*>(arg), ctx));
  1128. }
  1129. };
  1130. template <typename Context, typename T>
  1131. FMT_CONSTEXPR auto make_arg(T&& value) -> basic_format_arg<Context>;
  1132. // To minimize the number of types we need to deal with, long is translated
  1133. // either to int or to long long depending on its size.
  1134. enum { long_short = sizeof(long) == sizeof(int) };
  1135. using long_type = conditional_t<long_short, int, long long>;
  1136. using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
  1137. #ifdef __cpp_lib_byte
  1138. inline auto format_as(std::byte b) -> unsigned char {
  1139. return static_cast<unsigned char>(b);
  1140. }
  1141. #endif
  1142. template <typename T> struct has_format_as {
  1143. template <typename U, typename V = decltype(format_as(U())),
  1144. FMT_ENABLE_IF(std::is_enum<U>::value&& std::is_integral<V>::value)>
  1145. static auto check(U*) -> std::true_type;
  1146. static auto check(...) -> std::false_type;
  1147. enum { value = decltype(check(static_cast<T*>(nullptr)))::value };
  1148. };
  1149. // Maps formatting arguments to core types.
  1150. // arg_mapper reports errors by returning unformattable instead of using
  1151. // static_assert because it's used in the is_formattable trait.
  1152. template <typename Context> struct arg_mapper {
  1153. using char_type = typename Context::char_type;
  1154. FMT_CONSTEXPR FMT_INLINE auto map(signed char val) -> int { return val; }
  1155. FMT_CONSTEXPR FMT_INLINE auto map(unsigned char val) -> unsigned {
  1156. return val;
  1157. }
  1158. FMT_CONSTEXPR FMT_INLINE auto map(short val) -> int { return val; }
  1159. FMT_CONSTEXPR FMT_INLINE auto map(unsigned short val) -> unsigned {
  1160. return val;
  1161. }
  1162. FMT_CONSTEXPR FMT_INLINE auto map(int val) -> int { return val; }
  1163. FMT_CONSTEXPR FMT_INLINE auto map(unsigned val) -> unsigned { return val; }
  1164. FMT_CONSTEXPR FMT_INLINE auto map(long val) -> long_type { return val; }
  1165. FMT_CONSTEXPR FMT_INLINE auto map(unsigned long val) -> ulong_type {
  1166. return val;
  1167. }
  1168. FMT_CONSTEXPR FMT_INLINE auto map(long long val) -> long long { return val; }
  1169. FMT_CONSTEXPR FMT_INLINE auto map(unsigned long long val)
  1170. -> unsigned long long {
  1171. return val;
  1172. }
  1173. FMT_CONSTEXPR FMT_INLINE auto map(int128_opt val) -> int128_opt {
  1174. return val;
  1175. }
  1176. FMT_CONSTEXPR FMT_INLINE auto map(uint128_opt val) -> uint128_opt {
  1177. return val;
  1178. }
  1179. FMT_CONSTEXPR FMT_INLINE auto map(bool val) -> bool { return val; }
  1180. template <typename T, FMT_ENABLE_IF(std::is_same<T, char>::value ||
  1181. std::is_same<T, char_type>::value)>
  1182. FMT_CONSTEXPR FMT_INLINE auto map(T val) -> char_type {
  1183. return val;
  1184. }
  1185. template <typename T, enable_if_t<(std::is_same<T, wchar_t>::value ||
  1186. #ifdef __cpp_char8_t
  1187. std::is_same<T, char8_t>::value ||
  1188. #endif
  1189. std::is_same<T, char16_t>::value ||
  1190. std::is_same<T, char32_t>::value) &&
  1191. !std::is_same<T, char_type>::value,
  1192. int> = 0>
  1193. FMT_CONSTEXPR FMT_INLINE auto map(T) -> unformattable_char {
  1194. return {};
  1195. }
  1196. FMT_CONSTEXPR FMT_INLINE auto map(float val) -> float { return val; }
  1197. FMT_CONSTEXPR FMT_INLINE auto map(double val) -> double { return val; }
  1198. FMT_CONSTEXPR FMT_INLINE auto map(long double val) -> long double {
  1199. return val;
  1200. }
  1201. FMT_CONSTEXPR FMT_INLINE auto map(char_type* val) -> const char_type* {
  1202. return val;
  1203. }
  1204. FMT_CONSTEXPR FMT_INLINE auto map(const char_type* val) -> const char_type* {
  1205. return val;
  1206. }
  1207. template <typename T,
  1208. FMT_ENABLE_IF(is_string<T>::value && !std::is_pointer<T>::value &&
  1209. std::is_same<char_type, char_t<T>>::value)>
  1210. FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
  1211. -> basic_string_view<char_type> {
  1212. return to_string_view(val);
  1213. }
  1214. template <typename T,
  1215. FMT_ENABLE_IF(is_string<T>::value && !std::is_pointer<T>::value &&
  1216. !std::is_same<char_type, char_t<T>>::value)>
  1217. FMT_CONSTEXPR FMT_INLINE auto map(const T&) -> unformattable_char {
  1218. return {};
  1219. }
  1220. template <typename T,
  1221. FMT_ENABLE_IF(
  1222. std::is_convertible<T, basic_string_view<char_type>>::value &&
  1223. !is_string<T>::value && !has_formatter<T, Context>::value &&
  1224. !has_fallback_formatter<T, char_type>::value)>
  1225. FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
  1226. -> basic_string_view<char_type> {
  1227. return basic_string_view<char_type>(val);
  1228. }
  1229. template <typename T,
  1230. FMT_ENABLE_IF(
  1231. std::is_convertible<T, std_string_view<char_type>>::value &&
  1232. !std::is_convertible<T, basic_string_view<char_type>>::value &&
  1233. !is_string<T>::value && !has_formatter<T, Context>::value &&
  1234. !has_fallback_formatter<T, char_type>::value)>
  1235. FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
  1236. -> basic_string_view<char_type> {
  1237. return std_string_view<char_type>(val);
  1238. }
  1239. FMT_CONSTEXPR FMT_INLINE auto map(void* val) -> const void* { return val; }
  1240. FMT_CONSTEXPR FMT_INLINE auto map(const void* val) -> const void* {
  1241. return val;
  1242. }
  1243. FMT_CONSTEXPR FMT_INLINE auto map(std::nullptr_t val) -> const void* {
  1244. return val;
  1245. }
  1246. // We use SFINAE instead of a const T* parameter to avoid conflicting with
  1247. // the C array overload.
  1248. template <
  1249. typename T,
  1250. FMT_ENABLE_IF(
  1251. std::is_pointer<T>::value || std::is_member_pointer<T>::value ||
  1252. std::is_function<typename std::remove_pointer<T>::type>::value ||
  1253. (std::is_convertible<const T&, const void*>::value &&
  1254. !std::is_convertible<const T&, const char_type*>::value &&
  1255. !has_formatter<T, Context>::value))>
  1256. FMT_CONSTEXPR auto map(const T&) -> unformattable_pointer {
  1257. return {};
  1258. }
  1259. template <typename T, std::size_t N,
  1260. FMT_ENABLE_IF(!std::is_same<T, wchar_t>::value)>
  1261. FMT_CONSTEXPR FMT_INLINE auto map(const T (&values)[N]) -> const T (&)[N] {
  1262. return values;
  1263. }
  1264. template <typename T,
  1265. FMT_ENABLE_IF(
  1266. std::is_enum<T>::value&& std::is_convertible<T, int>::value &&
  1267. !has_format_as<T>::value && !has_formatter<T, Context>::value &&
  1268. !has_fallback_formatter<T, char_type>::value)>
  1269. FMT_DEPRECATED FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
  1270. -> decltype(std::declval<arg_mapper>().map(
  1271. static_cast<underlying_t<T>>(val))) {
  1272. return map(static_cast<underlying_t<T>>(val));
  1273. }
  1274. template <typename T, FMT_ENABLE_IF(has_format_as<T>::value &&
  1275. !has_formatter<T, Context>::value)>
  1276. FMT_CONSTEXPR FMT_INLINE auto map(const T& val)
  1277. -> decltype(std::declval<arg_mapper>().map(format_as(T()))) {
  1278. return map(format_as(val));
  1279. }
  1280. template <typename T, typename U = remove_cvref_t<T>>
  1281. struct formattable
  1282. : bool_constant<has_const_formatter<U, Context>() ||
  1283. !std::is_const<remove_reference_t<T>>::value ||
  1284. has_fallback_formatter<U, char_type>::value> {};
  1285. #if (FMT_MSC_VERSION != 0 && FMT_MSC_VERSION < 1910) || \
  1286. FMT_ICC_VERSION != 0 || defined(__NVCC__)
  1287. // Workaround a bug in MSVC and Intel (Issue 2746).
  1288. template <typename T> FMT_CONSTEXPR FMT_INLINE auto do_map(T&& val) -> T& {
  1289. return val;
  1290. }
  1291. #else
  1292. template <typename T, FMT_ENABLE_IF(formattable<T>::value)>
  1293. FMT_CONSTEXPR FMT_INLINE auto do_map(T&& val) -> T& {
  1294. return val;
  1295. }
  1296. template <typename T, FMT_ENABLE_IF(!formattable<T>::value)>
  1297. FMT_CONSTEXPR FMT_INLINE auto do_map(T&&) -> unformattable_const {
  1298. return {};
  1299. }
  1300. #endif
  1301. template <typename T, typename U = remove_cvref_t<T>,
  1302. FMT_ENABLE_IF(!is_string<U>::value && !is_char<U>::value &&
  1303. !std::is_array<U>::value &&
  1304. !std::is_pointer<U>::value &&
  1305. !has_format_as<U>::value &&
  1306. (has_formatter<U, Context>::value ||
  1307. has_fallback_formatter<U, char_type>::value))>
  1308. FMT_CONSTEXPR FMT_INLINE auto map(T&& val)
  1309. -> decltype(this->do_map(std::forward<T>(val))) {
  1310. return do_map(std::forward<T>(val));
  1311. }
  1312. template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
  1313. FMT_CONSTEXPR FMT_INLINE auto map(const T& named_arg)
  1314. -> decltype(std::declval<arg_mapper>().map(named_arg.value)) {
  1315. return map(named_arg.value);
  1316. }
  1317. auto map(...) -> unformattable { return {}; }
  1318. };
  1319. // A type constant after applying arg_mapper<Context>.
  1320. template <typename T, typename Context>
  1321. using mapped_type_constant =
  1322. type_constant<decltype(arg_mapper<Context>().map(std::declval<const T&>())),
  1323. typename Context::char_type>;
  1324. enum { packed_arg_bits = 4 };
  1325. // Maximum number of arguments with packed types.
  1326. enum { max_packed_args = 62 / packed_arg_bits };
  1327. enum : unsigned long long { is_unpacked_bit = 1ULL << 63 };
  1328. enum : unsigned long long { has_named_args_bit = 1ULL << 62 };
  1329. FMT_END_DETAIL_NAMESPACE
  1330. // An output iterator that appends to a buffer.
  1331. // It is used to reduce symbol sizes for the common case.
  1332. class appender : public std::back_insert_iterator<detail::buffer<char>> {
  1333. using base = std::back_insert_iterator<detail::buffer<char>>;
  1334. template <typename T>
  1335. friend auto get_buffer(appender out) -> detail::buffer<char>& {
  1336. return detail::get_container(out);
  1337. }
  1338. public:
  1339. using std::back_insert_iterator<detail::buffer<char>>::back_insert_iterator;
  1340. appender(base it) noexcept : base(it) {}
  1341. FMT_UNCHECKED_ITERATOR(appender);
  1342. auto operator++() noexcept -> appender& { return *this; }
  1343. auto operator++(int) noexcept -> appender { return *this; }
  1344. };
  1345. // A formatting argument. It is a trivially copyable/constructible type to
  1346. // allow storage in basic_memory_buffer.
  1347. template <typename Context> class basic_format_arg {
  1348. private:
  1349. detail::value<Context> value_;
  1350. detail::type type_;
  1351. template <typename ContextType, typename T>
  1352. friend FMT_CONSTEXPR auto detail::make_arg(T&& value)
  1353. -> basic_format_arg<ContextType>;
  1354. template <typename Visitor, typename Ctx>
  1355. friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis,
  1356. const basic_format_arg<Ctx>& arg)
  1357. -> decltype(vis(0));
  1358. friend class basic_format_args<Context>;
  1359. friend class dynamic_format_arg_store<Context>;
  1360. using char_type = typename Context::char_type;
  1361. template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
  1362. friend struct detail::arg_data;
  1363. basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)
  1364. : value_(args, size) {}
  1365. public:
  1366. class handle {
  1367. public:
  1368. explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}
  1369. void format(typename Context::parse_context_type& parse_ctx,
  1370. Context& ctx) const {
  1371. custom_.format(custom_.value, parse_ctx, ctx);
  1372. }
  1373. private:
  1374. detail::custom_value<Context> custom_;
  1375. };
  1376. constexpr basic_format_arg() : type_(detail::type::none_type) {}
  1377. constexpr explicit operator bool() const noexcept {
  1378. return type_ != detail::type::none_type;
  1379. }
  1380. auto type() const -> detail::type { return type_; }
  1381. auto is_integral() const -> bool { return detail::is_integral_type(type_); }
  1382. auto is_arithmetic() const -> bool {
  1383. return detail::is_arithmetic_type(type_);
  1384. }
  1385. };
  1386. /**
  1387. \rst
  1388. Visits an argument dispatching to the appropriate visit method based on
  1389. the argument type. For example, if the argument type is ``double`` then
  1390. ``vis(value)`` will be called with the value of type ``double``.
  1391. \endrst
  1392. */
  1393. template <typename Visitor, typename Context>
  1394. FMT_CONSTEXPR FMT_INLINE auto visit_format_arg(
  1395. Visitor&& vis, const basic_format_arg<Context>& arg) -> decltype(vis(0)) {
  1396. switch (arg.type_) {
  1397. case detail::type::none_type:
  1398. break;
  1399. case detail::type::int_type:
  1400. return vis(arg.value_.int_value);
  1401. case detail::type::uint_type:
  1402. return vis(arg.value_.uint_value);
  1403. case detail::type::long_long_type:
  1404. return vis(arg.value_.long_long_value);
  1405. case detail::type::ulong_long_type:
  1406. return vis(arg.value_.ulong_long_value);
  1407. case detail::type::int128_type:
  1408. return vis(detail::convert_for_visit(arg.value_.int128_value));
  1409. case detail::type::uint128_type:
  1410. return vis(detail::convert_for_visit(arg.value_.uint128_value));
  1411. case detail::type::bool_type:
  1412. return vis(arg.value_.bool_value);
  1413. case detail::type::char_type:
  1414. return vis(arg.value_.char_value);
  1415. case detail::type::float_type:
  1416. return vis(arg.value_.float_value);
  1417. case detail::type::double_type:
  1418. return vis(arg.value_.double_value);
  1419. case detail::type::long_double_type:
  1420. return vis(arg.value_.long_double_value);
  1421. case detail::type::cstring_type:
  1422. return vis(arg.value_.string.data);
  1423. case detail::type::string_type:
  1424. using sv = basic_string_view<typename Context::char_type>;
  1425. return vis(sv(arg.value_.string.data, arg.value_.string.size));
  1426. case detail::type::pointer_type:
  1427. return vis(arg.value_.pointer);
  1428. case detail::type::custom_type:
  1429. return vis(typename basic_format_arg<Context>::handle(arg.value_.custom));
  1430. }
  1431. return vis(monostate());
  1432. }
  1433. FMT_BEGIN_DETAIL_NAMESPACE
  1434. template <typename Char, typename InputIt>
  1435. auto copy_str(InputIt begin, InputIt end, appender out) -> appender {
  1436. get_container(out).append(begin, end);
  1437. return out;
  1438. }
  1439. template <typename Char, typename R, typename OutputIt>
  1440. FMT_CONSTEXPR auto copy_str(R&& rng, OutputIt out) -> OutputIt {
  1441. return detail::copy_str<Char>(rng.begin(), rng.end(), out);
  1442. }
  1443. #if FMT_GCC_VERSION && FMT_GCC_VERSION < 500
  1444. // A workaround for gcc 4.8 to make void_t work in a SFINAE context.
  1445. template <typename... Ts> struct void_t_impl { using type = void; };
  1446. template <typename... Ts>
  1447. using void_t = typename detail::void_t_impl<Ts...>::type;
  1448. #else
  1449. template <typename...> using void_t = void;
  1450. #endif
  1451. template <typename It, typename T, typename Enable = void>
  1452. struct is_output_iterator : std::false_type {};
  1453. template <typename It, typename T>
  1454. struct is_output_iterator<
  1455. It, T,
  1456. void_t<typename std::iterator_traits<It>::iterator_category,
  1457. decltype(*std::declval<It>() = std::declval<T>())>>
  1458. : std::true_type {};
  1459. template <typename OutputIt>
  1460. struct is_back_insert_iterator : std::false_type {};
  1461. template <typename Container>
  1462. struct is_back_insert_iterator<std::back_insert_iterator<Container>>
  1463. : std::true_type {};
  1464. template <typename OutputIt>
  1465. struct is_contiguous_back_insert_iterator : std::false_type {};
  1466. template <typename Container>
  1467. struct is_contiguous_back_insert_iterator<std::back_insert_iterator<Container>>
  1468. : is_contiguous<Container> {};
  1469. template <>
  1470. struct is_contiguous_back_insert_iterator<appender> : std::true_type {};
  1471. // A type-erased reference to an std::locale to avoid a heavy <locale> include.
  1472. class locale_ref {
  1473. private:
  1474. const void* locale_; // A type-erased pointer to std::locale.
  1475. public:
  1476. constexpr locale_ref() : locale_(nullptr) {}
  1477. template <typename Locale> explicit locale_ref(const Locale& loc);
  1478. explicit operator bool() const noexcept { return locale_ != nullptr; }
  1479. template <typename Locale> auto get() const -> Locale;
  1480. };
  1481. template <typename> constexpr auto encode_types() -> unsigned long long {
  1482. return 0;
  1483. }
  1484. template <typename Context, typename Arg, typename... Args>
  1485. constexpr auto encode_types() -> unsigned long long {
  1486. return static_cast<unsigned>(mapped_type_constant<Arg, Context>::value) |
  1487. (encode_types<Context, Args...>() << packed_arg_bits);
  1488. }
  1489. template <typename Context, typename T>
  1490. FMT_CONSTEXPR FMT_INLINE auto make_value(T&& val) -> value<Context> {
  1491. const auto& arg = arg_mapper<Context>().map(FMT_FORWARD(val));
  1492. constexpr bool formattable_char =
  1493. !std::is_same<decltype(arg), const unformattable_char&>::value;
  1494. static_assert(formattable_char, "Mixing character types is disallowed.");
  1495. constexpr bool formattable_const =
  1496. !std::is_same<decltype(arg), const unformattable_const&>::value;
  1497. static_assert(formattable_const, "Cannot format a const argument.");
  1498. // Formatting of arbitrary pointers is disallowed. If you want to output
  1499. // a pointer cast it to "void *" or "const void *". In particular, this
  1500. // forbids formatting of "[const] volatile char *" which is printed as bool
  1501. // by iostreams.
  1502. constexpr bool formattable_pointer =
  1503. !std::is_same<decltype(arg), const unformattable_pointer&>::value;
  1504. static_assert(formattable_pointer,
  1505. "Formatting of non-void pointers is disallowed.");
  1506. constexpr bool formattable =
  1507. !std::is_same<decltype(arg), const unformattable&>::value;
  1508. static_assert(
  1509. formattable,
  1510. "Cannot format an argument. To make type T formattable provide a "
  1511. "formatter<T> specialization: https://fmt.dev/latest/api.html#udt");
  1512. return {arg};
  1513. }
  1514. template <typename Context, typename T>
  1515. FMT_CONSTEXPR auto make_arg(T&& value) -> basic_format_arg<Context> {
  1516. basic_format_arg<Context> arg;
  1517. arg.type_ = mapped_type_constant<T, Context>::value;
  1518. arg.value_ = make_value<Context>(value);
  1519. return arg;
  1520. }
  1521. // The type template parameter is there to avoid an ODR violation when using
  1522. // a fallback formatter in one translation unit and an implicit conversion in
  1523. // another (not recommended).
  1524. template <bool IS_PACKED, typename Context, type, typename T,
  1525. FMT_ENABLE_IF(IS_PACKED)>
  1526. FMT_CONSTEXPR FMT_INLINE auto make_arg(T&& val) -> value<Context> {
  1527. return make_value<Context>(val);
  1528. }
  1529. template <bool IS_PACKED, typename Context, type, typename T,
  1530. FMT_ENABLE_IF(!IS_PACKED)>
  1531. FMT_CONSTEXPR inline auto make_arg(T&& value) -> basic_format_arg<Context> {
  1532. return make_arg<Context>(value);
  1533. }
  1534. FMT_END_DETAIL_NAMESPACE
  1535. // Formatting context.
  1536. template <typename OutputIt, typename Char> class basic_format_context {
  1537. public:
  1538. /** The character type for the output. */
  1539. using char_type = Char;
  1540. private:
  1541. OutputIt out_;
  1542. basic_format_args<basic_format_context> args_;
  1543. detail::locale_ref loc_;
  1544. public:
  1545. using iterator = OutputIt;
  1546. using format_arg = basic_format_arg<basic_format_context>;
  1547. using parse_context_type = basic_format_parse_context<Char>;
  1548. template <typename T> using formatter_type = formatter<T, char_type>;
  1549. basic_format_context(basic_format_context&&) = default;
  1550. basic_format_context(const basic_format_context&) = delete;
  1551. void operator=(const basic_format_context&) = delete;
  1552. /**
  1553. Constructs a ``basic_format_context`` object. References to the arguments are
  1554. stored in the object so make sure they have appropriate lifetimes.
  1555. */
  1556. constexpr basic_format_context(
  1557. OutputIt out, basic_format_args<basic_format_context> ctx_args,
  1558. detail::locale_ref loc = detail::locale_ref())
  1559. : out_(out), args_(ctx_args), loc_(loc) {}
  1560. constexpr auto arg(int id) const -> format_arg { return args_.get(id); }
  1561. FMT_CONSTEXPR auto arg(basic_string_view<char_type> name) -> format_arg {
  1562. return args_.get(name);
  1563. }
  1564. FMT_CONSTEXPR auto arg_id(basic_string_view<char_type> name) -> int {
  1565. return args_.get_id(name);
  1566. }
  1567. auto args() const -> const basic_format_args<basic_format_context>& {
  1568. return args_;
  1569. }
  1570. FMT_CONSTEXPR auto error_handler() -> detail::error_handler { return {}; }
  1571. void on_error(const char* message) { error_handler().on_error(message); }
  1572. // Returns an iterator to the beginning of the output range.
  1573. FMT_CONSTEXPR auto out() -> iterator { return out_; }
  1574. // Advances the begin iterator to ``it``.
  1575. void advance_to(iterator it) {
  1576. if (!detail::is_back_insert_iterator<iterator>()) out_ = it;
  1577. }
  1578. FMT_CONSTEXPR auto locale() -> detail::locale_ref { return loc_; }
  1579. };
  1580. template <typename Char>
  1581. using buffer_context =
  1582. basic_format_context<detail::buffer_appender<Char>, Char>;
  1583. using format_context = buffer_context<char>;
  1584. // Workaround an alias issue: https://stackoverflow.com/q/62767544/471164.
  1585. #define FMT_BUFFER_CONTEXT(Char) \
  1586. basic_format_context<detail::buffer_appender<Char>, Char>
  1587. template <typename T, typename Char = char>
  1588. using is_formattable = bool_constant<
  1589. !std::is_base_of<detail::unformattable,
  1590. decltype(detail::arg_mapper<buffer_context<Char>>().map(
  1591. std::declval<T>()))>::value &&
  1592. !detail::has_fallback_formatter<T, Char>::value>;
  1593. /**
  1594. \rst
  1595. An array of references to arguments. It can be implicitly converted into
  1596. `~fmt::basic_format_args` for passing into type-erased formatting functions
  1597. such as `~fmt::vformat`.
  1598. \endrst
  1599. */
  1600. template <typename Context, typename... Args>
  1601. class format_arg_store
  1602. #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
  1603. // Workaround a GCC template argument substitution bug.
  1604. : public basic_format_args<Context>
  1605. #endif
  1606. {
  1607. private:
  1608. static const size_t num_args = sizeof...(Args);
  1609. static const size_t num_named_args = detail::count_named_args<Args...>();
  1610. static const bool is_packed = num_args <= detail::max_packed_args;
  1611. using value_type = conditional_t<is_packed, detail::value<Context>,
  1612. basic_format_arg<Context>>;
  1613. detail::arg_data<value_type, typename Context::char_type, num_args,
  1614. num_named_args>
  1615. data_;
  1616. friend class basic_format_args<Context>;
  1617. static constexpr unsigned long long desc =
  1618. (is_packed ? detail::encode_types<Context, Args...>()
  1619. : detail::is_unpacked_bit | num_args) |
  1620. (num_named_args != 0
  1621. ? static_cast<unsigned long long>(detail::has_named_args_bit)
  1622. : 0);
  1623. public:
  1624. template <typename... T>
  1625. FMT_CONSTEXPR FMT_INLINE format_arg_store(T&&... args)
  1626. :
  1627. #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
  1628. basic_format_args<Context>(*this),
  1629. #endif
  1630. data_{detail::make_arg<
  1631. is_packed, Context,
  1632. detail::mapped_type_constant<remove_cvref_t<T>, Context>::value>(
  1633. FMT_FORWARD(args))...} {
  1634. detail::init_named_args(data_.named_args(), 0, 0, args...);
  1635. }
  1636. };
  1637. /**
  1638. \rst
  1639. Constructs a `~fmt::format_arg_store` object that contains references to
  1640. arguments and can be implicitly converted to `~fmt::format_args`. `Context`
  1641. can be omitted in which case it defaults to `~fmt::context`.
  1642. See `~fmt::arg` for lifetime considerations.
  1643. \endrst
  1644. */
  1645. template <typename Context = format_context, typename... Args>
  1646. constexpr auto make_format_args(Args&&... args)
  1647. -> format_arg_store<Context, remove_cvref_t<Args>...> {
  1648. return {FMT_FORWARD(args)...};
  1649. }
  1650. /**
  1651. \rst
  1652. Returns a named argument to be used in a formatting function.
  1653. It should only be used in a call to a formatting function or
  1654. `dynamic_format_arg_store::push_back`.
  1655. **Example**::
  1656. fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23));
  1657. \endrst
  1658. */
  1659. template <typename Char, typename T>
  1660. inline auto arg(const Char* name, const T& arg) -> detail::named_arg<Char, T> {
  1661. static_assert(!detail::is_named_arg<T>(), "nested named arguments");
  1662. return {name, arg};
  1663. }
  1664. /**
  1665. \rst
  1666. A view of a collection of formatting arguments. To avoid lifetime issues it
  1667. should only be used as a parameter type in type-erased functions such as
  1668. ``vformat``::
  1669. void vlog(string_view format_str, format_args args); // OK
  1670. format_args args = make_format_args(42); // Error: dangling reference
  1671. \endrst
  1672. */
  1673. template <typename Context> class basic_format_args {
  1674. public:
  1675. using size_type = int;
  1676. using format_arg = basic_format_arg<Context>;
  1677. private:
  1678. // A descriptor that contains information about formatting arguments.
  1679. // If the number of arguments is less or equal to max_packed_args then
  1680. // argument types are passed in the descriptor. This reduces binary code size
  1681. // per formatting function call.
  1682. unsigned long long desc_;
  1683. union {
  1684. // If is_packed() returns true then argument values are stored in values_;
  1685. // otherwise they are stored in args_. This is done to improve cache
  1686. // locality and reduce compiled code size since storing larger objects
  1687. // may require more code (at least on x86-64) even if the same amount of
  1688. // data is actually copied to stack. It saves ~10% on the bloat test.
  1689. const detail::value<Context>* values_;
  1690. const format_arg* args_;
  1691. };
  1692. constexpr auto is_packed() const -> bool {
  1693. return (desc_ & detail::is_unpacked_bit) == 0;
  1694. }
  1695. auto has_named_args() const -> bool {
  1696. return (desc_ & detail::has_named_args_bit) != 0;
  1697. }
  1698. FMT_CONSTEXPR auto type(int index) const -> detail::type {
  1699. int shift = index * detail::packed_arg_bits;
  1700. unsigned int mask = (1 << detail::packed_arg_bits) - 1;
  1701. return static_cast<detail::type>((desc_ >> shift) & mask);
  1702. }
  1703. constexpr FMT_INLINE basic_format_args(unsigned long long desc,
  1704. const detail::value<Context>* values)
  1705. : desc_(desc), values_(values) {}
  1706. constexpr basic_format_args(unsigned long long desc, const format_arg* args)
  1707. : desc_(desc), args_(args) {}
  1708. public:
  1709. constexpr basic_format_args() : desc_(0), args_(nullptr) {}
  1710. /**
  1711. \rst
  1712. Constructs a `basic_format_args` object from `~fmt::format_arg_store`.
  1713. \endrst
  1714. */
  1715. template <typename... Args>
  1716. constexpr FMT_INLINE basic_format_args(
  1717. const format_arg_store<Context, Args...>& store)
  1718. : basic_format_args(format_arg_store<Context, Args...>::desc,
  1719. store.data_.args()) {}
  1720. /**
  1721. \rst
  1722. Constructs a `basic_format_args` object from
  1723. `~fmt::dynamic_format_arg_store`.
  1724. \endrst
  1725. */
  1726. constexpr FMT_INLINE basic_format_args(
  1727. const dynamic_format_arg_store<Context>& store)
  1728. : basic_format_args(store.get_types(), store.data()) {}
  1729. /**
  1730. \rst
  1731. Constructs a `basic_format_args` object from a dynamic set of arguments.
  1732. \endrst
  1733. */
  1734. constexpr basic_format_args(const format_arg* args, int count)
  1735. : basic_format_args(detail::is_unpacked_bit | detail::to_unsigned(count),
  1736. args) {}
  1737. /** Returns the argument with the specified id. */
  1738. FMT_CONSTEXPR auto get(int id) const -> format_arg {
  1739. format_arg arg;
  1740. if (!is_packed()) {
  1741. if (id < max_size()) arg = args_[id];
  1742. return arg;
  1743. }
  1744. if (id >= detail::max_packed_args) return arg;
  1745. arg.type_ = type(id);
  1746. if (arg.type_ == detail::type::none_type) return arg;
  1747. arg.value_ = values_[id];
  1748. return arg;
  1749. }
  1750. template <typename Char>
  1751. auto get(basic_string_view<Char> name) const -> format_arg {
  1752. int id = get_id(name);
  1753. return id >= 0 ? get(id) : format_arg();
  1754. }
  1755. template <typename Char>
  1756. auto get_id(basic_string_view<Char> name) const -> int {
  1757. if (!has_named_args()) return -1;
  1758. const auto& named_args =
  1759. (is_packed() ? values_[-1] : args_[-1].value_).named_args;
  1760. for (size_t i = 0; i < named_args.size; ++i) {
  1761. if (named_args.data[i].name == name) return named_args.data[i].id;
  1762. }
  1763. return -1;
  1764. }
  1765. auto max_size() const -> int {
  1766. unsigned long long max_packed = detail::max_packed_args;
  1767. return static_cast<int>(is_packed() ? max_packed
  1768. : desc_ & ~detail::is_unpacked_bit);
  1769. }
  1770. };
  1771. /** An alias to ``basic_format_args<format_context>``. */
  1772. // A separate type would result in shorter symbols but break ABI compatibility
  1773. // between clang and gcc on ARM (#1919).
  1774. using format_args = basic_format_args<format_context>;
  1775. // We cannot use enum classes as bit fields because of a gcc bug, so we put them
  1776. // in namespaces instead (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414).
  1777. // Additionally, if an underlying type is specified, older gcc incorrectly warns
  1778. // that the type is too small. Both bugs are fixed in gcc 9.3.
  1779. #if FMT_GCC_VERSION && FMT_GCC_VERSION < 903
  1780. # define FMT_ENUM_UNDERLYING_TYPE(type)
  1781. #else
  1782. # define FMT_ENUM_UNDERLYING_TYPE(type) : type
  1783. #endif
  1784. namespace align {
  1785. enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, left, right, center,
  1786. numeric};
  1787. }
  1788. using align_t = align::type;
  1789. namespace sign {
  1790. enum type FMT_ENUM_UNDERLYING_TYPE(unsigned char){none, minus, plus, space};
  1791. }
  1792. using sign_t = sign::type;
  1793. FMT_BEGIN_DETAIL_NAMESPACE
  1794. // Workaround an array initialization issue in gcc 4.8.
  1795. template <typename Char> struct fill_t {
  1796. private:
  1797. enum { max_size = 4 };
  1798. Char data_[max_size] = {Char(' '), Char(0), Char(0), Char(0)};
  1799. unsigned char size_ = 1;
  1800. public:
  1801. FMT_CONSTEXPR void operator=(basic_string_view<Char> s) {
  1802. auto size = s.size();
  1803. if (size > max_size) return throw_format_error("invalid fill");
  1804. for (size_t i = 0; i < size; ++i) data_[i] = s[i];
  1805. size_ = static_cast<unsigned char>(size);
  1806. }
  1807. constexpr auto size() const -> size_t { return size_; }
  1808. constexpr auto data() const -> const Char* { return data_; }
  1809. FMT_CONSTEXPR auto operator[](size_t index) -> Char& { return data_[index]; }
  1810. FMT_CONSTEXPR auto operator[](size_t index) const -> const Char& {
  1811. return data_[index];
  1812. }
  1813. };
  1814. FMT_END_DETAIL_NAMESPACE
  1815. enum class presentation_type : unsigned char {
  1816. none,
  1817. // Integer types should go first,
  1818. dec, // 'd'
  1819. oct, // 'o'
  1820. hex_lower, // 'x'
  1821. hex_upper, // 'X'
  1822. bin_lower, // 'b'
  1823. bin_upper, // 'B'
  1824. hexfloat_lower, // 'a'
  1825. hexfloat_upper, // 'A'
  1826. exp_lower, // 'e'
  1827. exp_upper, // 'E'
  1828. fixed_lower, // 'f'
  1829. fixed_upper, // 'F'
  1830. general_lower, // 'g'
  1831. general_upper, // 'G'
  1832. chr, // 'c'
  1833. string, // 's'
  1834. pointer, // 'p'
  1835. debug // '?'
  1836. };
  1837. // Format specifiers for built-in and string types.
  1838. template <typename Char> struct basic_format_specs {
  1839. int width;
  1840. int precision;
  1841. presentation_type type;
  1842. align_t align : 4;
  1843. sign_t sign : 3;
  1844. bool alt : 1; // Alternate form ('#').
  1845. bool localized : 1;
  1846. detail::fill_t<Char> fill;
  1847. constexpr basic_format_specs()
  1848. : width(0),
  1849. precision(-1),
  1850. type(presentation_type::none),
  1851. align(align::none),
  1852. sign(sign::none),
  1853. alt(false),
  1854. localized(false) {}
  1855. };
  1856. using format_specs = basic_format_specs<char>;
  1857. FMT_BEGIN_DETAIL_NAMESPACE
  1858. enum class arg_id_kind { none, index, name };
  1859. // An argument reference.
  1860. template <typename Char> struct arg_ref {
  1861. FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {}
  1862. FMT_CONSTEXPR explicit arg_ref(int index)
  1863. : kind(arg_id_kind::index), val(index) {}
  1864. FMT_CONSTEXPR explicit arg_ref(basic_string_view<Char> name)
  1865. : kind(arg_id_kind::name), val(name) {}
  1866. FMT_CONSTEXPR auto operator=(int idx) -> arg_ref& {
  1867. kind = arg_id_kind::index;
  1868. val.index = idx;
  1869. return *this;
  1870. }
  1871. arg_id_kind kind;
  1872. union value {
  1873. FMT_CONSTEXPR value(int id = 0) : index{id} {}
  1874. FMT_CONSTEXPR value(basic_string_view<Char> n) : name(n) {}
  1875. int index;
  1876. basic_string_view<Char> name;
  1877. } val;
  1878. };
  1879. // Format specifiers with width and precision resolved at formatting rather
  1880. // than parsing time to allow re-using the same parsed specifiers with
  1881. // different sets of arguments (precompilation of format strings).
  1882. template <typename Char>
  1883. struct dynamic_format_specs : basic_format_specs<Char> {
  1884. arg_ref<Char> width_ref;
  1885. arg_ref<Char> precision_ref;
  1886. };
  1887. struct auto_id {};
  1888. // A format specifier handler that sets fields in basic_format_specs.
  1889. template <typename Char> class specs_setter {
  1890. protected:
  1891. basic_format_specs<Char>& specs_;
  1892. public:
  1893. explicit FMT_CONSTEXPR specs_setter(basic_format_specs<Char>& specs)
  1894. : specs_(specs) {}
  1895. FMT_CONSTEXPR specs_setter(const specs_setter& other)
  1896. : specs_(other.specs_) {}
  1897. FMT_CONSTEXPR void on_align(align_t align) { specs_.align = align; }
  1898. FMT_CONSTEXPR void on_fill(basic_string_view<Char> fill) {
  1899. specs_.fill = fill;
  1900. }
  1901. FMT_CONSTEXPR void on_sign(sign_t s) { specs_.sign = s; }
  1902. FMT_CONSTEXPR void on_hash() { specs_.alt = true; }
  1903. FMT_CONSTEXPR void on_localized() { specs_.localized = true; }
  1904. FMT_CONSTEXPR void on_zero() {
  1905. if (specs_.align == align::none) specs_.align = align::numeric;
  1906. specs_.fill[0] = Char('0');
  1907. }
  1908. FMT_CONSTEXPR void on_width(int width) { specs_.width = width; }
  1909. FMT_CONSTEXPR void on_precision(int precision) {
  1910. specs_.precision = precision;
  1911. }
  1912. FMT_CONSTEXPR void end_precision() {}
  1913. FMT_CONSTEXPR void on_type(presentation_type type) { specs_.type = type; }
  1914. };
  1915. // Format spec handler that saves references to arguments representing dynamic
  1916. // width and precision to be resolved at formatting time.
  1917. template <typename ParseContext>
  1918. class dynamic_specs_handler
  1919. : public specs_setter<typename ParseContext::char_type> {
  1920. public:
  1921. using char_type = typename ParseContext::char_type;
  1922. FMT_CONSTEXPR dynamic_specs_handler(dynamic_format_specs<char_type>& specs,
  1923. ParseContext& ctx)
  1924. : specs_setter<char_type>(specs), specs_(specs), context_(ctx) {}
  1925. FMT_CONSTEXPR dynamic_specs_handler(const dynamic_specs_handler& other)
  1926. : specs_setter<char_type>(other),
  1927. specs_(other.specs_),
  1928. context_(other.context_) {}
  1929. template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
  1930. specs_.width_ref = make_arg_ref(arg_id);
  1931. }
  1932. template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
  1933. specs_.precision_ref = make_arg_ref(arg_id);
  1934. }
  1935. FMT_CONSTEXPR void on_error(const char* message) {
  1936. context_.on_error(message);
  1937. }
  1938. private:
  1939. dynamic_format_specs<char_type>& specs_;
  1940. ParseContext& context_;
  1941. using arg_ref_type = arg_ref<char_type>;
  1942. FMT_CONSTEXPR auto make_arg_ref(int arg_id) -> arg_ref_type {
  1943. context_.check_arg_id(arg_id);
  1944. context_.check_dynamic_spec(arg_id);
  1945. return arg_ref_type(arg_id);
  1946. }
  1947. FMT_CONSTEXPR auto make_arg_ref(auto_id) -> arg_ref_type {
  1948. int arg_id = context_.next_arg_id();
  1949. context_.check_dynamic_spec(arg_id);
  1950. return arg_ref_type(arg_id);
  1951. }
  1952. FMT_CONSTEXPR auto make_arg_ref(basic_string_view<char_type> arg_id)
  1953. -> arg_ref_type {
  1954. context_.check_arg_id(arg_id);
  1955. basic_string_view<char_type> format_str(
  1956. context_.begin(), to_unsigned(context_.end() - context_.begin()));
  1957. return arg_ref_type(arg_id);
  1958. }
  1959. };
  1960. template <typename Char> constexpr bool is_ascii_letter(Char c) {
  1961. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
  1962. }
  1963. // Converts a character to ASCII. Returns a number > 127 on conversion failure.
  1964. template <typename Char, FMT_ENABLE_IF(std::is_integral<Char>::value)>
  1965. constexpr auto to_ascii(Char c) -> Char {
  1966. return c;
  1967. }
  1968. template <typename Char, FMT_ENABLE_IF(std::is_enum<Char>::value)>
  1969. constexpr auto to_ascii(Char c) -> underlying_t<Char> {
  1970. return c;
  1971. }
  1972. FMT_CONSTEXPR inline auto code_point_length_impl(char c) -> int {
  1973. return "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0\0\0\2\2\2\2\3\3\4"
  1974. [static_cast<unsigned char>(c) >> 3];
  1975. }
  1976. template <typename Char>
  1977. FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int {
  1978. if (const_check(sizeof(Char) != 1)) return 1;
  1979. int len = code_point_length_impl(static_cast<char>(*begin));
  1980. // Compute the pointer to the next character early so that the next
  1981. // iteration can start working on the next character. Neither Clang
  1982. // nor GCC figure out this reordering on their own.
  1983. return len + !len;
  1984. }
  1985. // Return the result via the out param to workaround gcc bug 77539.
  1986. template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>
  1987. FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool {
  1988. for (out = first; out != last; ++out) {
  1989. if (*out == value) return true;
  1990. }
  1991. return false;
  1992. }
  1993. template <>
  1994. inline auto find<false, char>(const char* first, const char* last, char value,
  1995. const char*& out) -> bool {
  1996. out = static_cast<const char*>(
  1997. std::memchr(first, value, to_unsigned(last - first)));
  1998. return out != nullptr;
  1999. }
  2000. // Parses the range [begin, end) as an unsigned integer. This function assumes
  2001. // that the range is non-empty and the first character is a digit.
  2002. template <typename Char>
  2003. FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end,
  2004. int error_value) noexcept -> int {
  2005. FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', "");
  2006. unsigned value = 0, prev = 0;
  2007. auto p = begin;
  2008. do {
  2009. prev = value;
  2010. value = value * 10 + unsigned(*p - '0');
  2011. ++p;
  2012. } while (p != end && '0' <= *p && *p <= '9');
  2013. auto num_digits = p - begin;
  2014. begin = p;
  2015. if (num_digits <= std::numeric_limits<int>::digits10)
  2016. return static_cast<int>(value);
  2017. // Check for overflow.
  2018. const unsigned max = to_unsigned((std::numeric_limits<int>::max)());
  2019. return num_digits == std::numeric_limits<int>::digits10 + 1 &&
  2020. prev * 10ull + unsigned(p[-1] - '0') <= max
  2021. ? static_cast<int>(value)
  2022. : error_value;
  2023. }
  2024. // Parses fill and alignment.
  2025. template <typename Char, typename Handler>
  2026. FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end,
  2027. Handler&& handler) -> const Char* {
  2028. FMT_ASSERT(begin != end, "");
  2029. auto align = align::none;
  2030. auto p = begin + code_point_length(begin);
  2031. if (end - p <= 0) p = begin;
  2032. for (;;) {
  2033. switch (to_ascii(*p)) {
  2034. case '<':
  2035. align = align::left;
  2036. break;
  2037. case '>':
  2038. align = align::right;
  2039. break;
  2040. case '^':
  2041. align = align::center;
  2042. break;
  2043. default:
  2044. break;
  2045. }
  2046. if (align != align::none) {
  2047. if (p != begin) {
  2048. auto c = *begin;
  2049. if (c == '{')
  2050. return handler.on_error("invalid fill character '{'"), begin;
  2051. handler.on_fill(basic_string_view<Char>(begin, to_unsigned(p - begin)));
  2052. begin = p + 1;
  2053. } else
  2054. ++begin;
  2055. handler.on_align(align);
  2056. break;
  2057. } else if (p == begin) {
  2058. break;
  2059. }
  2060. p = begin;
  2061. }
  2062. return begin;
  2063. }
  2064. template <typename Char> FMT_CONSTEXPR bool is_name_start(Char c) {
  2065. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c;
  2066. }
  2067. template <typename Char, typename IDHandler>
  2068. FMT_CONSTEXPR auto do_parse_arg_id(const Char* begin, const Char* end,
  2069. IDHandler&& handler) -> const Char* {
  2070. FMT_ASSERT(begin != end, "");
  2071. Char c = *begin;
  2072. if (c >= '0' && c <= '9') {
  2073. int index = 0;
  2074. if (c != '0')
  2075. index =
  2076. parse_nonnegative_int(begin, end, (std::numeric_limits<int>::max)());
  2077. else
  2078. ++begin;
  2079. if (begin == end || (*begin != '}' && *begin != ':'))
  2080. handler.on_error("invalid format string");
  2081. else
  2082. handler(index);
  2083. return begin;
  2084. }
  2085. if (!is_name_start(c)) {
  2086. handler.on_error("invalid format string");
  2087. return begin;
  2088. }
  2089. auto it = begin;
  2090. do {
  2091. ++it;
  2092. } while (it != end && (is_name_start(c = *it) || ('0' <= c && c <= '9')));
  2093. handler(basic_string_view<Char>(begin, to_unsigned(it - begin)));
  2094. return it;
  2095. }
  2096. template <typename Char, typename IDHandler>
  2097. FMT_CONSTEXPR FMT_INLINE auto parse_arg_id(const Char* begin, const Char* end,
  2098. IDHandler&& handler) -> const Char* {
  2099. Char c = *begin;
  2100. if (c != '}' && c != ':') return do_parse_arg_id(begin, end, handler);
  2101. handler();
  2102. return begin;
  2103. }
  2104. template <typename Char, typename Handler>
  2105. FMT_CONSTEXPR auto parse_width(const Char* begin, const Char* end,
  2106. Handler&& handler) -> const Char* {
  2107. using detail::auto_id;
  2108. struct width_adapter {
  2109. Handler& handler;
  2110. FMT_CONSTEXPR void operator()() { handler.on_dynamic_width(auto_id()); }
  2111. FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_width(id); }
  2112. FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
  2113. handler.on_dynamic_width(id);
  2114. }
  2115. FMT_CONSTEXPR void on_error(const char* message) {
  2116. if (message) handler.on_error(message);
  2117. }
  2118. };
  2119. FMT_ASSERT(begin != end, "");
  2120. if ('0' <= *begin && *begin <= '9') {
  2121. int width = parse_nonnegative_int(begin, end, -1);
  2122. if (width != -1)
  2123. handler.on_width(width);
  2124. else
  2125. handler.on_error("number is too big");
  2126. } else if (*begin == '{') {
  2127. ++begin;
  2128. if (begin != end) begin = parse_arg_id(begin, end, width_adapter{handler});
  2129. if (begin == end || *begin != '}')
  2130. return handler.on_error("invalid format string"), begin;
  2131. ++begin;
  2132. }
  2133. return begin;
  2134. }
  2135. template <typename Char, typename Handler>
  2136. FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end,
  2137. Handler&& handler) -> const Char* {
  2138. using detail::auto_id;
  2139. struct precision_adapter {
  2140. Handler& handler;
  2141. FMT_CONSTEXPR void operator()() { handler.on_dynamic_precision(auto_id()); }
  2142. FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_precision(id); }
  2143. FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
  2144. handler.on_dynamic_precision(id);
  2145. }
  2146. FMT_CONSTEXPR void on_error(const char* message) {
  2147. if (message) handler.on_error(message);
  2148. }
  2149. };
  2150. ++begin;
  2151. auto c = begin != end ? *begin : Char();
  2152. if ('0' <= c && c <= '9') {
  2153. auto precision = parse_nonnegative_int(begin, end, -1);
  2154. if (precision != -1)
  2155. handler.on_precision(precision);
  2156. else
  2157. handler.on_error("number is too big");
  2158. } else if (c == '{') {
  2159. ++begin;
  2160. if (begin != end)
  2161. begin = parse_arg_id(begin, end, precision_adapter{handler});
  2162. if (begin == end || *begin++ != '}')
  2163. return handler.on_error("invalid format string"), begin;
  2164. } else {
  2165. return handler.on_error("missing precision specifier"), begin;
  2166. }
  2167. handler.end_precision();
  2168. return begin;
  2169. }
  2170. template <typename Char>
  2171. FMT_CONSTEXPR auto parse_presentation_type(Char type) -> presentation_type {
  2172. switch (to_ascii(type)) {
  2173. case 'd':
  2174. return presentation_type::dec;
  2175. case 'o':
  2176. return presentation_type::oct;
  2177. case 'x':
  2178. return presentation_type::hex_lower;
  2179. case 'X':
  2180. return presentation_type::hex_upper;
  2181. case 'b':
  2182. return presentation_type::bin_lower;
  2183. case 'B':
  2184. return presentation_type::bin_upper;
  2185. case 'a':
  2186. return presentation_type::hexfloat_lower;
  2187. case 'A':
  2188. return presentation_type::hexfloat_upper;
  2189. case 'e':
  2190. return presentation_type::exp_lower;
  2191. case 'E':
  2192. return presentation_type::exp_upper;
  2193. case 'f':
  2194. return presentation_type::fixed_lower;
  2195. case 'F':
  2196. return presentation_type::fixed_upper;
  2197. case 'g':
  2198. return presentation_type::general_lower;
  2199. case 'G':
  2200. return presentation_type::general_upper;
  2201. case 'c':
  2202. return presentation_type::chr;
  2203. case 's':
  2204. return presentation_type::string;
  2205. case 'p':
  2206. return presentation_type::pointer;
  2207. case '?':
  2208. return presentation_type::debug;
  2209. default:
  2210. return presentation_type::none;
  2211. }
  2212. }
  2213. // Parses standard format specifiers and sends notifications about parsed
  2214. // components to handler.
  2215. template <typename Char, typename SpecHandler>
  2216. FMT_CONSTEXPR FMT_INLINE auto parse_format_specs(const Char* begin,
  2217. const Char* end,
  2218. SpecHandler&& handler)
  2219. -> const Char* {
  2220. if (1 < end - begin && begin[1] == '}' && is_ascii_letter(*begin) &&
  2221. *begin != 'L') {
  2222. presentation_type type = parse_presentation_type(*begin++);
  2223. if (type == presentation_type::none)
  2224. handler.on_error("invalid type specifier");
  2225. handler.on_type(type);
  2226. return begin;
  2227. }
  2228. if (begin == end) return begin;
  2229. begin = parse_align(begin, end, handler);
  2230. if (begin == end) return begin;
  2231. // Parse sign.
  2232. switch (to_ascii(*begin)) {
  2233. case '+':
  2234. handler.on_sign(sign::plus);
  2235. ++begin;
  2236. break;
  2237. case '-':
  2238. handler.on_sign(sign::minus);
  2239. ++begin;
  2240. break;
  2241. case ' ':
  2242. handler.on_sign(sign::space);
  2243. ++begin;
  2244. break;
  2245. default:
  2246. break;
  2247. }
  2248. if (begin == end) return begin;
  2249. if (*begin == '#') {
  2250. handler.on_hash();
  2251. if (++begin == end) return begin;
  2252. }
  2253. // Parse zero flag.
  2254. if (*begin == '0') {
  2255. handler.on_zero();
  2256. if (++begin == end) return begin;
  2257. }
  2258. begin = parse_width(begin, end, handler);
  2259. if (begin == end) return begin;
  2260. // Parse precision.
  2261. if (*begin == '.') {
  2262. begin = parse_precision(begin, end, handler);
  2263. if (begin == end) return begin;
  2264. }
  2265. if (*begin == 'L') {
  2266. handler.on_localized();
  2267. ++begin;
  2268. }
  2269. // Parse type.
  2270. if (begin != end && *begin != '}') {
  2271. presentation_type type = parse_presentation_type(*begin++);
  2272. if (type == presentation_type::none)
  2273. handler.on_error("invalid type specifier");
  2274. handler.on_type(type);
  2275. }
  2276. return begin;
  2277. }
  2278. template <typename Char, typename Handler>
  2279. FMT_CONSTEXPR auto parse_replacement_field(const Char* begin, const Char* end,
  2280. Handler&& handler) -> const Char* {
  2281. struct id_adapter {
  2282. Handler& handler;
  2283. int arg_id;
  2284. FMT_CONSTEXPR void operator()() { arg_id = handler.on_arg_id(); }
  2285. FMT_CONSTEXPR void operator()(int id) { arg_id = handler.on_arg_id(id); }
  2286. FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
  2287. arg_id = handler.on_arg_id(id);
  2288. }
  2289. FMT_CONSTEXPR void on_error(const char* message) {
  2290. if (message) handler.on_error(message);
  2291. }
  2292. };
  2293. ++begin;
  2294. if (begin == end) return handler.on_error("invalid format string"), end;
  2295. if (*begin == '}') {
  2296. handler.on_replacement_field(handler.on_arg_id(), begin);
  2297. } else if (*begin == '{') {
  2298. handler.on_text(begin, begin + 1);
  2299. } else {
  2300. auto adapter = id_adapter{handler, 0};
  2301. begin = parse_arg_id(begin, end, adapter);
  2302. Char c = begin != end ? *begin : Char();
  2303. if (c == '}') {
  2304. handler.on_replacement_field(adapter.arg_id, begin);
  2305. } else if (c == ':') {
  2306. begin = handler.on_format_specs(adapter.arg_id, begin + 1, end);
  2307. if (begin == end || *begin != '}')
  2308. return handler.on_error("unknown format specifier"), end;
  2309. } else {
  2310. return handler.on_error("missing '}' in format string"), end;
  2311. }
  2312. }
  2313. return begin + 1;
  2314. }
  2315. template <bool IS_CONSTEXPR, typename Char, typename Handler>
  2316. FMT_CONSTEXPR FMT_INLINE void parse_format_string(
  2317. basic_string_view<Char> format_str, Handler&& handler) {
  2318. // Workaround a name-lookup bug in MSVC's modules implementation.
  2319. using detail::find;
  2320. auto begin = format_str.data();
  2321. auto end = begin + format_str.size();
  2322. if (end - begin < 32) {
  2323. // Use a simple loop instead of memchr for small strings.
  2324. const Char* p = begin;
  2325. while (p != end) {
  2326. auto c = *p++;
  2327. if (c == '{') {
  2328. handler.on_text(begin, p - 1);
  2329. begin = p = parse_replacement_field(p - 1, end, handler);
  2330. } else if (c == '}') {
  2331. if (p == end || *p != '}')
  2332. return handler.on_error("unmatched '}' in format string");
  2333. handler.on_text(begin, p);
  2334. begin = ++p;
  2335. }
  2336. }
  2337. handler.on_text(begin, end);
  2338. return;
  2339. }
  2340. struct writer {
  2341. FMT_CONSTEXPR void operator()(const Char* from, const Char* to) {
  2342. if (from == to) return;
  2343. for (;;) {
  2344. const Char* p = nullptr;
  2345. if (!find<IS_CONSTEXPR>(from, to, Char('}'), p))
  2346. return handler_.on_text(from, to);
  2347. ++p;
  2348. if (p == to || *p != '}')
  2349. return handler_.on_error("unmatched '}' in format string");
  2350. handler_.on_text(from, p);
  2351. from = p + 1;
  2352. }
  2353. }
  2354. Handler& handler_;
  2355. } write = {handler};
  2356. while (begin != end) {
  2357. // Doing two passes with memchr (one for '{' and another for '}') is up to
  2358. // 2.5x faster than the naive one-pass implementation on big format strings.
  2359. const Char* p = begin;
  2360. if (*begin != '{' && !find<IS_CONSTEXPR>(begin + 1, end, Char('{'), p))
  2361. return write(begin, end);
  2362. write(begin, p);
  2363. begin = parse_replacement_field(p, end, handler);
  2364. }
  2365. }
  2366. template <typename T, bool = is_named_arg<T>::value> struct strip_named_arg {
  2367. using type = T;
  2368. };
  2369. template <typename T> struct strip_named_arg<T, true> {
  2370. using type = remove_cvref_t<decltype(T::value)>;
  2371. };
  2372. template <typename T, typename ParseContext>
  2373. FMT_CONSTEXPR auto parse_format_specs(ParseContext& ctx)
  2374. -> decltype(ctx.begin()) {
  2375. using char_type = typename ParseContext::char_type;
  2376. using context = buffer_context<char_type>;
  2377. using stripped_type = typename strip_named_arg<T>::type;
  2378. using mapped_type = conditional_t<
  2379. mapped_type_constant<T, context>::value != type::custom_type,
  2380. decltype(arg_mapper<context>().map(std::declval<const T&>())),
  2381. stripped_type>;
  2382. auto f = conditional_t<has_formatter<mapped_type, context>::value,
  2383. formatter<mapped_type, char_type>,
  2384. fallback_formatter<stripped_type, char_type>>();
  2385. return f.parse(ctx);
  2386. }
  2387. template <typename ErrorHandler>
  2388. FMT_CONSTEXPR void check_int_type_spec(presentation_type type,
  2389. ErrorHandler&& eh) {
  2390. if (type > presentation_type::bin_upper && type != presentation_type::chr)
  2391. eh.on_error("invalid type specifier");
  2392. }
  2393. // Checks char specs and returns true if the type spec is char (and not int).
  2394. template <typename Char, typename ErrorHandler = error_handler>
  2395. FMT_CONSTEXPR auto check_char_specs(const basic_format_specs<Char>& specs,
  2396. ErrorHandler&& eh = {}) -> bool {
  2397. if (specs.type != presentation_type::none &&
  2398. specs.type != presentation_type::chr &&
  2399. specs.type != presentation_type::debug) {
  2400. check_int_type_spec(specs.type, eh);
  2401. return false;
  2402. }
  2403. if (specs.align == align::numeric || specs.sign != sign::none || specs.alt)
  2404. eh.on_error("invalid format specifier for char");
  2405. return true;
  2406. }
  2407. // A floating-point presentation format.
  2408. enum class float_format : unsigned char {
  2409. general, // General: exponent notation or fixed point based on magnitude.
  2410. exp, // Exponent notation with the default precision of 6, e.g. 1.2e-3.
  2411. fixed, // Fixed point with the default precision of 6, e.g. 0.0012.
  2412. hex
  2413. };
  2414. struct float_specs {
  2415. int precision;
  2416. float_format format : 8;
  2417. sign_t sign : 8;
  2418. bool upper : 1;
  2419. bool locale : 1;
  2420. bool binary32 : 1;
  2421. bool showpoint : 1;
  2422. };
  2423. template <typename ErrorHandler = error_handler, typename Char>
  2424. FMT_CONSTEXPR auto parse_float_type_spec(const basic_format_specs<Char>& specs,
  2425. ErrorHandler&& eh = {})
  2426. -> float_specs {
  2427. auto result = float_specs();
  2428. result.showpoint = specs.alt;
  2429. result.locale = specs.localized;
  2430. switch (specs.type) {
  2431. case presentation_type::none:
  2432. result.format = float_format::general;
  2433. break;
  2434. case presentation_type::general_upper:
  2435. result.upper = true;
  2436. FMT_FALLTHROUGH;
  2437. case presentation_type::general_lower:
  2438. result.format = float_format::general;
  2439. break;
  2440. case presentation_type::exp_upper:
  2441. result.upper = true;
  2442. FMT_FALLTHROUGH;
  2443. case presentation_type::exp_lower:
  2444. result.format = float_format::exp;
  2445. result.showpoint |= specs.precision != 0;
  2446. break;
  2447. case presentation_type::fixed_upper:
  2448. result.upper = true;
  2449. FMT_FALLTHROUGH;
  2450. case presentation_type::fixed_lower:
  2451. result.format = float_format::fixed;
  2452. result.showpoint |= specs.precision != 0;
  2453. break;
  2454. case presentation_type::hexfloat_upper:
  2455. result.upper = true;
  2456. FMT_FALLTHROUGH;
  2457. case presentation_type::hexfloat_lower:
  2458. result.format = float_format::hex;
  2459. break;
  2460. default:
  2461. eh.on_error("invalid type specifier");
  2462. break;
  2463. }
  2464. return result;
  2465. }
  2466. template <typename ErrorHandler = error_handler>
  2467. FMT_CONSTEXPR auto check_cstring_type_spec(presentation_type type,
  2468. ErrorHandler&& eh = {}) -> bool {
  2469. if (type == presentation_type::none || type == presentation_type::string ||
  2470. type == presentation_type::debug)
  2471. return true;
  2472. if (type != presentation_type::pointer) eh.on_error("invalid type specifier");
  2473. return false;
  2474. }
  2475. template <typename ErrorHandler = error_handler>
  2476. FMT_CONSTEXPR void check_string_type_spec(presentation_type type,
  2477. ErrorHandler&& eh = {}) {
  2478. if (type != presentation_type::none && type != presentation_type::string &&
  2479. type != presentation_type::debug)
  2480. eh.on_error("invalid type specifier");
  2481. }
  2482. template <typename ErrorHandler>
  2483. FMT_CONSTEXPR void check_pointer_type_spec(presentation_type type,
  2484. ErrorHandler&& eh) {
  2485. if (type != presentation_type::none && type != presentation_type::pointer)
  2486. eh.on_error("invalid type specifier");
  2487. }
  2488. // A parse_format_specs handler that checks if specifiers are consistent with
  2489. // the argument type.
  2490. template <typename Handler> class specs_checker : public Handler {
  2491. private:
  2492. detail::type arg_type_;
  2493. FMT_CONSTEXPR void require_numeric_argument() {
  2494. if (!is_arithmetic_type(arg_type_))
  2495. this->on_error("format specifier requires numeric argument");
  2496. }
  2497. public:
  2498. FMT_CONSTEXPR specs_checker(const Handler& handler, detail::type arg_type)
  2499. : Handler(handler), arg_type_(arg_type) {}
  2500. FMT_CONSTEXPR void on_align(align_t align) {
  2501. if (align == align::numeric) require_numeric_argument();
  2502. Handler::on_align(align);
  2503. }
  2504. FMT_CONSTEXPR void on_sign(sign_t s) {
  2505. require_numeric_argument();
  2506. if (is_integral_type(arg_type_) && arg_type_ != type::int_type &&
  2507. arg_type_ != type::long_long_type && arg_type_ != type::int128_type &&
  2508. arg_type_ != type::char_type) {
  2509. this->on_error("format specifier requires signed argument");
  2510. }
  2511. Handler::on_sign(s);
  2512. }
  2513. FMT_CONSTEXPR void on_hash() {
  2514. require_numeric_argument();
  2515. Handler::on_hash();
  2516. }
  2517. FMT_CONSTEXPR void on_localized() {
  2518. require_numeric_argument();
  2519. Handler::on_localized();
  2520. }
  2521. FMT_CONSTEXPR void on_zero() {
  2522. require_numeric_argument();
  2523. Handler::on_zero();
  2524. }
  2525. FMT_CONSTEXPR void end_precision() {
  2526. if (is_integral_type(arg_type_) || arg_type_ == type::pointer_type)
  2527. this->on_error("precision not allowed for this argument type");
  2528. }
  2529. };
  2530. constexpr int invalid_arg_index = -1;
  2531. #if FMT_USE_NONTYPE_TEMPLATE_ARGS
  2532. template <int N, typename T, typename... Args, typename Char>
  2533. constexpr auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
  2534. if constexpr (detail::is_statically_named_arg<T>()) {
  2535. if (name == T::name) return N;
  2536. }
  2537. if constexpr (sizeof...(Args) > 0)
  2538. return get_arg_index_by_name<N + 1, Args...>(name);
  2539. (void)name; // Workaround an MSVC bug about "unused" parameter.
  2540. return invalid_arg_index;
  2541. }
  2542. #endif
  2543. template <typename... Args, typename Char>
  2544. FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
  2545. #if FMT_USE_NONTYPE_TEMPLATE_ARGS
  2546. if constexpr (sizeof...(Args) > 0)
  2547. return get_arg_index_by_name<0, Args...>(name);
  2548. #endif
  2549. (void)name;
  2550. return invalid_arg_index;
  2551. }
  2552. template <typename Char, typename ErrorHandler, typename... Args>
  2553. class format_string_checker {
  2554. private:
  2555. // In the future basic_format_parse_context will replace compile_parse_context
  2556. // here and will use is_constant_evaluated and downcasting to access the data
  2557. // needed for compile-time checks: https://godbolt.org/z/GvWzcTjh1.
  2558. using parse_context_type = compile_parse_context<Char, ErrorHandler>;
  2559. static constexpr int num_args = sizeof...(Args);
  2560. // Format specifier parsing function.
  2561. using parse_func = const Char* (*)(parse_context_type&);
  2562. parse_context_type context_;
  2563. parse_func parse_funcs_[num_args > 0 ? static_cast<size_t>(num_args) : 1];
  2564. type types_[num_args > 0 ? static_cast<size_t>(num_args) : 1];
  2565. public:
  2566. explicit FMT_CONSTEXPR format_string_checker(
  2567. basic_string_view<Char> format_str, ErrorHandler eh)
  2568. : context_(format_str, num_args, types_, eh),
  2569. parse_funcs_{&parse_format_specs<Args, parse_context_type>...},
  2570. types_{
  2571. mapped_type_constant<Args,
  2572. basic_format_context<Char*, Char>>::value...} {
  2573. }
  2574. FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
  2575. FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); }
  2576. FMT_CONSTEXPR auto on_arg_id(int id) -> int {
  2577. return context_.check_arg_id(id), id;
  2578. }
  2579. FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
  2580. #if FMT_USE_NONTYPE_TEMPLATE_ARGS
  2581. auto index = get_arg_index_by_name<Args...>(id);
  2582. if (index == invalid_arg_index) on_error("named argument is not found");
  2583. return context_.check_arg_id(index), index;
  2584. #else
  2585. (void)id;
  2586. on_error("compile-time checks for named arguments require C++20 support");
  2587. return 0;
  2588. #endif
  2589. }
  2590. FMT_CONSTEXPR void on_replacement_field(int, const Char*) {}
  2591. FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char*)
  2592. -> const Char* {
  2593. context_.advance_to(context_.begin() + (begin - &*context_.begin()));
  2594. // id >= 0 check is a workaround for gcc 10 bug (#2065).
  2595. return id >= 0 && id < num_args ? parse_funcs_[id](context_) : begin;
  2596. }
  2597. FMT_CONSTEXPR void on_error(const char* message) {
  2598. context_.on_error(message);
  2599. }
  2600. };
  2601. // Reports a compile-time error if S is not a valid format string.
  2602. template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
  2603. FMT_INLINE void check_format_string(const S&) {
  2604. #ifdef FMT_ENFORCE_COMPILE_STRING
  2605. static_assert(is_compile_string<S>::value,
  2606. "FMT_ENFORCE_COMPILE_STRING requires all format strings to use "
  2607. "FMT_STRING.");
  2608. #endif
  2609. }
  2610. template <typename... Args, typename S,
  2611. FMT_ENABLE_IF(is_compile_string<S>::value)>
  2612. void check_format_string(S format_str) {
  2613. FMT_CONSTEXPR auto s = basic_string_view<typename S::char_type>(format_str);
  2614. using checker = format_string_checker<typename S::char_type, error_handler,
  2615. remove_cvref_t<Args>...>;
  2616. FMT_CONSTEXPR bool invalid_format =
  2617. (parse_format_string<true>(s, checker(s, {})), true);
  2618. ignore_unused(invalid_format);
  2619. }
  2620. template <typename Char>
  2621. void vformat_to(
  2622. buffer<Char>& buf, basic_string_view<Char> fmt,
  2623. basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args,
  2624. locale_ref loc = {});
  2625. FMT_API void vprint_mojibake(std::FILE*, string_view, format_args);
  2626. #ifndef _WIN32
  2627. inline void vprint_mojibake(std::FILE*, string_view, format_args) {}
  2628. #endif
  2629. FMT_END_DETAIL_NAMESPACE
  2630. // A formatter specialization for the core types corresponding to detail::type
  2631. // constants.
  2632. template <typename T, typename Char>
  2633. struct formatter<T, Char,
  2634. enable_if_t<detail::type_constant<T, Char>::value !=
  2635. detail::type::custom_type>> {
  2636. private:
  2637. detail::dynamic_format_specs<Char> specs_;
  2638. public:
  2639. // Parses format specifiers stopping either at the end of the range or at the
  2640. // terminating '}'.
  2641. template <typename ParseContext>
  2642. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  2643. auto begin = ctx.begin(), end = ctx.end();
  2644. if (begin == end) return begin;
  2645. using handler_type = detail::dynamic_specs_handler<ParseContext>;
  2646. auto type = detail::type_constant<T, Char>::value;
  2647. auto checker =
  2648. detail::specs_checker<handler_type>(handler_type(specs_, ctx), type);
  2649. auto it = detail::parse_format_specs(begin, end, checker);
  2650. auto eh = ctx.error_handler();
  2651. switch (type) {
  2652. case detail::type::none_type:
  2653. FMT_ASSERT(false, "invalid argument type");
  2654. break;
  2655. case detail::type::bool_type:
  2656. if (specs_.type == presentation_type::none ||
  2657. specs_.type == presentation_type::string) {
  2658. break;
  2659. }
  2660. FMT_FALLTHROUGH;
  2661. case detail::type::int_type:
  2662. case detail::type::uint_type:
  2663. case detail::type::long_long_type:
  2664. case detail::type::ulong_long_type:
  2665. case detail::type::int128_type:
  2666. case detail::type::uint128_type:
  2667. detail::check_int_type_spec(specs_.type, eh);
  2668. break;
  2669. case detail::type::char_type:
  2670. detail::check_char_specs(specs_, eh);
  2671. break;
  2672. case detail::type::float_type:
  2673. if (detail::const_check(FMT_USE_FLOAT))
  2674. detail::parse_float_type_spec(specs_, eh);
  2675. else
  2676. FMT_ASSERT(false, "float support disabled");
  2677. break;
  2678. case detail::type::double_type:
  2679. if (detail::const_check(FMT_USE_DOUBLE))
  2680. detail::parse_float_type_spec(specs_, eh);
  2681. else
  2682. FMT_ASSERT(false, "double support disabled");
  2683. break;
  2684. case detail::type::long_double_type:
  2685. if (detail::const_check(FMT_USE_LONG_DOUBLE))
  2686. detail::parse_float_type_spec(specs_, eh);
  2687. else
  2688. FMT_ASSERT(false, "long double support disabled");
  2689. break;
  2690. case detail::type::cstring_type:
  2691. detail::check_cstring_type_spec(specs_.type, eh);
  2692. break;
  2693. case detail::type::string_type:
  2694. detail::check_string_type_spec(specs_.type, eh);
  2695. break;
  2696. case detail::type::pointer_type:
  2697. detail::check_pointer_type_spec(specs_.type, eh);
  2698. break;
  2699. case detail::type::custom_type:
  2700. // Custom format specifiers are checked in parse functions of
  2701. // formatter specializations.
  2702. break;
  2703. }
  2704. return it;
  2705. }
  2706. template <detail::type U = detail::type_constant<T, Char>::value,
  2707. enable_if_t<(U == detail::type::string_type ||
  2708. U == detail::type::cstring_type ||
  2709. U == detail::type::char_type),
  2710. int> = 0>
  2711. FMT_CONSTEXPR void set_debug_format() {
  2712. specs_.type = presentation_type::debug;
  2713. }
  2714. template <typename FormatContext>
  2715. FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const
  2716. -> decltype(ctx.out());
  2717. };
  2718. #define FMT_FORMAT_AS(Type, Base) \
  2719. template <typename Char> \
  2720. struct formatter<Type, Char> : formatter<Base, Char> { \
  2721. template <typename FormatContext> \
  2722. auto format(Type const& val, FormatContext& ctx) const \
  2723. -> decltype(ctx.out()) { \
  2724. return formatter<Base, Char>::format(static_cast<Base>(val), ctx); \
  2725. } \
  2726. }
  2727. FMT_FORMAT_AS(signed char, int);
  2728. FMT_FORMAT_AS(unsigned char, unsigned);
  2729. FMT_FORMAT_AS(short, int);
  2730. FMT_FORMAT_AS(unsigned short, unsigned);
  2731. FMT_FORMAT_AS(long, long long);
  2732. FMT_FORMAT_AS(unsigned long, unsigned long long);
  2733. FMT_FORMAT_AS(Char*, const Char*);
  2734. FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>);
  2735. FMT_FORMAT_AS(std::nullptr_t, const void*);
  2736. FMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>);
  2737. template <typename Char> struct basic_runtime { basic_string_view<Char> str; };
  2738. /** A compile-time format string. */
  2739. template <typename Char, typename... Args> class basic_format_string {
  2740. private:
  2741. basic_string_view<Char> str_;
  2742. public:
  2743. template <typename S,
  2744. FMT_ENABLE_IF(
  2745. std::is_convertible<const S&, basic_string_view<Char>>::value)>
  2746. FMT_CONSTEVAL FMT_INLINE basic_format_string(const S& s) : str_(s) {
  2747. static_assert(
  2748. detail::count<
  2749. (std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
  2750. std::is_reference<Args>::value)...>() == 0,
  2751. "passing views as lvalues is disallowed");
  2752. #ifdef FMT_HAS_CONSTEVAL
  2753. if constexpr (detail::count_named_args<Args...>() ==
  2754. detail::count_statically_named_args<Args...>()) {
  2755. using checker = detail::format_string_checker<Char, detail::error_handler,
  2756. remove_cvref_t<Args>...>;
  2757. detail::parse_format_string<true>(str_, checker(s, {}));
  2758. }
  2759. #else
  2760. detail::check_format_string<Args...>(s);
  2761. #endif
  2762. }
  2763. basic_format_string(basic_runtime<Char> r) : str_(r.str) {}
  2764. FMT_INLINE operator basic_string_view<Char>() const { return str_; }
  2765. };
  2766. #if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
  2767. // Workaround broken conversion on older gcc.
  2768. template <typename...> using format_string = string_view;
  2769. inline auto runtime(string_view s) -> string_view { return s; }
  2770. #else
  2771. template <typename... Args>
  2772. using format_string = basic_format_string<char, type_identity_t<Args>...>;
  2773. /**
  2774. \rst
  2775. Creates a runtime format string.
  2776. **Example**::
  2777. // Check format string at runtime instead of compile-time.
  2778. fmt::print(fmt::runtime("{:d}"), "I am not a number");
  2779. \endrst
  2780. */
  2781. inline auto runtime(string_view s) -> basic_runtime<char> { return {{s}}; }
  2782. #endif
  2783. FMT_API auto vformat(string_view fmt, format_args args) -> std::string;
  2784. /**
  2785. \rst
  2786. Formats ``args`` according to specifications in ``fmt`` and returns the result
  2787. as a string.
  2788. **Example**::
  2789. #include <fmt/core.h>
  2790. std::string message = fmt::format("The answer is {}.", 42);
  2791. \endrst
  2792. */
  2793. template <typename... T>
  2794. FMT_NODISCARD FMT_INLINE auto format(format_string<T...> fmt, T&&... args)
  2795. -> std::string {
  2796. return vformat(fmt, fmt::make_format_args(args...));
  2797. }
  2798. /** Formats a string and writes the output to ``out``. */
  2799. template <typename OutputIt,
  2800. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
  2801. auto vformat_to(OutputIt out, string_view fmt, format_args args) -> OutputIt {
  2802. using detail::get_buffer;
  2803. auto&& buf = get_buffer<char>(out);
  2804. detail::vformat_to(buf, fmt, args, {});
  2805. return detail::get_iterator(buf);
  2806. }
  2807. /**
  2808. \rst
  2809. Formats ``args`` according to specifications in ``fmt``, writes the result to
  2810. the output iterator ``out`` and returns the iterator past the end of the output
  2811. range. `format_to` does not append a terminating null character.
  2812. **Example**::
  2813. auto out = std::vector<char>();
  2814. fmt::format_to(std::back_inserter(out), "{}", 42);
  2815. \endrst
  2816. */
  2817. template <typename OutputIt, typename... T,
  2818. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
  2819. FMT_INLINE auto format_to(OutputIt out, format_string<T...> fmt, T&&... args)
  2820. -> OutputIt {
  2821. return vformat_to(out, fmt, fmt::make_format_args(args...));
  2822. }
  2823. template <typename OutputIt> struct format_to_n_result {
  2824. /** Iterator past the end of the output range. */
  2825. OutputIt out;
  2826. /** Total (not truncated) output size. */
  2827. size_t size;
  2828. };
  2829. template <typename OutputIt, typename... T,
  2830. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
  2831. auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args)
  2832. -> format_to_n_result<OutputIt> {
  2833. using traits = detail::fixed_buffer_traits;
  2834. auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);
  2835. detail::vformat_to(buf, fmt, args, {});
  2836. return {buf.out(), buf.count()};
  2837. }
  2838. /**
  2839. \rst
  2840. Formats ``args`` according to specifications in ``fmt``, writes up to ``n``
  2841. characters of the result to the output iterator ``out`` and returns the total
  2842. (not truncated) output size and the iterator past the end of the output range.
  2843. `format_to_n` does not append a terminating null character.
  2844. \endrst
  2845. */
  2846. template <typename OutputIt, typename... T,
  2847. FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
  2848. FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string<T...> fmt,
  2849. T&&... args) -> format_to_n_result<OutputIt> {
  2850. return vformat_to_n(out, n, fmt, fmt::make_format_args(args...));
  2851. }
  2852. /** Returns the number of chars in the output of ``format(fmt, args...)``. */
  2853. template <typename... T>
  2854. FMT_NODISCARD FMT_INLINE auto formatted_size(format_string<T...> fmt,
  2855. T&&... args) -> size_t {
  2856. auto buf = detail::counting_buffer<>();
  2857. detail::vformat_to(buf, string_view(fmt), fmt::make_format_args(args...), {});
  2858. return buf.count();
  2859. }
  2860. FMT_API void vprint(string_view fmt, format_args args);
  2861. FMT_API void vprint(std::FILE* f, string_view fmt, format_args args);
  2862. /**
  2863. \rst
  2864. Formats ``args`` according to specifications in ``fmt`` and writes the output
  2865. to ``stdout``.
  2866. **Example**::
  2867. fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
  2868. \endrst
  2869. */
  2870. template <typename... T>
  2871. FMT_INLINE void print(format_string<T...> fmt, T&&... args) {
  2872. const auto& vargs = fmt::make_format_args(args...);
  2873. return detail::is_utf8() ? vprint(fmt, vargs)
  2874. : detail::vprint_mojibake(stdout, fmt, vargs);
  2875. }
  2876. /**
  2877. \rst
  2878. Formats ``args`` according to specifications in ``fmt`` and writes the
  2879. output to the file ``f``.
  2880. **Example**::
  2881. fmt::print(stderr, "Don't {}!", "panic");
  2882. \endrst
  2883. */
  2884. template <typename... T>
  2885. FMT_INLINE void print(std::FILE* f, format_string<T...> fmt, T&&... args) {
  2886. const auto& vargs = fmt::make_format_args(args...);
  2887. return detail::is_utf8() ? vprint(f, fmt, vargs)
  2888. : detail::vprint_mojibake(f, fmt, vargs);
  2889. }
  2890. FMT_MODULE_EXPORT_END
  2891. FMT_GCC_PRAGMA("GCC pop_options")
  2892. FMT_END_NAMESPACE
  2893. #ifdef FMT_HEADER_ONLY
  2894. # include "format.h"
  2895. #endif
  2896. #endif // FMT_CORE_H_