compile.h 19 KB

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