You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

611 lines
21 KiB

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