Debian Codegraph @

podofo/3rdparty/fmtlib/fmt/compile.h

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