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