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