compile.h 18 KB

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