compile.h 19 KB

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