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/concepts.h> 23 #include <__format/format_context.h> 24 #include <__format/format_error.h> 25 #include <__format/formatter.h> 26 #include <__format/formatter_output.h> 27 #include <__format/parser_std_format_spec.h> 28 #include <__iterator/back_insert_iterator.h> 29 #include <__ranges/concepts.h> 30 #include <__ranges/data.h> 31 #include <__ranges/size.h> 32 #include <__type_traits/remove_cvref.h> 33 #include <string_view> 34 35 _LIBCPP_BEGIN_NAMESPACE_STD 36 37 #if _LIBCPP_STD_VER >= 23 38 39 template <class _Tp, class _CharT = char> 40 requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT> 41 struct _LIBCPP_TEMPLATE_VIS range_formatter { 42 _LIBCPP_HIDE_FROM_ABI constexpr void set_separator(basic_string_view<_CharT> __separator) noexcept { 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) noexcept { 47 __opening_bracket_ = __opening_bracket; 48 __closing_bracket_ = __closing_bracket; 49 } 50 51 _LIBCPP_HIDE_FROM_ABI constexpr formatter<_Tp, _CharT>& underlying() noexcept { return __underlying_; } 52 _LIBCPP_HIDE_FROM_ABI constexpr const formatter<_Tp, _CharT>& underlying() const noexcept { return __underlying_; } 53 54 template <class _ParseContext> 55 _LIBCPP_HIDE_FROM_ABI 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({}, {}); 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("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("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("The n option and type s can't be used together"); 106 std::__throw_format_error("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("Type s and an underlying format specification can't be used together"); 111 std::__throw_format_error("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 _LIBCPP_HIDE_FROM_ABI 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 _LIBCPP_HIDE_FROM_ABI 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 _LIBCPP_HIDE_FROM_ABI 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 // P2106's from_range has not been implemented yet. Instead use a simple 188 // copy operation. 189 // TODO FMT use basic_string's "from_range" constructor. 190 // return std::formatter<basic_string<_CharT>, _CharT>{}.format(basic_string<_CharT>{from_range, __range}, __ctx); 191 basic_string<_CharT> __str; 192 ranges::copy(__range, back_insert_iterator{__str}); 193 return __formatter.format(__str, __ctx); 194 } 195 } 196 197 template <ranges::input_range _Rp, class _FormatContext> 198 _LIBCPP_HIDE_FROM_ABI typename _FormatContext::iterator 199 __format_as_sequence(_Rp&& __range, _FormatContext& __ctx) const { 200 __ctx.advance_to(ranges::copy(__opening_bracket_, __ctx.out()).out); 201 bool __use_separator = false; 202 for (auto&& __e : __range) { 203 if (__use_separator) 204 __ctx.advance_to(ranges::copy(__separator_, __ctx.out()).out); 205 else 206 __use_separator = true; 207 208 __ctx.advance_to(__underlying_.format(__e, __ctx)); 209 } 210 211 return ranges::copy(__closing_bracket_, __ctx.out()).out; 212 } 213 214 __format_spec::__parser<_CharT> __parser_{.__alignment_ = __format_spec::__alignment::__left}; 215 216 private: 217 template <contiguous_iterator _Iterator> 218 _LIBCPP_HIDE_FROM_ABI constexpr void __parse_type(_Iterator& __begin, _Iterator __end) { 219 switch (*__begin) { 220 case _CharT('m'): 221 if constexpr (__fmt_pair_like<_Tp>) { 222 set_brackets(_LIBCPP_STATICALLY_WIDEN(_CharT, "{"), _LIBCPP_STATICALLY_WIDEN(_CharT, "}")); 223 set_separator(_LIBCPP_STATICALLY_WIDEN(_CharT, ", ")); 224 ++__begin; 225 } else 226 std::__throw_format_error("Type m requires a pair or a tuple with two elements"); 227 break; 228 229 case _CharT('s'): 230 if constexpr (same_as<_Tp, _CharT>) { 231 __parser_.__type_ = __format_spec::__type::__string; 232 ++__begin; 233 } else 234 std::__throw_format_error("Type s requires character type as formatting argument"); 235 break; 236 237 case _CharT('?'): 238 ++__begin; 239 if (__begin == __end || *__begin != _CharT('s')) 240 std::__throw_format_error("The format specifier should consume the input or end with a '}'"); 241 if constexpr (same_as<_Tp, _CharT>) { 242 __parser_.__type_ = __format_spec::__type::__debug; 243 ++__begin; 244 } else 245 std::__throw_format_error("Type ?s requires character type as formatting argument"); 246 } 247 } 248 249 template <class _ParseContext> 250 _LIBCPP_HIDE_FROM_ABI constexpr typename _ParseContext::iterator 251 __parse_empty_range_underlying_spec(_ParseContext& __ctx, typename _ParseContext::iterator __begin) { 252 __ctx.advance_to(__begin); 253 [[maybe_unused]] typename _ParseContext::iterator __result = __underlying_.parse(__ctx); 254 _LIBCPP_ASSERT_UNCATEGORIZED( 255 __result == __begin, 256 "the underlying's parse function should not advance the input beyond the end of the input"); 257 return __begin; 258 } 259 260 formatter<_Tp, _CharT> __underlying_; 261 basic_string_view<_CharT> __separator_ = _LIBCPP_STATICALLY_WIDEN(_CharT, ", "); 262 basic_string_view<_CharT> __opening_bracket_ = _LIBCPP_STATICALLY_WIDEN(_CharT, "["); 263 basic_string_view<_CharT> __closing_bracket_ = _LIBCPP_STATICALLY_WIDEN(_CharT, "]"); 264 }; 265 266 #endif //_LIBCPP_STD_VER >= 23 267 268 _LIBCPP_END_NAMESPACE_STD 269 270 #endif // _LIBCPP___FORMAT_RANGE_FORMATTER_H 271