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_RANGE_FORMATTER_H
11#define _LIBCPP___FORMAT_RANGE_FORMATTER_H
12
13#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
14# pragma GCC system_header
15#endif
16
17#include <__algorithm/ranges_copy.h>
18#include <__chrono/statically_widen.h>
19#include <__concepts/same_as.h>
20#include <__config>
21#include <__format/buffer.h>
22#include <__format/fmt_pair_like.h>
23#include <__format/format_context.h>
24#include <__format/format_error.h>
25#include <__format/formattable.h>
26#include <__format/formatter.h>
27#include <__format/formatter_output.h>
28#include <__format/parser_std_format_spec.h>
29#include <__iterator/back_insert_iterator.h>
30#include <__ranges/concepts.h>
31#include <__ranges/data.h>
32#include <__ranges/from_range.h>
33#include <__ranges/size.h>
34#include <__type_traits/remove_cvref.h>
35#include <string_view>
36
37#if _LIBCPP_STD_VER >= 23
38
39_LIBCPP_BEGIN_NAMESPACE_STD
40
41template <class _Tp, class _CharT = char>
42 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
43struct range_formatter {
44 constexpr void set_separator(basic_string_view<_CharT> __separator) noexcept { __separator_ = __separator; }
45 constexpr void
46 set_brackets(basic_string_view<_CharT> __opening_bracket, basic_string_view<_CharT> __closing_bracket) noexcept {
47 __opening_bracket_ = __opening_bracket;
48 __closing_bracket_ = __closing_bracket;
49 }
50
51 constexpr formatter<_Tp, _CharT>& underlying() noexcept { return __underlying_; }
52 constexpr const formatter<_Tp, _CharT>& underlying() const noexcept { return __underlying_; }
53
54 template <class _ParseContext>
55 constexpr typename _ParseContext::iterator parse(_ParseContext& __ctx) {
56 auto __begin = __parser_.__parse(__ctx, __format_spec::__fields_range);
57 auto __end = __ctx.end();
58 // Note the cases where __begin == __end in this code only happens when the
59 // replacement-field has no terminating }, or when the parse is manually
60 // called with a format-spec. The former is an error and the latter means
61 // using a formatter without the format functions or print.
62 if (__begin == __end) [[unlikely]]
63 return __parse_empty_range_underlying_spec(__ctx, __begin);
64
65 // The n field overrides a possible m type, therefore delay applying the
66 // effect of n until the type has been procesed.
67 __parse_type(__begin, __end);
68 if (__parser_.__clear_brackets_)
69 set_brackets(opening_bracket: {}, closing_bracket: {});
70 if (__begin == __end) [[unlikely]]
71 return __parse_empty_range_underlying_spec(__ctx, __begin);
72
73 bool __has_range_underlying_spec = *__begin == _CharT(':');
74 if (__has_range_underlying_spec) {
75 // range-underlying-spec:
76 // : format-spec
77 ++__begin;
78 } else if (__begin != __end && *__begin != _CharT('}'))
79 // When there is no underlaying range the current parse should have
80 // consumed the format-spec. If not, the not consumed input will be
81 // processed by the underlying. For example {:-} for a range in invalid,
82 // the sign field is not present. Without this check the underlying_ will
83 // get -} as input which my be valid.
84 std::__throw_format_error(s: "The format specifier should consume the input or end with a '}'");
85
86 __ctx.advance_to(__begin);
87 __begin = __underlying_.parse(__ctx);
88
89 // This test should not be required if __has_range_underlying_spec is false.
90 // However this test makes sure the underlying formatter left the parser in
91 // a valid state. (Note this is not a full protection against evil parsers.
92 // For example
93 // } this is test for the next argument {}
94 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
95 // could consume more than it should.
96 if (__begin != __end && *__begin != _CharT('}'))
97 std::__throw_format_error(s: "The format specifier should consume the input or end with a '}'");
98
99 if (__parser_.__type_ != __format_spec::__type::__default) {
100 // [format.range.formatter]/6
101 // If the range-type is s or ?s, then there shall be no n option and no
102 // range-underlying-spec.
103 if (__parser_.__clear_brackets_) {
104 if (__parser_.__type_ == __format_spec::__type::__string)
105 std::__throw_format_error(s: "The n option and type s can't be used together");
106 std::__throw_format_error(s: "The n option and type ?s can't be used together");
107 }
108 if (__has_range_underlying_spec) {
109 if (__parser_.__type_ == __format_spec::__type::__string)
110 std::__throw_format_error(s: "Type s and an underlying format specification can't be used together");
111 std::__throw_format_error(s: "Type ?s and an underlying format specification can't be used together");
112 }
113 } else if (!__has_range_underlying_spec)
114 std::__set_debug_format(__underlying_);
115
116 return __begin;
117 }
118
119 template <ranges::input_range _Rp, class _FormatContext>
120 requires formattable<ranges::range_reference_t<_Rp>, _CharT> &&
121 same_as<remove_cvref_t<ranges::range_reference_t<_Rp>>, _Tp>
122 typename _FormatContext::iterator format(_Rp&& __range, _FormatContext& __ctx) const {
123 __format_spec::__parsed_specifications<_CharT> __specs = __parser_.__get_parsed_std_specifications(__ctx);
124
125 if (!__specs.__has_width())
126 return __format_range(__range, __ctx, __specs);
127
128 // The size of the buffer needed is:
129 // - open bracket characters
130 // - close bracket character
131 // - n elements where every element may have a different size
132 // - (n -1) separators
133 // The size of the element is hard to predict, knowing the type helps but
134 // it depends on the format-spec. As an initial estimate we guess 6
135 // characters.
136 // Typically both brackets are 1 character and the separator is 2
137 // characters. Which means there will be
138 // (n - 1) * 2 + 1 + 1 = n * 2 character
139 // So estimate 8 times the range size as buffer.
140 std::size_t __capacity_hint = 0;
141 if constexpr (std::ranges::sized_range<_Rp>)
142 __capacity_hint = 8 * ranges::size(__range);
143 __format::__retarget_buffer<_CharT> __buffer{__capacity_hint};
144 basic_format_context<typename __format::__retarget_buffer<_CharT>::__iterator, _CharT> __c{
145 __buffer.__make_output_iterator(), __ctx};
146
147 __format_range(__range, __c, __specs);
148
149 return __formatter::__write_string_no_precision(__buffer.__view(), __ctx.out(), __specs);
150 }
151
152 template <ranges::input_range _Rp, class _FormatContext>
153 typename _FormatContext::iterator
154 __format_range(_Rp&& __range, _FormatContext& __ctx, __format_spec::__parsed_specifications<_CharT> __specs) const {
155 if constexpr (same_as<_Tp, _CharT>) {
156 switch (__specs.__std_.__type_) {
157 case __format_spec::__type::__string:
158 case __format_spec::__type::__debug:
159 return __format_as_string(__range, __ctx, __specs.__std_.__type_ == __format_spec::__type::__debug);
160 default:
161 return __format_as_sequence(__range, __ctx);
162 }
163 } else
164 return __format_as_sequence(__range, __ctx);
165 }
166
167 template <ranges::input_range _Rp, class _FormatContext>
168 typename _FormatContext::iterator
169 __format_as_string(_Rp&& __range, _FormatContext& __ctx, bool __debug_format) const {
170 // When the range is contiguous use a basic_string_view instead to avoid a
171 // copy of the underlying data. The basic_string_view formatter
172 // specialization is the "basic" string formatter in libc++.
173 if constexpr (ranges::contiguous_range<_Rp> && std::ranges::sized_range<_Rp>) {
174 std::formatter<basic_string_view<_CharT>, _CharT> __formatter;
175 if (__debug_format)
176 __formatter.set_debug_format();
177 return __formatter.format(
178 basic_string_view<_CharT>{
179 ranges::data(__range),
180 ranges::size(__range),
181 },
182 __ctx);
183 } else {
184 std::formatter<basic_string<_CharT>, _CharT> __formatter;
185 if (__debug_format)
186 __formatter.set_debug_format();
187 return __formatter.format(basic_string<_CharT>{from_range, __range}, __ctx);
188 }
189 }
190
191 template <ranges::input_range _Rp, class _FormatContext>
192 typename _FormatContext::iterator __format_as_sequence(_Rp&& __range, _FormatContext& __ctx) const {
193 __ctx.advance_to(ranges::copy(__opening_bracket_, __ctx.out()).out);
194 bool __use_separator = false;
195 for (auto&& __e : __range) {
196 if (__use_separator)
197 __ctx.advance_to(ranges::copy(__separator_, __ctx.out()).out);
198 else
199 __use_separator = true;
200
201 __ctx.advance_to(__underlying_.format(__e, __ctx));
202 }
203
204 return ranges::copy(__closing_bracket_, __ctx.out()).out;
205 }
206
207 __format_spec::__parser<_CharT> __parser_ = {
208 __format_spec::__parser_data<_CharT>{.__alignment_ = __format_spec::__alignment::__left}};
209
210private:
211 template <contiguous_iterator _Iterator>
212 constexpr void __parse_type(_Iterator& __begin, _Iterator __end) {
213 switch (*__begin) {
214 case _CharT('m'):
215 if constexpr (__fmt_pair_like<_Tp>) {
216 __underlying_.set_separator(_LIBCPP_STATICALLY_WIDEN(_CharT, ": "));
217 __underlying_.set_brackets({}, {});
218 set_brackets(_LIBCPP_STATICALLY_WIDEN(_CharT, "{"), _LIBCPP_STATICALLY_WIDEN(_CharT, "}"));
219 set_separator(_LIBCPP_STATICALLY_WIDEN(_CharT, ", "));
220 ++__begin;
221 } else
222 std::__throw_format_error(s: "Type m requires a pair or a tuple with two elements");
223 break;
224
225 case _CharT('s'):
226 if constexpr (same_as<_Tp, _CharT>) {
227 __parser_.__type_ = __format_spec::__type::__string;
228 ++__begin;
229 } else
230 std::__throw_format_error(s: "Type s requires character type as formatting argument");
231 break;
232
233 case _CharT('?'):
234 ++__begin;
235 if (__begin == __end || *__begin != _CharT('s'))
236 std::__throw_format_error(s: "The format specifier should consume the input or end with a '}'");
237 if constexpr (same_as<_Tp, _CharT>) {
238 __parser_.__type_ = __format_spec::__type::__debug;
239 ++__begin;
240 } else
241 std::__throw_format_error(s: "Type ?s requires character type as formatting argument");
242 }
243 }
244
245 template <class _ParseContext>
246 constexpr typename _ParseContext::iterator
247 __parse_empty_range_underlying_spec(_ParseContext& __ctx, typename _ParseContext::iterator __begin) {
248 __ctx.advance_to(__begin);
249 [[maybe_unused]] typename _ParseContext::iterator __result = __underlying_.parse(__ctx);
250 _LIBCPP_ASSERT_INTERNAL(__result == __begin,
251 "the underlying's parse function should not advance the input beyond the end of the input");
252 return __begin;
253 }
254
255 formatter<_Tp, _CharT> __underlying_;
256 basic_string_view<_CharT> __separator_ = _LIBCPP_STATICALLY_WIDEN(_CharT, ", ");
257 basic_string_view<_CharT> __opening_bracket_ = _LIBCPP_STATICALLY_WIDEN(_CharT, "[");
258 basic_string_view<_CharT> __closing_bracket_ = _LIBCPP_STATICALLY_WIDEN(_CharT, "]");
259};
260
261_LIBCPP_END_NAMESPACE_STD
262
263#endif // _LIBCPP_STD_VER >= 23
264
265#endif // _LIBCPP___FORMAT_RANGE_FORMATTER_H
266