WPILibC++ 2025.2.1
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
22namespace detail {
23
24template <typename S>
25struct 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
45template <typename Char, size_t N, fmt::detail::fixed_string<Char, N> Str>
46struct udl_compiled_string : compiled_string {
47 using char_type = Char;
48 constexpr explicit operator basic_string_view<char_type>() const {
49 return {Str.data, N - 1};
50 }
51};
52#endif
53
54template <typename T, typename... Tail>
55auto first(const T& value, const Tail&...) -> const T& {
56 return value;
57}
58
59#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
60template <typename... Args> struct type_list {};
61
62// Returns a reference to the argument at index N from [first, rest...].
63template <int N, typename T, typename... Args>
64constexpr 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
74template <int N, typename T, typename... Args, typename Char>
75constexpr 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
86template <typename... Args, typename Char>
87FMT_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
96template <typename Char, typename... Args>
97constexpr 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
102template <int N, typename> struct get_type_impl;
103
104template <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
109template <int N, typename T>
110using get_type = typename get_type_impl<N, T>::type;
111
112template <typename T> struct is_compiled_format : std::false_type {};
113
114template <typename Char> struct text {
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
124template <typename Char>
125struct is_compiled_format<text<Char>> : std::true_type {};
126
127template <typename Char>
128constexpr text<Char> make_text(basic_string_view<Char> s, size_t pos,
129 size_t size) {
130 return {{&s[pos], size}};
131}
132
133template <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&`.
145template <typename T, int N, typename... Args>
146constexpr 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
155template <typename Char>
156struct is_compiled_format<code_unit<Char>> : std::true_type {};
157
158// A replacement field that refers to argument N.
159template <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) {
167 return copy<Char>(s.begin(), s.end(), out);
168 } else {
169 return write<Char>(out, arg);
170 }
171 }
172};
173
174template <typename Char, typename T, int N>
175struct is_compiled_format<field<Char, T, N>> : std::true_type {};
176
177// A replacement field that refers to argument with name.
178template <typename Char> struct runtime_named_field {
179 using char_type = Char;
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
206template <typename Char>
207struct is_compiled_format<runtime_named_field<Char>> : std::true_type {};
208
209// A replacement field that refers to argument N and has format specifiers.
210template <typename Char, typename T, int N> struct spec_field {
211 using char_type = Char;
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...);
220 return fmt.format(get_arg_checked<T, N>(args...), ctx);
221 }
222};
223
224template <typename Char, typename T, int N>
225struct is_compiled_format<spec_field<Char, T, N>> : std::true_type {};
226
227template <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
239template <typename L, typename R>
240struct is_compiled_format<concat<L, R>> : std::true_type {};
241
242template <typename L, typename R>
243constexpr concat<L, R> make_concat(L lhs, R rhs) {
244 return {lhs, rhs};
245}
246
247struct unknown_format {};
248
249template <typename Char>
250constexpr 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
257template <typename Args, size_t POS, int ID, typename S>
258constexpr auto compile_format_string(S fmt);
259
260template <typename Args, size_t POS, int ID, typename T, typename S>
261constexpr 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
274template <typename T, typename Char> struct parse_specs_result {
276 size_t end;
277 int next_arg_id;
278};
279
280enum { manual_indexing_id = -1 };
281
282template <typename T, typename Char>
283constexpr 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
294template <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
314template <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
320template <int ID, typename Char>
321constexpr 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
327template <typename T, typename Enable = void> struct field_type {
328 using type = remove_cvref_t<T>;
329};
330
331template <typename T>
332struct field_type<T, enable_if_t<detail::is_named_arg<T>::value>> {
333 using type = remove_cvref_t<decltype(T::value)>;
334};
335
336template <typename T, typename Args, size_t END_POS, int ARG_INDEX, int NEXT_ID,
337 typename S>
338constexpr 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.
364template <typename Args, size_t POS, int ID, typename S>
365constexpr 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
427template <typename... Args, typename S,
429constexpr 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
443
444#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
445
446template <typename CompiledFormat, typename... Args,
447 typename Char = typename CompiledFormat::char_type,
448 FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
449FMT_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
456template <typename OutputIt, typename CompiledFormat, typename... Args,
457 FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
458constexpr FMT_INLINE OutputIt format_to(OutputIt out, const CompiledFormat& cf,
459 const Args&... args) {
460 return cf.format(out, args...);
461}
462
463template <typename S, typename... Args,
465FMT_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(
484 std::forward<Args>(args)...);
485 } else {
486 return fmt::format(compiled, std::forward<Args>(args)...);
487 }
488}
489
490template <typename OutputIt, typename S, typename... Args,
492FMT_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
505template <typename OutputIt, typename S, typename... Args,
507auto format_to_n(OutputIt out, size_t n, const S& fmt, Args&&... args)
509 using traits = detail::fixed_buffer_traits;
511 fmt::format_to(std::back_inserter(buf), fmt, std::forward<Args>(args)...);
512 return {buf.out(), buf.count()};
513}
514
515template <typename S, typename... Args,
517FMT_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
524template <typename S, typename... Args,
526void print(std::FILE* f, const S& fmt, const Args&... args) {
527 auto buf = memory_buffer();
528 fmt::format_to(appender(buf), fmt, args...);
529 detail::print(f, {buf.data(), buf.size()});
530}
531
532template <typename S, typename... Args,
534void print(const S& fmt, const Args&... args) {
535 print(stdout, fmt, args...);
536}
537
538#if FMT_USE_NONTYPE_TEMPLATE_ARGS
539inline namespace literals {
540template <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
550
551#endif // FMT_COMPILE_H_
An implementation of std::basic_string_view for pre-C++17.
Definition base.h:504
constexpr auto size() const noexcept -> size_t
Returns the string size.
Definition base.h:549
constexpr auto data() const noexcept -> const Char *
Returns a pointer to the string data.
Definition base.h:546
FMT_CONSTEXPR void remove_prefix(size_t n) noexcept
Definition base.h:558
Definition compile.h:20
Definition base.h:1955
Definition base.h:1809
Definition base.h:1826
Definition base.h:2081
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:507
FMT_CONSTEXPR20 auto formatted_size(const S &fmt, const Args &... args) -> size_t
Definition compile.h:517
void print(std::FILE *f, const S &fmt, const Args &... args)
Definition compile.h:526
FMT_INLINE auto format_to(OutputIt out, detail::locale_ref loc, format_string< T... > fmt, T &&... args) -> OutputIt
Definition format.h:4162
FMT_INLINE auto format(detail::locale_ref loc, format_string< T... > fmt, T &&... args) -> std::string
Definition format.h:4146
basic_memory_buffer< char > memory_buffer
Definition format.h:891
#define FMT_THROW(x)
Definition format.h:149
detail namespace with internal helper functions
Definition input_adapters.h:32
auto first(const T &value, const Tail &...) -> const T &
Definition compile.h:55
OutStringType concat(Args &&... args)
Definition string_concat.h:137
FMT_API void print(FILE *, string_view)
constexpr auto max_value() -> T
Definition format.h:407
@ value
the parser finished reading a JSON value
auto get(const wpi::detail::iteration_proxy_value< IteratorType > &i) -> decltype(i.key())
Definition iteration_proxy.h:193
typename V::value_type char_t
String's character (code unit) type. detail:: is intentional to prevent ADL.
Definition base.h:935
FMT_CONSTEXPR auto parse_arg_id(const Char *begin, const Char *end, Handler &&handler) -> const Char *
Definition base.h:1293
Definition json.h:5183
cubed< length::millimeter > L
Definition volume.h:49
Definition base.h:2323
Definition compile.h:25
Definition base.h:1014
Definition base.h:2808
Definition base.h:651
#define S(label, offset, message)
Definition Errors.h:113
typename std::enable_if< B, T >::type enable_if_t
Definition base.h:297
#define FMT_ASSERT(condition, message)
Definition base.h:381
#define FMT_END_EXPORT
Definition base.h:250
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:2775
basic_appender< char > appender
Definition base.h:619
typename std::remove_cv< remove_reference_t< T > >::type remove_cvref_t
Definition base.h:306
#define FMT_CONSTEXPR
Definition base.h:113
arg_id_kind
Definition base.h:686
#define FMT_BEGIN_NAMESPACE
Definition base.h:239
conditional_t< std::is_same< OutputIt, appender >::value, context, generic_context< OutputIt, Char > > basic_format_context
Definition base.h:632
#define FMT_ENABLE_IF(...)
Definition base.h:334
#define FMT_BEGIN_EXPORT
Definition base.h:249
#define FMT_INLINE
Definition base.h:209
#define FMT_CONSTEXPR20
Definition base.h:141
#define FMT_END_NAMESPACE
Definition base.h:242
#define FMT_EXPORT
Definition base.h:248