compile.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. // Formatting library for C++ - experimental format string compilation
  2. //
  3. // Copyright (c) 2012 - present, Victor Zverovich and fmt contributors
  4. // All rights reserved.
  5. //
  6. // For the license information refer to format.h.
  7. #ifndef FMT_COMPILE_H_
  8. #define FMT_COMPILE_H_
  9. #ifndef FMT_MODULE
  10. # include <iterator> // std::back_inserter
  11. #endif
  12. #include "format.h"
  13. FMT_BEGIN_NAMESPACE
  14. // A compile-time string which is compiled into fast formatting code.
  15. FMT_EXPORT class compiled_string {};
  16. namespace detail {
  17. template <typename T, typename InputIt>
  18. FMT_CONSTEXPR inline auto copy(InputIt begin, InputIt end, counting_iterator it)
  19. -> counting_iterator {
  20. return it + (end - begin);
  21. }
  22. template <typename S>
  23. struct is_compiled_string : std::is_base_of<compiled_string, S> {};
  24. /**
  25. * Converts a string literal `s` into a format string that will be parsed at
  26. * compile time and converted into efficient formatting code. Requires C++17
  27. * `constexpr if` compiler support.
  28. *
  29. * **Example**:
  30. *
  31. * // Converts 42 into std::string using the most efficient method and no
  32. * // runtime format string processing.
  33. * std::string s = fmt::format(FMT_COMPILE("{}"), 42);
  34. */
  35. #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
  36. # define FMT_COMPILE(s) FMT_STRING_IMPL(s, fmt::compiled_string, explicit)
  37. #else
  38. # define FMT_COMPILE(s) FMT_STRING(s)
  39. #endif
  40. #if FMT_USE_NONTYPE_TEMPLATE_ARGS
  41. template <typename Char, size_t N,
  42. fmt::detail_exported::fixed_string<Char, N> Str>
  43. struct udl_compiled_string : compiled_string {
  44. using char_type = Char;
  45. explicit constexpr operator basic_string_view<char_type>() const {
  46. return {Str.data, N - 1};
  47. }
  48. };
  49. #endif
  50. template <typename T, typename... Tail>
  51. auto first(const T& value, const Tail&...) -> const T& {
  52. return value;
  53. }
  54. #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
  55. template <typename... Args> struct type_list {};
  56. // Returns a reference to the argument at index N from [first, rest...].
  57. template <int N, typename T, typename... Args>
  58. constexpr const auto& get([[maybe_unused]] const T& first,
  59. [[maybe_unused]] const Args&... rest) {
  60. static_assert(N < 1 + sizeof...(Args), "index is out of bounds");
  61. if constexpr (N == 0)
  62. return first;
  63. else
  64. return detail::get<N - 1>(rest...);
  65. }
  66. template <typename Char, typename... Args>
  67. constexpr int get_arg_index_by_name(basic_string_view<Char> name,
  68. type_list<Args...>) {
  69. return get_arg_index_by_name<Args...>(name);
  70. }
  71. template <int N, typename> struct get_type_impl;
  72. template <int N, typename... Args> struct get_type_impl<N, type_list<Args...>> {
  73. using type =
  74. remove_cvref_t<decltype(detail::get<N>(std::declval<Args>()...))>;
  75. };
  76. template <int N, typename T>
  77. using get_type = typename get_type_impl<N, T>::type;
  78. template <typename T> struct is_compiled_format : std::false_type {};
  79. template <typename Char> struct text {
  80. basic_string_view<Char> data;
  81. using char_type = Char;
  82. template <typename OutputIt, typename... Args>
  83. constexpr OutputIt format(OutputIt out, const Args&...) const {
  84. return write<Char>(out, data);
  85. }
  86. };
  87. template <typename Char>
  88. struct is_compiled_format<text<Char>> : std::true_type {};
  89. template <typename Char>
  90. constexpr text<Char> make_text(basic_string_view<Char> s, size_t pos,
  91. size_t size) {
  92. return {{&s[pos], size}};
  93. }
  94. template <typename Char> struct code_unit {
  95. Char value;
  96. using char_type = Char;
  97. template <typename OutputIt, typename... Args>
  98. constexpr OutputIt format(OutputIt out, const Args&...) const {
  99. *out++ = value;
  100. return out;
  101. }
  102. };
  103. // This ensures that the argument type is convertible to `const T&`.
  104. template <typename T, int N, typename... Args>
  105. constexpr const T& get_arg_checked(const Args&... args) {
  106. const auto& arg = detail::get<N>(args...);
  107. if constexpr (detail::is_named_arg<remove_cvref_t<decltype(arg)>>()) {
  108. return arg.value;
  109. } else {
  110. return arg;
  111. }
  112. }
  113. template <typename Char>
  114. struct is_compiled_format<code_unit<Char>> : std::true_type {};
  115. // A replacement field that refers to argument N.
  116. template <typename Char, typename T, int N> struct field {
  117. using char_type = Char;
  118. template <typename OutputIt, typename... Args>
  119. constexpr OutputIt format(OutputIt out, const Args&... args) const {
  120. const T& arg = get_arg_checked<T, N>(args...);
  121. if constexpr (std::is_convertible<T, basic_string_view<Char>>::value) {
  122. auto s = basic_string_view<Char>(arg);
  123. return copy<Char>(s.begin(), s.end(), out);
  124. }
  125. return write<Char>(out, arg);
  126. }
  127. };
  128. template <typename Char, typename T, int N>
  129. struct is_compiled_format<field<Char, T, N>> : std::true_type {};
  130. // A replacement field that refers to argument with name.
  131. template <typename Char> struct runtime_named_field {
  132. using char_type = Char;
  133. basic_string_view<Char> name;
  134. template <typename OutputIt, typename T>
  135. constexpr static bool try_format_argument(
  136. OutputIt& out,
  137. // [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9
  138. [[maybe_unused]] basic_string_view<Char> arg_name, const T& arg) {
  139. if constexpr (is_named_arg<typename std::remove_cv<T>::type>::value) {
  140. if (arg_name == arg.name) {
  141. out = write<Char>(out, arg.value);
  142. return true;
  143. }
  144. }
  145. return false;
  146. }
  147. template <typename OutputIt, typename... Args>
  148. constexpr OutputIt format(OutputIt out, const Args&... args) const {
  149. bool found = (try_format_argument(out, name, args) || ...);
  150. if (!found) {
  151. FMT_THROW(format_error("argument with specified name is not found"));
  152. }
  153. return out;
  154. }
  155. };
  156. template <typename Char>
  157. struct is_compiled_format<runtime_named_field<Char>> : std::true_type {};
  158. // A replacement field that refers to argument N and has format specifiers.
  159. template <typename Char, typename T, int N> struct spec_field {
  160. using char_type = Char;
  161. formatter<T, Char> fmt;
  162. template <typename OutputIt, typename... Args>
  163. constexpr FMT_INLINE OutputIt format(OutputIt out,
  164. const Args&... args) const {
  165. const auto& vargs =
  166. fmt::make_format_args<basic_format_context<OutputIt, Char>>(args...);
  167. basic_format_context<OutputIt, Char> ctx(out, vargs);
  168. return fmt.format(get_arg_checked<T, N>(args...), ctx);
  169. }
  170. };
  171. template <typename Char, typename T, int N>
  172. struct is_compiled_format<spec_field<Char, T, N>> : std::true_type {};
  173. template <typename L, typename R> struct concat {
  174. L lhs;
  175. R rhs;
  176. using char_type = typename L::char_type;
  177. template <typename OutputIt, typename... Args>
  178. constexpr OutputIt format(OutputIt out, const Args&... args) const {
  179. out = lhs.format(out, args...);
  180. return rhs.format(out, args...);
  181. }
  182. };
  183. template <typename L, typename R>
  184. struct is_compiled_format<concat<L, R>> : std::true_type {};
  185. template <typename L, typename R>
  186. constexpr concat<L, R> make_concat(L lhs, R rhs) {
  187. return {lhs, rhs};
  188. }
  189. struct unknown_format {};
  190. template <typename Char>
  191. constexpr size_t parse_text(basic_string_view<Char> str, size_t pos) {
  192. for (size_t size = str.size(); pos != size; ++pos) {
  193. if (str[pos] == '{' || str[pos] == '}') break;
  194. }
  195. return pos;
  196. }
  197. template <typename Args, size_t POS, int ID, typename S>
  198. constexpr auto compile_format_string(S fmt);
  199. template <typename Args, size_t POS, int ID, typename T, typename S>
  200. constexpr auto parse_tail(T head, S fmt) {
  201. if constexpr (POS != basic_string_view<typename S::char_type>(fmt).size()) {
  202. constexpr auto tail = compile_format_string<Args, POS, ID>(fmt);
  203. if constexpr (std::is_same<remove_cvref_t<decltype(tail)>,
  204. unknown_format>())
  205. return tail;
  206. else
  207. return make_concat(head, tail);
  208. } else {
  209. return head;
  210. }
  211. }
  212. template <typename T, typename Char> struct parse_specs_result {
  213. formatter<T, Char> fmt;
  214. size_t end;
  215. int next_arg_id;
  216. };
  217. enum { manual_indexing_id = -1 };
  218. template <typename T, typename Char>
  219. constexpr parse_specs_result<T, Char> parse_specs(basic_string_view<Char> str,
  220. size_t pos, int next_arg_id) {
  221. str.remove_prefix(pos);
  222. auto ctx =
  223. compile_parse_context<Char>(str, max_value<int>(), nullptr, next_arg_id);
  224. auto f = formatter<T, Char>();
  225. auto end = f.parse(ctx);
  226. return {f, pos + fmt::detail::to_unsigned(end - str.data()),
  227. next_arg_id == 0 ? manual_indexing_id : ctx.next_arg_id()};
  228. }
  229. template <typename Char> struct arg_id_handler {
  230. arg_ref<Char> arg_id;
  231. constexpr int on_auto() {
  232. FMT_ASSERT(false, "handler cannot be used with automatic indexing");
  233. return 0;
  234. }
  235. constexpr int on_index(int id) {
  236. arg_id = arg_ref<Char>(id);
  237. return 0;
  238. }
  239. constexpr int on_name(basic_string_view<Char> id) {
  240. arg_id = arg_ref<Char>(id);
  241. return 0;
  242. }
  243. };
  244. template <typename Char> struct parse_arg_id_result {
  245. arg_ref<Char> arg_id;
  246. const Char* arg_id_end;
  247. };
  248. template <int ID, typename Char>
  249. constexpr auto parse_arg_id(const Char* begin, const Char* end) {
  250. auto handler = arg_id_handler<Char>{arg_ref<Char>{}};
  251. auto arg_id_end = parse_arg_id(begin, end, handler);
  252. return parse_arg_id_result<Char>{handler.arg_id, arg_id_end};
  253. }
  254. template <typename T, typename Enable = void> struct field_type {
  255. using type = remove_cvref_t<T>;
  256. };
  257. template <typename T>
  258. struct field_type<T, enable_if_t<detail::is_named_arg<T>::value>> {
  259. using type = remove_cvref_t<decltype(T::value)>;
  260. };
  261. template <typename T, typename Args, size_t END_POS, int ARG_INDEX, int NEXT_ID,
  262. typename S>
  263. constexpr auto parse_replacement_field_then_tail(S fmt) {
  264. using char_type = typename S::char_type;
  265. constexpr auto str = basic_string_view<char_type>(fmt);
  266. constexpr char_type c = END_POS != str.size() ? str[END_POS] : char_type();
  267. if constexpr (c == '}') {
  268. return parse_tail<Args, END_POS + 1, NEXT_ID>(
  269. field<char_type, typename field_type<T>::type, ARG_INDEX>(), fmt);
  270. } else if constexpr (c != ':') {
  271. FMT_THROW(format_error("expected ':'"));
  272. } else {
  273. constexpr auto result = parse_specs<typename field_type<T>::type>(
  274. str, END_POS + 1, NEXT_ID == manual_indexing_id ? 0 : NEXT_ID);
  275. if constexpr (result.end >= str.size() || str[result.end] != '}') {
  276. FMT_THROW(format_error("expected '}'"));
  277. return 0;
  278. } else {
  279. return parse_tail<Args, result.end + 1, result.next_arg_id>(
  280. spec_field<char_type, typename field_type<T>::type, ARG_INDEX>{
  281. result.fmt},
  282. fmt);
  283. }
  284. }
  285. }
  286. // Compiles a non-empty format string and returns the compiled representation
  287. // or unknown_format() on unrecognized input.
  288. template <typename Args, size_t POS, int ID, typename S>
  289. constexpr auto compile_format_string(S fmt) {
  290. using char_type = typename S::char_type;
  291. constexpr auto str = basic_string_view<char_type>(fmt);
  292. if constexpr (str[POS] == '{') {
  293. if constexpr (POS + 1 == str.size())
  294. FMT_THROW(format_error("unmatched '{' in format string"));
  295. if constexpr (str[POS + 1] == '{') {
  296. return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), fmt);
  297. } else if constexpr (str[POS + 1] == '}' || str[POS + 1] == ':') {
  298. static_assert(ID != manual_indexing_id,
  299. "cannot switch from manual to automatic argument indexing");
  300. constexpr auto next_id =
  301. ID != manual_indexing_id ? ID + 1 : manual_indexing_id;
  302. return parse_replacement_field_then_tail<get_type<ID, Args>, Args,
  303. POS + 1, ID, next_id>(fmt);
  304. } else {
  305. constexpr auto arg_id_result =
  306. parse_arg_id<ID>(str.data() + POS + 1, str.data() + str.size());
  307. constexpr auto arg_id_end_pos = arg_id_result.arg_id_end - str.data();
  308. constexpr char_type c =
  309. arg_id_end_pos != str.size() ? str[arg_id_end_pos] : char_type();
  310. static_assert(c == '}' || c == ':', "missing '}' in format string");
  311. if constexpr (arg_id_result.arg_id.kind == arg_id_kind::index) {
  312. static_assert(
  313. ID == manual_indexing_id || ID == 0,
  314. "cannot switch from automatic to manual argument indexing");
  315. constexpr auto arg_index = arg_id_result.arg_id.val.index;
  316. return parse_replacement_field_then_tail<get_type<arg_index, Args>,
  317. Args, arg_id_end_pos,
  318. arg_index, manual_indexing_id>(
  319. fmt);
  320. } else if constexpr (arg_id_result.arg_id.kind == arg_id_kind::name) {
  321. constexpr auto arg_index =
  322. get_arg_index_by_name(arg_id_result.arg_id.val.name, Args{});
  323. if constexpr (arg_index >= 0) {
  324. constexpr auto next_id =
  325. ID != manual_indexing_id ? ID + 1 : manual_indexing_id;
  326. return parse_replacement_field_then_tail<
  327. decltype(get_type<arg_index, Args>::value), Args, arg_id_end_pos,
  328. arg_index, next_id>(fmt);
  329. } else if constexpr (c == '}') {
  330. return parse_tail<Args, arg_id_end_pos + 1, ID>(
  331. runtime_named_field<char_type>{arg_id_result.arg_id.val.name},
  332. fmt);
  333. } else if constexpr (c == ':') {
  334. return unknown_format(); // no type info for specs parsing
  335. }
  336. }
  337. }
  338. } else if constexpr (str[POS] == '}') {
  339. if constexpr (POS + 1 == str.size())
  340. FMT_THROW(format_error("unmatched '}' in format string"));
  341. return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), fmt);
  342. } else {
  343. constexpr auto end = parse_text(str, POS + 1);
  344. if constexpr (end - POS > 1) {
  345. return parse_tail<Args, end, ID>(make_text(str, POS, end - POS), fmt);
  346. } else {
  347. return parse_tail<Args, end, ID>(code_unit<char_type>{str[POS]}, fmt);
  348. }
  349. }
  350. }
  351. template <typename... Args, typename S,
  352. FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
  353. constexpr auto compile(S fmt) {
  354. constexpr auto str = basic_string_view<typename S::char_type>(fmt);
  355. if constexpr (str.size() == 0) {
  356. return detail::make_text(str, 0, 0);
  357. } else {
  358. constexpr auto result =
  359. detail::compile_format_string<detail::type_list<Args...>, 0, 0>(fmt);
  360. return result;
  361. }
  362. }
  363. #endif // defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
  364. } // namespace detail
  365. FMT_BEGIN_EXPORT
  366. #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
  367. template <typename CompiledFormat, typename... Args,
  368. typename Char = typename CompiledFormat::char_type,
  369. FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
  370. FMT_INLINE std::basic_string<Char> format(const CompiledFormat& cf,
  371. const Args&... args) {
  372. auto s = std::basic_string<Char>();
  373. cf.format(std::back_inserter(s), args...);
  374. return s;
  375. }
  376. template <typename OutputIt, typename CompiledFormat, typename... Args,
  377. FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
  378. constexpr FMT_INLINE OutputIt format_to(OutputIt out, const CompiledFormat& cf,
  379. const Args&... args) {
  380. return cf.format(out, args...);
  381. }
  382. template <typename S, typename... Args,
  383. FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
  384. FMT_INLINE std::basic_string<typename S::char_type> format(const S&,
  385. Args&&... args) {
  386. if constexpr (std::is_same<typename S::char_type, char>::value) {
  387. constexpr auto str = basic_string_view<typename S::char_type>(S());
  388. if constexpr (str.size() == 2 && str[0] == '{' && str[1] == '}') {
  389. const auto& first = detail::first(args...);
  390. if constexpr (detail::is_named_arg<
  391. remove_cvref_t<decltype(first)>>::value) {
  392. return fmt::to_string(first.value);
  393. } else {
  394. return fmt::to_string(first);
  395. }
  396. }
  397. }
  398. constexpr auto compiled = detail::compile<Args...>(S());
  399. if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
  400. detail::unknown_format>()) {
  401. return fmt::format(
  402. static_cast<basic_string_view<typename S::char_type>>(S()),
  403. std::forward<Args>(args)...);
  404. } else {
  405. return fmt::format(compiled, std::forward<Args>(args)...);
  406. }
  407. }
  408. template <typename OutputIt, typename S, typename... Args,
  409. FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
  410. FMT_CONSTEXPR OutputIt format_to(OutputIt out, const S&, Args&&... args) {
  411. constexpr auto compiled = detail::compile<Args...>(S());
  412. if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
  413. detail::unknown_format>()) {
  414. return fmt::format_to(
  415. out, static_cast<basic_string_view<typename S::char_type>>(S()),
  416. std::forward<Args>(args)...);
  417. } else {
  418. return fmt::format_to(out, compiled, std::forward<Args>(args)...);
  419. }
  420. }
  421. #endif
  422. template <typename OutputIt, typename S, typename... Args,
  423. FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
  424. auto format_to_n(OutputIt out, size_t n, const S& fmt, Args&&... args)
  425. -> format_to_n_result<OutputIt> {
  426. using traits = detail::fixed_buffer_traits;
  427. auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);
  428. fmt::format_to(std::back_inserter(buf), fmt, std::forward<Args>(args)...);
  429. return {buf.out(), buf.count()};
  430. }
  431. template <typename S, typename... Args,
  432. FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
  433. FMT_CONSTEXPR20 auto formatted_size(const S& fmt, const Args&... args)
  434. -> size_t {
  435. return fmt::format_to(detail::counting_iterator(), fmt, args...).count();
  436. }
  437. template <typename S, typename... Args,
  438. FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
  439. void print(std::FILE* f, const S& fmt, const Args&... args) {
  440. memory_buffer buffer;
  441. fmt::format_to(std::back_inserter(buffer), fmt, args...);
  442. detail::print(f, {buffer.data(), buffer.size()});
  443. }
  444. template <typename S, typename... Args,
  445. FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
  446. void print(const S& fmt, const Args&... args) {
  447. print(stdout, fmt, args...);
  448. }
  449. #if FMT_USE_NONTYPE_TEMPLATE_ARGS
  450. inline namespace literals {
  451. template <detail_exported::fixed_string Str> constexpr auto operator""_cf() {
  452. using char_t = remove_cvref_t<decltype(Str.data[0])>;
  453. return detail::udl_compiled_string<char_t, sizeof(Str.data) / sizeof(char_t),
  454. Str>();
  455. }
  456. } // namespace literals
  457. #endif
  458. FMT_END_EXPORT
  459. FMT_END_NAMESPACE
  460. #endif // FMT_COMPILE_H_