std.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. // Formatting library for C++ - formatters for standard library types
  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_STD_H_
  8. #define FMT_STD_H_
  9. #include <atomic>
  10. #include <bitset>
  11. #include <cstdlib>
  12. #include <exception>
  13. #include <memory>
  14. #include <thread>
  15. #include <type_traits>
  16. #include <typeinfo>
  17. #include <utility>
  18. #include <vector>
  19. #include "format.h"
  20. #include "ostream.h"
  21. #if FMT_HAS_INCLUDE(<version>)
  22. # include <version>
  23. #endif
  24. // Checking FMT_CPLUSPLUS for warning suppression in MSVC.
  25. #if FMT_CPLUSPLUS >= 201703L
  26. # if FMT_HAS_INCLUDE(<filesystem>)
  27. # include <filesystem>
  28. # endif
  29. # if FMT_HAS_INCLUDE(<variant>)
  30. # include <variant>
  31. # endif
  32. # if FMT_HAS_INCLUDE(<optional>)
  33. # include <optional>
  34. # endif
  35. #endif
  36. #if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE(<source_location>)
  37. # include <source_location>
  38. #endif
  39. // GCC 4 does not support FMT_HAS_INCLUDE.
  40. #if FMT_HAS_INCLUDE(<cxxabi.h>) || defined(__GLIBCXX__)
  41. # include <cxxabi.h>
  42. // Android NDK with gabi++ library on some architectures does not implement
  43. // abi::__cxa_demangle().
  44. # ifndef __GABIXX_CXXABI_H__
  45. # define FMT_HAS_ABI_CXA_DEMANGLE
  46. # endif
  47. #endif
  48. // Check if typeid is available.
  49. #ifndef FMT_USE_TYPEID
  50. // __RTTI is for EDG compilers. In MSVC typeid is available without RTTI.
  51. # if defined(__GXX_RTTI) || FMT_HAS_FEATURE(cxx_rtti) || FMT_MSC_VERSION || \
  52. defined(__INTEL_RTTI__) || defined(__RTTI)
  53. # define FMT_USE_TYPEID 1
  54. # else
  55. # define FMT_USE_TYPEID 0
  56. # endif
  57. #endif
  58. // For older Xcode versions, __cpp_lib_xxx flags are inaccurately defined.
  59. #ifndef FMT_CPP_LIB_FILESYSTEM
  60. # ifdef __cpp_lib_filesystem
  61. # define FMT_CPP_LIB_FILESYSTEM __cpp_lib_filesystem
  62. # else
  63. # define FMT_CPP_LIB_FILESYSTEM 0
  64. # endif
  65. #endif
  66. #ifndef FMT_CPP_LIB_VARIANT
  67. # ifdef __cpp_lib_variant
  68. # define FMT_CPP_LIB_VARIANT __cpp_lib_variant
  69. # else
  70. # define FMT_CPP_LIB_VARIANT 0
  71. # endif
  72. #endif
  73. #if FMT_CPP_LIB_FILESYSTEM
  74. FMT_BEGIN_NAMESPACE
  75. namespace detail {
  76. template <typename Char, typename PathChar>
  77. auto get_path_string(const std::filesystem::path& p,
  78. const std::basic_string<PathChar>& native) {
  79. if constexpr (std::is_same_v<Char, char> && std::is_same_v<PathChar, wchar_t>)
  80. return to_utf8<wchar_t>(native, to_utf8_error_policy::replace);
  81. else
  82. return p.string<Char>();
  83. }
  84. template <typename Char, typename PathChar>
  85. void write_escaped_path(basic_memory_buffer<Char>& quoted,
  86. const std::filesystem::path& p,
  87. const std::basic_string<PathChar>& native) {
  88. if constexpr (std::is_same_v<Char, char> &&
  89. std::is_same_v<PathChar, wchar_t>) {
  90. auto buf = basic_memory_buffer<wchar_t>();
  91. write_escaped_string<wchar_t>(std::back_inserter(buf), native);
  92. bool valid = to_utf8<wchar_t>::convert(quoted, {buf.data(), buf.size()});
  93. FMT_ASSERT(valid, "invalid utf16");
  94. } else if constexpr (std::is_same_v<Char, PathChar>) {
  95. write_escaped_string<std::filesystem::path::value_type>(
  96. std::back_inserter(quoted), native);
  97. } else {
  98. write_escaped_string<Char>(std::back_inserter(quoted), p.string<Char>());
  99. }
  100. }
  101. } // namespace detail
  102. FMT_EXPORT
  103. template <typename Char> struct formatter<std::filesystem::path, Char> {
  104. private:
  105. format_specs<Char> specs_;
  106. detail::arg_ref<Char> width_ref_;
  107. bool debug_ = false;
  108. char path_type_ = 0;
  109. public:
  110. FMT_CONSTEXPR void set_debug_format(bool set = true) { debug_ = set; }
  111. template <typename ParseContext> FMT_CONSTEXPR auto parse(ParseContext& ctx) {
  112. auto it = ctx.begin(), end = ctx.end();
  113. if (it == end) return it;
  114. it = detail::parse_align(it, end, specs_);
  115. if (it == end) return it;
  116. it = detail::parse_dynamic_spec(it, end, specs_.width, width_ref_, ctx);
  117. if (it != end && *it == '?') {
  118. debug_ = true;
  119. ++it;
  120. }
  121. if (it != end && (*it == 'g')) path_type_ = *it++;
  122. return it;
  123. }
  124. template <typename FormatContext>
  125. auto format(const std::filesystem::path& p, FormatContext& ctx) const {
  126. auto specs = specs_;
  127. # ifdef _WIN32
  128. auto path_string = !path_type_ ? p.native() : p.generic_wstring();
  129. # else
  130. auto path_string = !path_type_ ? p.native() : p.generic_string();
  131. # endif
  132. detail::handle_dynamic_spec<detail::width_checker>(specs.width, width_ref_,
  133. ctx);
  134. if (!debug_) {
  135. auto s = detail::get_path_string<Char>(p, path_string);
  136. return detail::write(ctx.out(), basic_string_view<Char>(s), specs);
  137. }
  138. auto quoted = basic_memory_buffer<Char>();
  139. detail::write_escaped_path(quoted, p, path_string);
  140. return detail::write(ctx.out(),
  141. basic_string_view<Char>(quoted.data(), quoted.size()),
  142. specs);
  143. }
  144. };
  145. FMT_END_NAMESPACE
  146. #endif // FMT_CPP_LIB_FILESYSTEM
  147. FMT_BEGIN_NAMESPACE
  148. FMT_EXPORT
  149. template <std::size_t N, typename Char>
  150. struct formatter<std::bitset<N>, Char> : nested_formatter<string_view> {
  151. private:
  152. // Functor because C++11 doesn't support generic lambdas.
  153. struct writer {
  154. const std::bitset<N>& bs;
  155. template <typename OutputIt>
  156. FMT_CONSTEXPR auto operator()(OutputIt out) -> OutputIt {
  157. for (auto pos = N; pos > 0; --pos) {
  158. out = detail::write<Char>(out, bs[pos - 1] ? Char('1') : Char('0'));
  159. }
  160. return out;
  161. }
  162. };
  163. public:
  164. template <typename FormatContext>
  165. auto format(const std::bitset<N>& bs, FormatContext& ctx) const
  166. -> decltype(ctx.out()) {
  167. return write_padded(ctx, writer{bs});
  168. }
  169. };
  170. FMT_EXPORT
  171. template <typename Char>
  172. struct formatter<std::thread::id, Char> : basic_ostream_formatter<Char> {};
  173. FMT_END_NAMESPACE
  174. #ifdef __cpp_lib_optional
  175. FMT_BEGIN_NAMESPACE
  176. FMT_EXPORT
  177. template <typename T, typename Char>
  178. struct formatter<std::optional<T>, Char,
  179. std::enable_if_t<is_formattable<T, Char>::value>> {
  180. private:
  181. formatter<T, Char> underlying_;
  182. static constexpr basic_string_view<Char> optional =
  183. detail::string_literal<Char, 'o', 'p', 't', 'i', 'o', 'n', 'a', 'l',
  184. '('>{};
  185. static constexpr basic_string_view<Char> none =
  186. detail::string_literal<Char, 'n', 'o', 'n', 'e'>{};
  187. template <class U>
  188. FMT_CONSTEXPR static auto maybe_set_debug_format(U& u, bool set)
  189. -> decltype(u.set_debug_format(set)) {
  190. u.set_debug_format(set);
  191. }
  192. template <class U>
  193. FMT_CONSTEXPR static void maybe_set_debug_format(U&, ...) {}
  194. public:
  195. template <typename ParseContext> FMT_CONSTEXPR auto parse(ParseContext& ctx) {
  196. maybe_set_debug_format(underlying_, true);
  197. return underlying_.parse(ctx);
  198. }
  199. template <typename FormatContext>
  200. auto format(const std::optional<T>& opt, FormatContext& ctx) const
  201. -> decltype(ctx.out()) {
  202. if (!opt) return detail::write<Char>(ctx.out(), none);
  203. auto out = ctx.out();
  204. out = detail::write<Char>(out, optional);
  205. ctx.advance_to(out);
  206. out = underlying_.format(*opt, ctx);
  207. return detail::write(out, ')');
  208. }
  209. };
  210. FMT_END_NAMESPACE
  211. #endif // __cpp_lib_optional
  212. #ifdef __cpp_lib_source_location
  213. FMT_BEGIN_NAMESPACE
  214. FMT_EXPORT
  215. template <> struct formatter<std::source_location> {
  216. template <typename ParseContext> FMT_CONSTEXPR auto parse(ParseContext& ctx) {
  217. return ctx.begin();
  218. }
  219. template <typename FormatContext>
  220. auto format(const std::source_location& loc, FormatContext& ctx) const
  221. -> decltype(ctx.out()) {
  222. auto out = ctx.out();
  223. out = detail::write(out, loc.file_name());
  224. out = detail::write(out, ':');
  225. out = detail::write<char>(out, loc.line());
  226. out = detail::write(out, ':');
  227. out = detail::write<char>(out, loc.column());
  228. out = detail::write(out, ": ");
  229. out = detail::write(out, loc.function_name());
  230. return out;
  231. }
  232. };
  233. FMT_END_NAMESPACE
  234. #endif
  235. #if FMT_CPP_LIB_VARIANT
  236. FMT_BEGIN_NAMESPACE
  237. namespace detail {
  238. template <typename T>
  239. using variant_index_sequence =
  240. std::make_index_sequence<std::variant_size<T>::value>;
  241. template <typename> struct is_variant_like_ : std::false_type {};
  242. template <typename... Types>
  243. struct is_variant_like_<std::variant<Types...>> : std::true_type {};
  244. // formattable element check.
  245. template <typename T, typename C> class is_variant_formattable_ {
  246. template <std::size_t... Is>
  247. static std::conjunction<
  248. is_formattable<std::variant_alternative_t<Is, T>, C>...>
  249. check(std::index_sequence<Is...>);
  250. public:
  251. static constexpr const bool value =
  252. decltype(check(variant_index_sequence<T>{}))::value;
  253. };
  254. template <typename Char, typename OutputIt, typename T>
  255. auto write_variant_alternative(OutputIt out, const T& v) -> OutputIt {
  256. if constexpr (is_string<T>::value)
  257. return write_escaped_string<Char>(out, detail::to_string_view(v));
  258. else if constexpr (std::is_same_v<T, Char>)
  259. return write_escaped_char(out, v);
  260. else
  261. return write<Char>(out, v);
  262. }
  263. } // namespace detail
  264. template <typename T> struct is_variant_like {
  265. static constexpr const bool value = detail::is_variant_like_<T>::value;
  266. };
  267. template <typename T, typename C> struct is_variant_formattable {
  268. static constexpr const bool value =
  269. detail::is_variant_formattable_<T, C>::value;
  270. };
  271. FMT_EXPORT
  272. template <typename Char> struct formatter<std::monostate, Char> {
  273. template <typename ParseContext>
  274. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  275. return ctx.begin();
  276. }
  277. template <typename FormatContext>
  278. auto format(const std::monostate&, FormatContext& ctx) const
  279. -> decltype(ctx.out()) {
  280. return detail::write<Char>(ctx.out(), "monostate");
  281. }
  282. };
  283. FMT_EXPORT
  284. template <typename Variant, typename Char>
  285. struct formatter<
  286. Variant, Char,
  287. std::enable_if_t<std::conjunction_v<
  288. is_variant_like<Variant>, is_variant_formattable<Variant, Char>>>> {
  289. template <typename ParseContext>
  290. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  291. return ctx.begin();
  292. }
  293. template <typename FormatContext>
  294. auto format(const Variant& value, FormatContext& ctx) const
  295. -> decltype(ctx.out()) {
  296. auto out = ctx.out();
  297. out = detail::write<Char>(out, "variant(");
  298. FMT_TRY {
  299. std::visit(
  300. [&](const auto& v) {
  301. out = detail::write_variant_alternative<Char>(out, v);
  302. },
  303. value);
  304. }
  305. FMT_CATCH(const std::bad_variant_access&) {
  306. detail::write<Char>(out, "valueless by exception");
  307. }
  308. *out++ = ')';
  309. return out;
  310. }
  311. };
  312. FMT_END_NAMESPACE
  313. #endif // FMT_CPP_LIB_VARIANT
  314. FMT_BEGIN_NAMESPACE
  315. FMT_EXPORT
  316. template <typename Char> struct formatter<std::error_code, Char> {
  317. template <typename ParseContext>
  318. FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
  319. return ctx.begin();
  320. }
  321. template <typename FormatContext>
  322. FMT_CONSTEXPR auto format(const std::error_code& ec, FormatContext& ctx) const
  323. -> decltype(ctx.out()) {
  324. auto out = ctx.out();
  325. out = detail::write_bytes(out, ec.category().name(), format_specs<Char>());
  326. out = detail::write<Char>(out, Char(':'));
  327. out = detail::write<Char>(out, ec.value());
  328. return out;
  329. }
  330. };
  331. FMT_EXPORT
  332. template <typename T, typename Char>
  333. struct formatter<
  334. T, Char, // DEPRECATED! Mixing code unit types.
  335. typename std::enable_if<std::is_base_of<std::exception, T>::value>::type> {
  336. private:
  337. bool with_typename_ = false;
  338. public:
  339. FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
  340. -> decltype(ctx.begin()) {
  341. auto it = ctx.begin();
  342. auto end = ctx.end();
  343. if (it == end || *it == '}') return it;
  344. if (*it == 't') {
  345. ++it;
  346. with_typename_ = FMT_USE_TYPEID != 0;
  347. }
  348. return it;
  349. }
  350. template <typename OutputIt>
  351. auto format(const std::exception& ex,
  352. basic_format_context<OutputIt, Char>& ctx) const -> OutputIt {
  353. format_specs<Char> spec;
  354. auto out = ctx.out();
  355. if (!with_typename_)
  356. return detail::write_bytes(out, string_view(ex.what()), spec);
  357. #if FMT_USE_TYPEID
  358. const std::type_info& ti = typeid(ex);
  359. # ifdef FMT_HAS_ABI_CXA_DEMANGLE
  360. int status = 0;
  361. std::size_t size = 0;
  362. std::unique_ptr<char, void (*)(void*)> demangled_name_ptr(
  363. abi::__cxa_demangle(ti.name(), nullptr, &size, &status), &std::free);
  364. string_view demangled_name_view;
  365. if (demangled_name_ptr) {
  366. demangled_name_view = demangled_name_ptr.get();
  367. // Normalization of stdlib inline namespace names.
  368. // libc++ inline namespaces.
  369. // std::__1::* -> std::*
  370. // std::__1::__fs::* -> std::*
  371. // libstdc++ inline namespaces.
  372. // std::__cxx11::* -> std::*
  373. // std::filesystem::__cxx11::* -> std::filesystem::*
  374. if (demangled_name_view.starts_with("std::")) {
  375. char* begin = demangled_name_ptr.get();
  376. char* to = begin + 5; // std::
  377. for (char *from = to, *end = begin + demangled_name_view.size();
  378. from < end;) {
  379. // This is safe, because demangled_name is NUL-terminated.
  380. if (from[0] == '_' && from[1] == '_') {
  381. char* next = from + 1;
  382. while (next < end && *next != ':') next++;
  383. if (next[0] == ':' && next[1] == ':') {
  384. from = next + 2;
  385. continue;
  386. }
  387. }
  388. *to++ = *from++;
  389. }
  390. demangled_name_view = {begin, detail::to_unsigned(to - begin)};
  391. }
  392. } else {
  393. demangled_name_view = string_view(ti.name());
  394. }
  395. out = detail::write_bytes(out, demangled_name_view, spec);
  396. # elif FMT_MSC_VERSION
  397. string_view demangled_name_view(ti.name());
  398. if (demangled_name_view.starts_with("class "))
  399. demangled_name_view.remove_prefix(6);
  400. else if (demangled_name_view.starts_with("struct "))
  401. demangled_name_view.remove_prefix(7);
  402. out = detail::write_bytes(out, demangled_name_view, spec);
  403. # else
  404. out = detail::write_bytes(out, string_view(ti.name()), spec);
  405. # endif
  406. *out++ = ':';
  407. *out++ = ' ';
  408. return detail::write_bytes(out, string_view(ex.what()), spec);
  409. #endif
  410. }
  411. };
  412. namespace detail {
  413. template <typename T, typename Enable = void>
  414. struct has_flip : std::false_type {};
  415. template <typename T>
  416. struct has_flip<T, void_t<decltype(std::declval<T>().flip())>>
  417. : std::true_type {};
  418. template <typename T> struct is_bit_reference_like {
  419. static constexpr const bool value =
  420. std::is_convertible<T, bool>::value &&
  421. std::is_nothrow_assignable<T, bool>::value && has_flip<T>::value;
  422. };
  423. #ifdef _LIBCPP_VERSION
  424. // Workaround for libc++ incompatibility with C++ standard.
  425. // According to the Standard, `bitset::operator[] const` returns bool.
  426. template <typename C>
  427. struct is_bit_reference_like<std::__bit_const_reference<C>> {
  428. static constexpr const bool value = true;
  429. };
  430. #endif
  431. } // namespace detail
  432. // We can't use std::vector<bool, Allocator>::reference and
  433. // std::bitset<N>::reference because the compiler can't deduce Allocator and N
  434. // in partial specialization.
  435. FMT_EXPORT
  436. template <typename BitRef, typename Char>
  437. struct formatter<BitRef, Char,
  438. enable_if_t<detail::is_bit_reference_like<BitRef>::value>>
  439. : formatter<bool, Char> {
  440. template <typename FormatContext>
  441. FMT_CONSTEXPR auto format(const BitRef& v, FormatContext& ctx) const
  442. -> decltype(ctx.out()) {
  443. return formatter<bool, Char>::format(v, ctx);
  444. }
  445. };
  446. FMT_EXPORT
  447. template <typename T, typename Char>
  448. struct formatter<std::atomic<T>, Char,
  449. enable_if_t<is_formattable<T, Char>::value>>
  450. : formatter<T, Char> {
  451. template <typename FormatContext>
  452. auto format(const std::atomic<T>& v, FormatContext& ctx) const
  453. -> decltype(ctx.out()) {
  454. return formatter<T, Char>::format(v.load(), ctx);
  455. }
  456. };
  457. #ifdef __cpp_lib_atomic_flag_test
  458. FMT_EXPORT
  459. template <typename Char>
  460. struct formatter<std::atomic_flag, Char> : formatter<bool, Char> {
  461. template <typename FormatContext>
  462. auto format(const std::atomic_flag& v, FormatContext& ctx) const
  463. -> decltype(ctx.out()) {
  464. return formatter<bool, Char>::format(v.test(), ctx);
  465. }
  466. };
  467. #endif // __cpp_lib_atomic_flag_test
  468. FMT_END_NAMESPACE
  469. #endif // FMT_STD_H_