Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-07-09 08:31:54

0001 // Formatting library for C++ - experimental format string compilation
0002 //
0003 // Copyright (c) 2012 - present, Victor Zverovich and fmt contributors
0004 // All rights reserved.
0005 //
0006 // For the license information refer to format.h.
0007 
0008 #ifndef FMT_COMPILE_H_
0009 #define FMT_COMPILE_H_
0010 
0011 #include "format.h"
0012 
0013 FMT_BEGIN_NAMESPACE
0014 namespace detail {
0015 
0016 template <typename Char, typename InputIt>
0017 FMT_CONSTEXPR inline auto copy_str(InputIt begin, InputIt end,
0018                                    counting_iterator it) -> counting_iterator {
0019   return it + (end - begin);
0020 }
0021 
0022 // A compile-time string which is compiled into fast formatting code.
0023 class compiled_string {};
0024 
0025 template <typename S>
0026 struct is_compiled_string : std::is_base_of<compiled_string, S> {};
0027 
0028 /**
0029   \rst
0030   Converts a string literal *s* into a format string that will be parsed at
0031   compile time and converted into efficient formatting code. Requires C++17
0032   ``constexpr if`` compiler support.
0033 
0034   **Example**::
0035 
0036     // Converts 42 into std::string using the most efficient method and no
0037     // runtime format string processing.
0038     std::string s = fmt::format(FMT_COMPILE("{}"), 42);
0039   \endrst
0040  */
0041 #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
0042 #  define FMT_COMPILE(s) \
0043     FMT_STRING_IMPL(s, fmt::detail::compiled_string, explicit)
0044 #else
0045 #  define FMT_COMPILE(s) FMT_STRING(s)
0046 #endif
0047 
0048 #if FMT_USE_NONTYPE_TEMPLATE_ARGS
0049 template <typename Char, size_t N,
0050           fmt::detail_exported::fixed_string<Char, N> Str>
0051 struct udl_compiled_string : compiled_string {
0052   using char_type = Char;
0053   explicit constexpr operator basic_string_view<char_type>() const {
0054     return {Str.data, N - 1};
0055   }
0056 };
0057 #endif
0058 
0059 template <typename T, typename... Tail>
0060 auto first(const T& value, const Tail&...) -> const T& {
0061   return value;
0062 }
0063 
0064 #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
0065 template <typename... Args> struct type_list {};
0066 
0067 // Returns a reference to the argument at index N from [first, rest...].
0068 template <int N, typename T, typename... Args>
0069 constexpr const auto& get([[maybe_unused]] const T& first,
0070                           [[maybe_unused]] const Args&... rest) {
0071   static_assert(N < 1 + sizeof...(Args), "index is out of bounds");
0072   if constexpr (N == 0)
0073     return first;
0074   else
0075     return detail::get<N - 1>(rest...);
0076 }
0077 
0078 template <typename Char, typename... Args>
0079 constexpr int get_arg_index_by_name(basic_string_view<Char> name,
0080                                     type_list<Args...>) {
0081   return get_arg_index_by_name<Args...>(name);
0082 }
0083 
0084 template <int N, typename> struct get_type_impl;
0085 
0086 template <int N, typename... Args> struct get_type_impl<N, type_list<Args...>> {
0087   using type =
0088       remove_cvref_t<decltype(detail::get<N>(std::declval<Args>()...))>;
0089 };
0090 
0091 template <int N, typename T>
0092 using get_type = typename get_type_impl<N, T>::type;
0093 
0094 template <typename T> struct is_compiled_format : std::false_type {};
0095 
0096 template <typename Char> struct text {
0097   basic_string_view<Char> data;
0098   using char_type = Char;
0099 
0100   template <typename OutputIt, typename... Args>
0101   constexpr OutputIt format(OutputIt out, const Args&...) const {
0102     return write<Char>(out, data);
0103   }
0104 };
0105 
0106 template <typename Char>
0107 struct is_compiled_format<text<Char>> : std::true_type {};
0108 
0109 template <typename Char>
0110 constexpr text<Char> make_text(basic_string_view<Char> s, size_t pos,
0111                                size_t size) {
0112   return {{&s[pos], size}};
0113 }
0114 
0115 template <typename Char> struct code_unit {
0116   Char value;
0117   using char_type = Char;
0118 
0119   template <typename OutputIt, typename... Args>
0120   constexpr OutputIt format(OutputIt out, const Args&...) const {
0121     *out++ = value;
0122     return out;
0123   }
0124 };
0125 
0126 // This ensures that the argument type is convertible to `const T&`.
0127 template <typename T, int N, typename... Args>
0128 constexpr const T& get_arg_checked(const Args&... args) {
0129   const auto& arg = detail::get<N>(args...);
0130   if constexpr (detail::is_named_arg<remove_cvref_t<decltype(arg)>>()) {
0131     return arg.value;
0132   } else {
0133     return arg;
0134   }
0135 }
0136 
0137 template <typename Char>
0138 struct is_compiled_format<code_unit<Char>> : std::true_type {};
0139 
0140 // A replacement field that refers to argument N.
0141 template <typename Char, typename T, int N> struct field {
0142   using char_type = Char;
0143 
0144   template <typename OutputIt, typename... Args>
0145   constexpr OutputIt format(OutputIt out, const Args&... args) const {
0146     const T& arg = get_arg_checked<T, N>(args...);
0147     if constexpr (std::is_convertible_v<T, basic_string_view<Char>>) {
0148       auto s = basic_string_view<Char>(arg);
0149       return copy_str<Char>(s.begin(), s.end(), out);
0150     }
0151     return write<Char>(out, arg);
0152   }
0153 };
0154 
0155 template <typename Char, typename T, int N>
0156 struct is_compiled_format<field<Char, T, N>> : std::true_type {};
0157 
0158 // A replacement field that refers to argument with name.
0159 template <typename Char> struct runtime_named_field {
0160   using char_type = Char;
0161   basic_string_view<Char> name;
0162 
0163   template <typename OutputIt, typename T>
0164   constexpr static bool try_format_argument(
0165       OutputIt& out,
0166       // [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9
0167       [[maybe_unused]] basic_string_view<Char> arg_name, const T& arg) {
0168     if constexpr (is_named_arg<typename std::remove_cv<T>::type>::value) {
0169       if (arg_name == arg.name) {
0170         out = write<Char>(out, arg.value);
0171         return true;
0172       }
0173     }
0174     return false;
0175   }
0176 
0177   template <typename OutputIt, typename... Args>
0178   constexpr OutputIt format(OutputIt out, const Args&... args) const {
0179     bool found = (try_format_argument(out, name, args) || ...);
0180     if (!found) {
0181       FMT_THROW(format_error("argument with specified name is not found"));
0182     }
0183     return out;
0184   }
0185 };
0186 
0187 template <typename Char>
0188 struct is_compiled_format<runtime_named_field<Char>> : std::true_type {};
0189 
0190 // A replacement field that refers to argument N and has format specifiers.
0191 template <typename Char, typename T, int N> struct spec_field {
0192   using char_type = Char;
0193   formatter<T, Char> fmt;
0194 
0195   template <typename OutputIt, typename... Args>
0196   constexpr FMT_INLINE OutputIt format(OutputIt out,
0197                                        const Args&... args) const {
0198     const auto& vargs =
0199         fmt::make_format_args<basic_format_context<OutputIt, Char>>(args...);
0200     basic_format_context<OutputIt, Char> ctx(out, vargs);
0201     return fmt.format(get_arg_checked<T, N>(args...), ctx);
0202   }
0203 };
0204 
0205 template <typename Char, typename T, int N>
0206 struct is_compiled_format<spec_field<Char, T, N>> : std::true_type {};
0207 
0208 template <typename L, typename R> struct concat {
0209   L lhs;
0210   R rhs;
0211   using char_type = typename L::char_type;
0212 
0213   template <typename OutputIt, typename... Args>
0214   constexpr OutputIt format(OutputIt out, const Args&... args) const {
0215     out = lhs.format(out, args...);
0216     return rhs.format(out, args...);
0217   }
0218 };
0219 
0220 template <typename L, typename R>
0221 struct is_compiled_format<concat<L, R>> : std::true_type {};
0222 
0223 template <typename L, typename R>
0224 constexpr concat<L, R> make_concat(L lhs, R rhs) {
0225   return {lhs, rhs};
0226 }
0227 
0228 struct unknown_format {};
0229 
0230 template <typename Char>
0231 constexpr size_t parse_text(basic_string_view<Char> str, size_t pos) {
0232   for (size_t size = str.size(); pos != size; ++pos) {
0233     if (str[pos] == '{' || str[pos] == '}') break;
0234   }
0235   return pos;
0236 }
0237 
0238 template <typename Args, size_t POS, int ID, typename S>
0239 constexpr auto compile_format_string(S format_str);
0240 
0241 template <typename Args, size_t POS, int ID, typename T, typename S>
0242 constexpr auto parse_tail(T head, S format_str) {
0243   if constexpr (POS !=
0244                 basic_string_view<typename S::char_type>(format_str).size()) {
0245     constexpr auto tail = compile_format_string<Args, POS, ID>(format_str);
0246     if constexpr (std::is_same<remove_cvref_t<decltype(tail)>,
0247                                unknown_format>())
0248       return tail;
0249     else
0250       return make_concat(head, tail);
0251   } else {
0252     return head;
0253   }
0254 }
0255 
0256 template <typename T, typename Char> struct parse_specs_result {
0257   formatter<T, Char> fmt;
0258   size_t end;
0259   int next_arg_id;
0260 };
0261 
0262 enum { manual_indexing_id = -1 };
0263 
0264 template <typename T, typename Char>
0265 constexpr parse_specs_result<T, Char> parse_specs(basic_string_view<Char> str,
0266                                                   size_t pos, int next_arg_id) {
0267   str.remove_prefix(pos);
0268   auto ctx =
0269       compile_parse_context<Char>(str, max_value<int>(), nullptr, next_arg_id);
0270   auto f = formatter<T, Char>();
0271   auto end = f.parse(ctx);
0272   return {f, pos + fmt::detail::to_unsigned(end - str.data()),
0273           next_arg_id == 0 ? manual_indexing_id : ctx.next_arg_id()};
0274 }
0275 
0276 template <typename Char> struct arg_id_handler {
0277   arg_ref<Char> arg_id;
0278 
0279   constexpr int on_auto() {
0280     FMT_ASSERT(false, "handler cannot be used with automatic indexing");
0281     return 0;
0282   }
0283   constexpr int on_index(int id) {
0284     arg_id = arg_ref<Char>(id);
0285     return 0;
0286   }
0287   constexpr int on_name(basic_string_view<Char> id) {
0288     arg_id = arg_ref<Char>(id);
0289     return 0;
0290   }
0291 };
0292 
0293 template <typename Char> struct parse_arg_id_result {
0294   arg_ref<Char> arg_id;
0295   const Char* arg_id_end;
0296 };
0297 
0298 template <int ID, typename Char>
0299 constexpr auto parse_arg_id(const Char* begin, const Char* end) {
0300   auto handler = arg_id_handler<Char>{arg_ref<Char>{}};
0301   auto arg_id_end = parse_arg_id(begin, end, handler);
0302   return parse_arg_id_result<Char>{handler.arg_id, arg_id_end};
0303 }
0304 
0305 template <typename T, typename Enable = void> struct field_type {
0306   using type = remove_cvref_t<T>;
0307 };
0308 
0309 template <typename T>
0310 struct field_type<T, enable_if_t<detail::is_named_arg<T>::value>> {
0311   using type = remove_cvref_t<decltype(T::value)>;
0312 };
0313 
0314 template <typename T, typename Args, size_t END_POS, int ARG_INDEX, int NEXT_ID,
0315           typename S>
0316 constexpr auto parse_replacement_field_then_tail(S format_str) {
0317   using char_type = typename S::char_type;
0318   constexpr auto str = basic_string_view<char_type>(format_str);
0319   constexpr char_type c = END_POS != str.size() ? str[END_POS] : char_type();
0320   if constexpr (c == '}') {
0321     return parse_tail<Args, END_POS + 1, NEXT_ID>(
0322         field<char_type, typename field_type<T>::type, ARG_INDEX>(),
0323         format_str);
0324   } else if constexpr (c != ':') {
0325     FMT_THROW(format_error("expected ':'"));
0326   } else {
0327     constexpr auto result = parse_specs<typename field_type<T>::type>(
0328         str, END_POS + 1, NEXT_ID == manual_indexing_id ? 0 : NEXT_ID);
0329     if constexpr (result.end >= str.size() || str[result.end] != '}') {
0330       FMT_THROW(format_error("expected '}'"));
0331       return 0;
0332     } else {
0333       return parse_tail<Args, result.end + 1, result.next_arg_id>(
0334           spec_field<char_type, typename field_type<T>::type, ARG_INDEX>{
0335               result.fmt},
0336           format_str);
0337     }
0338   }
0339 }
0340 
0341 // Compiles a non-empty format string and returns the compiled representation
0342 // or unknown_format() on unrecognized input.
0343 template <typename Args, size_t POS, int ID, typename S>
0344 constexpr auto compile_format_string(S format_str) {
0345   using char_type = typename S::char_type;
0346   constexpr auto str = basic_string_view<char_type>(format_str);
0347   if constexpr (str[POS] == '{') {
0348     if constexpr (POS + 1 == str.size())
0349       FMT_THROW(format_error("unmatched '{' in format string"));
0350     if constexpr (str[POS + 1] == '{') {
0351       return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str);
0352     } else if constexpr (str[POS + 1] == '}' || str[POS + 1] == ':') {
0353       static_assert(ID != manual_indexing_id,
0354                     "cannot switch from manual to automatic argument indexing");
0355       constexpr auto next_id =
0356           ID != manual_indexing_id ? ID + 1 : manual_indexing_id;
0357       return parse_replacement_field_then_tail<get_type<ID, Args>, Args,
0358                                                POS + 1, ID, next_id>(
0359           format_str);
0360     } else {
0361       constexpr auto arg_id_result =
0362           parse_arg_id<ID>(str.data() + POS + 1, str.data() + str.size());
0363       constexpr auto arg_id_end_pos = arg_id_result.arg_id_end - str.data();
0364       constexpr char_type c =
0365           arg_id_end_pos != str.size() ? str[arg_id_end_pos] : char_type();
0366       static_assert(c == '}' || c == ':', "missing '}' in format string");
0367       if constexpr (arg_id_result.arg_id.kind == arg_id_kind::index) {
0368         static_assert(
0369             ID == manual_indexing_id || ID == 0,
0370             "cannot switch from automatic to manual argument indexing");
0371         constexpr auto arg_index = arg_id_result.arg_id.val.index;
0372         return parse_replacement_field_then_tail<get_type<arg_index, Args>,
0373                                                  Args, arg_id_end_pos,
0374                                                  arg_index, manual_indexing_id>(
0375             format_str);
0376       } else if constexpr (arg_id_result.arg_id.kind == arg_id_kind::name) {
0377         constexpr auto arg_index =
0378             get_arg_index_by_name(arg_id_result.arg_id.val.name, Args{});
0379         if constexpr (arg_index >= 0) {
0380           constexpr auto next_id =
0381               ID != manual_indexing_id ? ID + 1 : manual_indexing_id;
0382           return parse_replacement_field_then_tail<
0383               decltype(get_type<arg_index, Args>::value), Args, arg_id_end_pos,
0384               arg_index, next_id>(format_str);
0385         } else if constexpr (c == '}') {
0386           return parse_tail<Args, arg_id_end_pos + 1, ID>(
0387               runtime_named_field<char_type>{arg_id_result.arg_id.val.name},
0388               format_str);
0389         } else if constexpr (c == ':') {
0390           return unknown_format();  // no type info for specs parsing
0391         }
0392       }
0393     }
0394   } else if constexpr (str[POS] == '}') {
0395     if constexpr (POS + 1 == str.size())
0396       FMT_THROW(format_error("unmatched '}' in format string"));
0397     return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str);
0398   } else {
0399     constexpr auto end = parse_text(str, POS + 1);
0400     if constexpr (end - POS > 1) {
0401       return parse_tail<Args, end, ID>(make_text(str, POS, end - POS),
0402                                        format_str);
0403     } else {
0404       return parse_tail<Args, end, ID>(code_unit<char_type>{str[POS]},
0405                                        format_str);
0406     }
0407   }
0408 }
0409 
0410 template <typename... Args, typename S,
0411           FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
0412 constexpr auto compile(S format_str) {
0413   constexpr auto str = basic_string_view<typename S::char_type>(format_str);
0414   if constexpr (str.size() == 0) {
0415     return detail::make_text(str, 0, 0);
0416   } else {
0417     constexpr auto result =
0418         detail::compile_format_string<detail::type_list<Args...>, 0, 0>(
0419             format_str);
0420     return result;
0421   }
0422 }
0423 #endif  // defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
0424 }  // namespace detail
0425 
0426 FMT_BEGIN_EXPORT
0427 
0428 #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
0429 
0430 template <typename CompiledFormat, typename... Args,
0431           typename Char = typename CompiledFormat::char_type,
0432           FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
0433 FMT_INLINE std::basic_string<Char> format(const CompiledFormat& cf,
0434                                           const Args&... args) {
0435   auto s = std::basic_string<Char>();
0436   cf.format(std::back_inserter(s), args...);
0437   return s;
0438 }
0439 
0440 template <typename OutputIt, typename CompiledFormat, typename... Args,
0441           FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
0442 constexpr FMT_INLINE OutputIt format_to(OutputIt out, const CompiledFormat& cf,
0443                                         const Args&... args) {
0444   return cf.format(out, args...);
0445 }
0446 
0447 template <typename S, typename... Args,
0448           FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
0449 FMT_INLINE std::basic_string<typename S::char_type> format(const S&,
0450                                                            Args&&... args) {
0451   if constexpr (std::is_same<typename S::char_type, char>::value) {
0452     constexpr auto str = basic_string_view<typename S::char_type>(S());
0453     if constexpr (str.size() == 2 && str[0] == '{' && str[1] == '}') {
0454       const auto& first = detail::first(args...);
0455       if constexpr (detail::is_named_arg<
0456                         remove_cvref_t<decltype(first)>>::value) {
0457         return fmt::to_string(first.value);
0458       } else {
0459         return fmt::to_string(first);
0460       }
0461     }
0462   }
0463   constexpr auto compiled = detail::compile<Args...>(S());
0464   if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
0465                              detail::unknown_format>()) {
0466     return fmt::format(
0467         static_cast<basic_string_view<typename S::char_type>>(S()),
0468         std::forward<Args>(args)...);
0469   } else {
0470     return fmt::format(compiled, std::forward<Args>(args)...);
0471   }
0472 }
0473 
0474 template <typename OutputIt, typename S, typename... Args,
0475           FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
0476 FMT_CONSTEXPR OutputIt format_to(OutputIt out, const S&, Args&&... args) {
0477   constexpr auto compiled = detail::compile<Args...>(S());
0478   if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
0479                              detail::unknown_format>()) {
0480     return fmt::format_to(
0481         out, static_cast<basic_string_view<typename S::char_type>>(S()),
0482         std::forward<Args>(args)...);
0483   } else {
0484     return fmt::format_to(out, compiled, std::forward<Args>(args)...);
0485   }
0486 }
0487 #endif
0488 
0489 template <typename OutputIt, typename S, typename... Args,
0490           FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
0491 auto format_to_n(OutputIt out, size_t n, const S& format_str, Args&&... args)
0492     -> format_to_n_result<OutputIt> {
0493   using traits = detail::fixed_buffer_traits;
0494   auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);
0495   fmt::format_to(std::back_inserter(buf), format_str,
0496                  std::forward<Args>(args)...);
0497   return {buf.out(), buf.count()};
0498 }
0499 
0500 template <typename S, typename... Args,
0501           FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
0502 FMT_CONSTEXPR20 auto formatted_size(const S& format_str, const Args&... args)
0503     -> size_t {
0504   return fmt::format_to(detail::counting_iterator(), format_str, args...)
0505       .count();
0506 }
0507 
0508 template <typename S, typename... Args,
0509           FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
0510 void print(std::FILE* f, const S& format_str, const Args&... args) {
0511   memory_buffer buffer;
0512   fmt::format_to(std::back_inserter(buffer), format_str, args...);
0513   detail::print(f, {buffer.data(), buffer.size()});
0514 }
0515 
0516 template <typename S, typename... Args,
0517           FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
0518 void print(const S& format_str, const Args&... args) {
0519   print(stdout, format_str, args...);
0520 }
0521 
0522 #if FMT_USE_NONTYPE_TEMPLATE_ARGS
0523 inline namespace literals {
0524 template <detail_exported::fixed_string Str> constexpr auto operator""_cf() {
0525   using char_t = remove_cvref_t<decltype(Str.data[0])>;
0526   return detail::udl_compiled_string<char_t, sizeof(Str.data) / sizeof(char_t),
0527                                      Str>();
0528 }
0529 }  // namespace literals
0530 #endif
0531 
0532 FMT_END_EXPORT
0533 FMT_END_NAMESPACE
0534 
0535 #endif  // FMT_COMPILE_H_