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