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