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