1 // Formatting library for C++ - experimental range support
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7 //
8 // Copyright (c) 2018 - present, Remotion (Igor Schulz)
9 // All Rights Reserved
10 // {fmt} support for ranges, containers and types tuple interface.
11 
12 #ifndef FMT_RANGES_H_
13 #define FMT_RANGES_H_
14 
15 #include <initializer_list>
16 #include <type_traits>
17 
18 #include "format.h"
19 
20 FMT_BEGIN_NAMESPACE
21 
22 template <typename Char, typename Enable = void> struct formatting_range {
23 #ifdef FMT_DEPRECATED_BRACED_RANGES
24   Char prefix = '{';
25   Char postfix = '}';
26 #else
27   Char prefix = '[';
28   Char postfix = ']';
29 #endif
30 
31   template <typename ParseContext>
32   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
33     return ctx.begin();
34   }
35 };
36 
37 template <typename Char, typename Enable = void> struct formatting_tuple {
38   Char prefix = '(';
39   Char postfix = ')';
40 
41   template <typename ParseContext>
42   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
43     return ctx.begin();
44   }
45 };
46 
47 namespace detail {
48 
49 template <typename RangeT, typename OutputIterator>
copy(const RangeT & range,OutputIterator out)50 OutputIterator copy(const RangeT& range, OutputIterator out) {
51   for (auto it = range.begin(), end = range.end(); it != end; ++it)
52     *out++ = *it;
53   return out;
54 }
55 
56 template <typename OutputIterator>
copy(const char * str,OutputIterator out)57 OutputIterator copy(const char* str, OutputIterator out) {
58   while (*str) *out++ = *str++;
59   return out;
60 }
61 
62 template <typename OutputIterator>
copy(char ch,OutputIterator out)63 OutputIterator copy(char ch, OutputIterator out) {
64   *out++ = ch;
65   return out;
66 }
67 
68 template <typename OutputIterator>
copy(wchar_t ch,OutputIterator out)69 OutputIterator copy(wchar_t ch, OutputIterator out) {
70   *out++ = ch;
71   return out;
72 }
73 
74 /// Return true value if T has std::string interface, like std::string_view.
75 template <typename T> class is_std_string_like {
76   template <typename U>
77   static auto check(U* p)
78       -> decltype((void)p->find('a'), p->length(), (void)p->data(), int());
79   template <typename> static void check(...);
80 
81  public:
82   static FMT_CONSTEXPR_DECL const bool value =
83       is_string<T>::value || !std::is_void<decltype(check<T>(nullptr))>::value;
84 };
85 
86 template <typename Char>
87 struct is_std_string_like<fmt::basic_string_view<Char>> : std::true_type {};
88 
89 template <typename... Ts> struct conditional_helper {};
90 
91 template <typename T, typename _ = void> struct is_range_ : std::false_type {};
92 
93 #if !FMT_MSC_VER || FMT_MSC_VER > 1800
94 
95 #  define FMT_DECLTYPE_RETURN(val)  \
96     ->decltype(val) { return val; } \
97     static_assert(                  \
98         true, "")  // This makes it so that a semicolon is required after the
99                    // macro, which helps clang-format handle the formatting.
100 
101 // C array overload
102 template <typename T, std::size_t N>
103 auto range_begin(const T (&arr)[N]) -> const T* {
104   return arr;
105 }
106 template <typename T, std::size_t N>
107 auto range_end(const T (&arr)[N]) -> const T* {
108   return arr + N;
109 }
110 
111 template <typename T, typename Enable = void>
112 struct has_member_fn_begin_end_t : std::false_type {};
113 
114 template <typename T>
115 struct has_member_fn_begin_end_t<T, void_t<decltype(std::declval<T>().begin()),
116                                            decltype(std::declval<T>().end())>>
117     : std::true_type {};
118 
119 // Member function overload
120 template <typename T>
121 auto range_begin(T&& rng) FMT_DECLTYPE_RETURN(static_cast<T&&>(rng).begin());
122 template <typename T>
123 auto range_end(T&& rng) FMT_DECLTYPE_RETURN(static_cast<T&&>(rng).end());
124 
125 // ADL overload. Only participates in overload resolution if member functions
126 // are not found.
127 template <typename T>
128 auto range_begin(T&& rng)
129     -> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,
130                    decltype(begin(static_cast<T&&>(rng)))> {
131   return begin(static_cast<T&&>(rng));
132 }
133 template <typename T>
134 auto range_end(T&& rng) -> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,
135                                        decltype(end(static_cast<T&&>(rng)))> {
136   return end(static_cast<T&&>(rng));
137 }
138 
139 template <typename T, typename Enable = void>
140 struct has_const_begin_end : std::false_type {};
141 template <typename T, typename Enable = void>
142 struct has_mutable_begin_end : std::false_type {};
143 
144 template <typename T>
145 struct has_const_begin_end<
146     T, void_t<decltype(detail::range_begin(
147                   std::declval<const remove_cvref_t<T>&>())),
148               decltype(detail::range_begin(
149                   std::declval<const remove_cvref_t<T>&>()))>>
150     : std::true_type {};
151 
152 template <typename T>
153 struct has_mutable_begin_end<
154     T, void_t<decltype(detail::range_begin(std::declval<T>())),
155               decltype(detail::range_begin(std::declval<T>())),
156               enable_if_t<std::is_copy_constructible<T>::value>>>
157     : std::true_type {};
158 
159 template <typename T>
160 struct is_range_<T, void>
161     : std::integral_constant<bool, (has_const_begin_end<T>::value ||
162                                     has_mutable_begin_end<T>::value)> {};
163 
164 template <typename T, typename Enable = void> struct range_to_view;
165 template <typename T>
166 struct range_to_view<T, enable_if_t<has_const_begin_end<T>::value>> {
167   struct view_t {
168     const T* m_range_ptr;
169 
170     auto begin() const FMT_DECLTYPE_RETURN(detail::range_begin(*m_range_ptr));
171     auto end() const FMT_DECLTYPE_RETURN(detail::range_end(*m_range_ptr));
172   };
173   static auto view(const T& range) -> view_t { return {&range}; }
174 };
175 
176 template <typename T>
177 struct range_to_view<T, enable_if_t<!has_const_begin_end<T>::value &&
178                                     has_mutable_begin_end<T>::value>> {
179   struct view_t {
180     T m_range_copy;
181 
182     auto begin() FMT_DECLTYPE_RETURN(detail::range_begin(m_range_copy));
183     auto end() FMT_DECLTYPE_RETURN(detail::range_end(m_range_copy));
184   };
185   static auto view(const T& range) -> view_t { return {range}; }
186 };
187 #  undef FMT_DECLTYPE_RETURN
188 #endif
189 
190 /// tuple_size and tuple_element check.
191 template <typename T> class is_tuple_like_ {
192   template <typename U>
193   static auto check(U* p) -> decltype(std::tuple_size<U>::value, int());
194   template <typename> static void check(...);
195 
196  public:
197   static FMT_CONSTEXPR_DECL const bool value =
198       !std::is_void<decltype(check<T>(nullptr))>::value;
199 };
200 
201 // Check for integer_sequence
202 #if defined(__cpp_lib_integer_sequence) || FMT_MSC_VER >= 1900
203 template <typename T, T... N>
204 using integer_sequence = std::integer_sequence<T, N...>;
205 template <size_t... N> using index_sequence = std::index_sequence<N...>;
206 template <size_t N> using make_index_sequence = std::make_index_sequence<N>;
207 #else
208 template <typename T, T... N> struct integer_sequence {
209   using value_type = T;
210 
211   static FMT_CONSTEXPR size_t size() { return sizeof...(N); }
212 };
213 
214 template <size_t... N> using index_sequence = integer_sequence<size_t, N...>;
215 
216 template <typename T, size_t N, T... Ns>
217 struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {};
218 template <typename T, T... Ns>
219 struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {};
220 
221 template <size_t N>
222 using make_index_sequence = make_integer_sequence<size_t, N>;
223 #endif
224 
225 template <class Tuple, class F, size_t... Is>
226 void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT {
227   using std::get;
228   // using free function get<I>(T) now.
229   const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
230   (void)_;  // blocks warnings
231 }
232 
233 template <class T>
234 FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes(
235     T const&) {
236   return {};
237 }
238 
239 template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) {
240   const auto indexes = get_indexes(tup);
241   for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
242 }
243 
244 template <typename Range>
245 using value_type =
246     remove_cvref_t<decltype(*detail::range_begin(std::declval<Range>()))>;
247 
248 template <typename OutputIt> OutputIt write_delimiter(OutputIt out) {
249   *out++ = ',';
250   *out++ = ' ';
251   return out;
252 }
253 
254 template <
255     typename Char, typename OutputIt, typename Arg,
256     FMT_ENABLE_IF(is_std_string_like<typename std::decay<Arg>::type>::value)>
257 OutputIt write_range_entry(OutputIt out, const Arg& v) {
258   *out++ = '"';
259   out = write<Char>(out, v);
260   *out++ = '"';
261   return out;
262 }
263 
264 template <typename Char, typename OutputIt, typename Arg,
265           FMT_ENABLE_IF(std::is_same<Arg, Char>::value)>
266 OutputIt write_range_entry(OutputIt out, const Arg v) {
267   *out++ = '\'';
268   *out++ = v;
269   *out++ = '\'';
270   return out;
271 }
272 
273 template <
274     typename Char, typename OutputIt, typename Arg,
275     FMT_ENABLE_IF(!is_std_string_like<typename std::decay<Arg>::type>::value &&
276                   !std::is_same<Arg, Char>::value)>
277 OutputIt write_range_entry(OutputIt out, const Arg& v) {
278   return write<Char>(out, v);
279 }
280 
281 }  // namespace detail
282 
283 template <typename T> struct is_tuple_like {
284   static FMT_CONSTEXPR_DECL const bool value =
285       detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value;
286 };
287 
288 template <typename TupleT, typename Char>
289 struct formatter<TupleT, Char, enable_if_t<fmt::is_tuple_like<TupleT>::value>> {
290  private:
291   // C++11 generic lambda for format()
292   template <typename FormatContext> struct format_each {
293     template <typename T> void operator()(const T& v) {
294       if (i > 0) out = detail::write_delimiter(out);
295       out = detail::write_range_entry<Char>(out, v);
296       ++i;
297     }
298     formatting_tuple<Char>& formatting;
299     size_t& i;
300     typename std::add_lvalue_reference<
301         decltype(std::declval<FormatContext>().out())>::type out;
302   };
303 
304  public:
305   formatting_tuple<Char> formatting;
306 
307   template <typename ParseContext>
308   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
309     return formatting.parse(ctx);
310   }
311 
312   template <typename FormatContext = format_context>
313   auto format(const TupleT& values, FormatContext& ctx) -> decltype(ctx.out()) {
314     auto out = ctx.out();
315     size_t i = 0;
316 
317     detail::copy(formatting.prefix, out);
318     detail::for_each(values, format_each<FormatContext>{formatting, i, out});
319     detail::copy(formatting.postfix, out);
320 
321     return ctx.out();
322   }
323 };
324 
325 template <typename T, typename Char> struct is_range {
326   static FMT_CONSTEXPR_DECL const bool value =
327       detail::is_range_<T>::value && !detail::is_std_string_like<T>::value &&
328       !std::is_convertible<T, std::basic_string<Char>>::value &&
329       !std::is_constructible<detail::std_string_view<Char>, T>::value;
330 };
331 
332 template <typename T, typename Char>
333 struct formatter<
334     T, Char,
335     enable_if_t<
336         fmt::is_range<T, Char>::value
337 // Workaround a bug in MSVC 2017 and earlier.
338 #if !FMT_MSC_VER || FMT_MSC_VER >= 1927
339         && (has_formatter<detail::value_type<T>, format_context>::value ||
340             detail::has_fallback_formatter<detail::value_type<T>, Char>::value)
341 #endif
342         >> {
343   formatting_range<Char> formatting;
344 
345   template <typename ParseContext>
346   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
347     return formatting.parse(ctx);
348   }
349 
350   template <typename FormatContext>
351   typename FormatContext::iterator format(const T& values, FormatContext& ctx) {
352     auto out = detail::copy(formatting.prefix, ctx.out());
353     size_t i = 0;
354     auto view = detail::range_to_view<T>::view(values);
355     auto it = view.begin();
356     auto end = view.end();
357     for (; it != end; ++it) {
358       if (i > 0) out = detail::write_delimiter(out);
359       out = detail::write_range_entry<Char>(out, *it);
360       ++i;
361     }
362     return detail::copy(formatting.postfix, out);
363   }
364 };
365 
366 template <typename Char, typename... T> struct tuple_join_view : detail::view {
367   const std::tuple<T...>& tuple;
368   basic_string_view<Char> sep;
369 
370   tuple_join_view(const std::tuple<T...>& t, basic_string_view<Char> s)
371       : tuple(t), sep{s} {}
372 };
373 
374 template <typename Char, typename... T>
375 using tuple_arg_join = tuple_join_view<Char, T...>;
376 
377 template <typename Char, typename... T>
378 struct formatter<tuple_join_view<Char, T...>, Char> {
379   template <typename ParseContext>
380   FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
381     return ctx.begin();
382   }
383 
384   template <typename FormatContext>
385   auto format(const tuple_join_view<Char, T...>& value, FormatContext& ctx) ->
386       typename FormatContext::iterator {
387     return format(value, ctx, detail::make_index_sequence<sizeof...(T)>{});
388   }
389 
390  private:
391   template <typename FormatContext, size_t... N>
392   auto format(const tuple_join_view<Char, T...>& value, FormatContext& ctx,
393               detail::index_sequence<N...>) ->
394       typename FormatContext::iterator {
395     using std::get;
396     return format_args(value, ctx, get<N>(value.tuple)...);
397   }
398 
399   template <typename FormatContext>
400   auto format_args(const tuple_join_view<Char, T...>&, FormatContext& ctx) ->
401       typename FormatContext::iterator {
402     // NOTE: for compilers that support C++17, this empty function instantiation
403     // can be replaced with a constexpr branch in the variadic overload.
404     return ctx.out();
405   }
406 
407   template <typename FormatContext, typename Arg, typename... Args>
408   auto format_args(const tuple_join_view<Char, T...>& value, FormatContext& ctx,
409                    const Arg& arg, const Args&... args) ->
410       typename FormatContext::iterator {
411     using base = formatter<typename std::decay<Arg>::type, Char>;
412     auto out = base().format(arg, ctx);
413     if (sizeof...(Args) > 0) {
414       out = std::copy(value.sep.begin(), value.sep.end(), out);
415       ctx.advance_to(out);
416       return format_args(value, ctx, args...);
417     }
418     return out;
419   }
420 };
421 
422 FMT_MODULE_EXPORT_BEGIN
423 
424 /**
425   \rst
426   Returns an object that formats `tuple` with elements separated by `sep`.
427 
428   **Example**::
429 
430     std::tuple<int, char> t = {1, 'a'};
431     fmt::print("{}", fmt::join(t, ", "));
432     // Output: "1, a"
433   \endrst
434  */
435 template <typename... T>
436 FMT_CONSTEXPR auto join(const std::tuple<T...>& tuple, string_view sep)
437     -> tuple_join_view<char, T...> {
438   return {tuple, sep};
439 }
440 
441 template <typename... T>
442 FMT_CONSTEXPR auto join(const std::tuple<T...>& tuple,
443                         basic_string_view<wchar_t> sep)
444     -> tuple_join_view<wchar_t, T...> {
445   return {tuple, sep};
446 }
447 
448 /**
449   \rst
450   Returns an object that formats `initializer_list` with elements separated by
451   `sep`.
452 
453   **Example**::
454 
455     fmt::print("{}", fmt::join({1, 2, 3}, ", "));
456     // Output: "1, 2, 3"
457   \endrst
458  */
459 template <typename T>
460 auto join(std::initializer_list<T> list, string_view sep)
461     -> join_view<const T*, const T*> {
462   return join(std::begin(list), std::end(list), sep);
463 }
464 
465 FMT_MODULE_EXPORT_END
466 FMT_END_NAMESPACE
467 
468 #endif  // FMT_RANGES_H_
469