1 // -*- C++ -*-
2 //===----------------------------------------------------------------------===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #ifndef _LIBCPP___FORMAT_FORMATTER_TUPLE_H
11 #define _LIBCPP___FORMAT_FORMATTER_TUPLE_H
12 
13 #include <__algorithm/ranges_copy.h>
14 #include <__availability>
15 #include <__chrono/statically_widen.h>
16 #include <__config>
17 #include <__format/concepts.h>
18 #include <__format/format_args.h>
19 #include <__format/format_context.h>
20 #include <__format/format_error.h>
21 #include <__format/format_parse_context.h>
22 #include <__format/formatter.h>
23 #include <__format/formatter_output.h>
24 #include <__format/parser_std_format_spec.h>
25 #include <__iterator/back_insert_iterator.h>
26 #include <__type_traits/remove_cvref.h>
27 #include <__utility/integer_sequence.h>
28 #include <__utility/pair.h>
29 #include <string_view>
30 #include <tuple>
31 
32 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
33 #  pragma GCC system_header
34 #endif
35 
36 _LIBCPP_BEGIN_NAMESPACE_STD
37 
38 #if _LIBCPP_STD_VER > 20
39 
40 template <__fmt_char_type _CharT, class _Tuple, formattable<_CharT>... _Args>
41 struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT __formatter_tuple {
42   _LIBCPP_HIDE_FROM_ABI constexpr void set_separator(basic_string_view<_CharT> __separator) {
43     __separator_ = __separator;
44   }
45   _LIBCPP_HIDE_FROM_ABI constexpr void
46   set_brackets(basic_string_view<_CharT> __opening_bracket, basic_string_view<_CharT> __closing_bracket) {
47     __opening_bracket_ = __opening_bracket;
48     __closing_bracket_ = __closing_bracket;
49   }
50 
51   template <class _ParseContext>
52   _LIBCPP_HIDE_FROM_ABI constexpr typename _ParseContext::iterator parse(_ParseContext& __parse_ctx) {
53     const _CharT* __begin = __parser_.__parse(__parse_ctx, __format_spec::__fields_tuple);
54 
55     // [format.tuple]/7
56     //   ... For each element e in underlying_, if e.set_debug_format()
57     //   is a valid expression, calls e.set_debug_format().
58     // TODO FMT this can be removed when P2733 is accepted.
59     std::__for_each_index_sequence(make_index_sequence<sizeof...(_Args)>(), [&]<size_t _Index> {
60       std::__set_debug_format(std::get<_Index>(__underlying_));
61     });
62 
63     const _CharT* __end = __parse_ctx.end();
64     if (__begin == __end)
65       return __begin;
66 
67     if (*__begin == _CharT('m')) {
68       if constexpr (sizeof...(_Args) == 2) {
69         set_separator(_LIBCPP_STATICALLY_WIDEN(_CharT, ": "));
70         set_brackets({}, {});
71         ++__begin;
72       } else
73         std::__throw_format_error("The format specifier m requires a pair or a two-element tuple");
74     } else if (*__begin == _CharT('n')) {
75       set_brackets({}, {});
76       ++__begin;
77     }
78 
79     if (__begin != __end && *__begin != _CharT('}'))
80       std::__throw_format_error("The format-spec should consume the input or end with a '}'");
81 
82     return __begin;
83   }
84 
85   template <class _FormatContext>
86   typename _FormatContext::iterator _LIBCPP_HIDE_FROM_ABI
87   format(conditional_t<(formattable<const _Args, _CharT> && ...), const _Tuple&, _Tuple&> __tuple,
88          _FormatContext& __ctx) const {
89     __format_spec::__parsed_specifications<_CharT> __specs = __parser_.__get_parsed_std_specifications(__ctx);
90 
91     if (!__specs.__has_width())
92       return __format_tuple(__tuple, __ctx);
93 
94     basic_string<_CharT> __str;
95 
96     // Since the output is written to a different iterator a new context is
97     // created. Since the underlying formatter uses the default formatting it
98     // doesn't need a locale or the formatting arguments. So creating a new
99     // context works.
100     //
101     // This solution works for this formatter, but it will not work for the
102     // range_formatter. In that patch a generic solution is work in progress.
103     // Once that is finished it can be used here. (The range_formatter will use
104     // these features so it's easier to add it there and then port it.)
105     //
106     // TODO FMT Use formatting wrapping used in the range_formatter.
107     basic_format_context __c = std::__format_context_create(
108         back_insert_iterator{__str},
109         basic_format_args<basic_format_context<back_insert_iterator<basic_string<_CharT>>, _CharT>>{});
110 
111     __format_tuple(__tuple, __c);
112 
113     return __formatter::__write_string_no_precision(basic_string_view{__str}, __ctx.out(), __specs);
114   }
115 
116   template <class _FormatContext>
117   _LIBCPP_HIDE_FROM_ABI typename _FormatContext::iterator __format_tuple(auto&& __tuple, _FormatContext& __ctx) const {
118     __ctx.advance_to(std::ranges::copy(__opening_bracket_, __ctx.out()).out);
119 
120     std::__for_each_index_sequence(make_index_sequence<sizeof...(_Args)>(), [&]<size_t _Index> {
121       if constexpr (_Index)
122         __ctx.advance_to(std::ranges::copy(__separator_, __ctx.out()).out);
123 
124         // During review Victor suggested to make the exposition only
125         // __underlying_ member a local variable. Currently the Standard
126         // requires nested debug-enabled formatter specializations not to
127         // output escaped output. P2733 fixes that bug, once accepted the
128         // code below can be used.
129         // (Note when a paper allows parsing a tuple-underlying-spec the
130         // exposition only member needs to be a class member. Earlier
131         // revisions of P2286 proposed that, but this was not pursued,
132         // due to time constrains and complexity of the matter.)
133         // TODO FMT This can be updated after P2733 is accepted.
134 #  if 0
135       // P2286 uses an exposition only member in the formatter
136       //   tuple<formatter<remove_cvref_t<_Args>, _CharT>...> __underlying_;
137       // This was used in earlier versions of the paper since
138       // __underlying_.parse(...) was called. This is no longer the case
139       // so we can reduce the scope of the formatter.
140       //
141       // It does require the underlying's parse effect to be moved here too.
142       using _Arg = tuple_element<_Index, decltype(__tuple)>;
143       formatter<remove_cvref_t<_Args>, _CharT> __underlying;
144 
145       // [format.tuple]/7
146       //   ... For each element e in underlying_, if e.set_debug_format()
147       //   is a valid expression, calls e.set_debug_format().
148       std::__set_debug_format(__underlying);
149 #  else
150       __ctx.advance_to(std::get<_Index>(__underlying_).format(std::get<_Index>(__tuple), __ctx));
151 #  endif
152     });
153 
154     return std::ranges::copy(__closing_bracket_, __ctx.out()).out;
155   }
156 
157   __format_spec::__parser<_CharT> __parser_{.__alignment_ = __format_spec::__alignment::__left};
158 
159 private:
160   tuple<formatter<remove_cvref_t<_Args>, _CharT>...> __underlying_;
161   basic_string_view<_CharT> __separator_       = _LIBCPP_STATICALLY_WIDEN(_CharT, ", ");
162   basic_string_view<_CharT> __opening_bracket_ = _LIBCPP_STATICALLY_WIDEN(_CharT, "(");
163   basic_string_view<_CharT> __closing_bracket_ = _LIBCPP_STATICALLY_WIDEN(_CharT, ")");
164 };
165 
166 template <__fmt_char_type _CharT, formattable<_CharT>... _Args>
167 struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter<pair<_Args...>, _CharT>
168     : public __formatter_tuple<_CharT, pair<_Args...>, _Args...> {};
169 
170 template <__fmt_char_type _CharT, formattable<_CharT>... _Args>
171 struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter<tuple<_Args...>, _CharT>
172     : public __formatter_tuple<_CharT, tuple<_Args...>, _Args...> {};
173 
174 #endif //_LIBCPP_STD_VER > 20
175 
176 _LIBCPP_END_NAMESPACE_STD
177 
178 #endif // _LIBCPP___FORMAT_FORMATTER_TUPLE_H
179