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