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 > 20
40
41template <class _Tp, class _CharT = char>
42  requires same_as<remove_cvref_t<_Tp>, _Tp> && formattable<_Tp, _CharT>
43struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT range_formatter {
44  _LIBCPP_HIDE_FROM_ABI constexpr void set_separator(basic_string_view<_CharT> __separator) {
45    __separator_ = __separator;
46  }
47  _LIBCPP_HIDE_FROM_ABI constexpr void
48  set_brackets(basic_string_view<_CharT> __opening_bracket, basic_string_view<_CharT> __closing_bracket) {
49    __opening_bracket_ = __opening_bracket;
50    __closing_bracket_ = __closing_bracket;
51  }
52
53  _LIBCPP_HIDE_FROM_ABI constexpr formatter<_Tp, _CharT>& underlying() { return __underlying_; }
54  _LIBCPP_HIDE_FROM_ABI constexpr const formatter<_Tp, _CharT>& underlying() const { return __underlying_; }
55
56  template <class _ParseContext>
57  _LIBCPP_HIDE_FROM_ABI constexpr typename _ParseContext::iterator parse(_ParseContext& __parse_ctx) {
58    const _CharT* __begin = __parser_.__parse(__parse_ctx, __format_spec::__fields_range);
59    const _CharT* __end   = __parse_ctx.end();
60    if (__begin == __end)
61      return __begin;
62
63    // The n field overrides a possible m type, therefore delay applying the
64    // effect of n until the type has been procesed.
65    bool __clear_brackets = (*__begin == _CharT('n'));
66    if (__clear_brackets) {
67      ++__begin;
68      if (__begin == __end) {
69        // Since there is no more data, clear the brackets before returning.
70        set_brackets({}, {});
71        return __begin;
72      }
73    }
74
75    __parse_type(__begin, __end);
76    if (__clear_brackets)
77      set_brackets({}, {});
78    if (__begin == __end)
79      return __begin;
80
81    bool __has_range_underlying_spec = *__begin == _CharT(':');
82    if (__parser_.__type_ != __format_spec::__type::__default) {
83      // [format.range.formatter]/6
84      //   If the range-type is s or ?s, then there shall be no n option and no
85      //   range-underlying-spec.
86      if (__clear_brackets) {
87        if (__parser_.__type_ == __format_spec::__type::__string)
88          std::__throw_format_error("The n option and type s can't be used together");
89        std::__throw_format_error("The n option and type ?s can't be used together");
90      }
91      if (__has_range_underlying_spec) {
92        if (__parser_.__type_ == __format_spec::__type::__string)
93          std::__throw_format_error("Type s and an underlying format specification can't be used together");
94        std::__throw_format_error("Type ?s and an underlying format specification can't be used together");
95      }
96    } else if (!__has_range_underlying_spec)
97      std::__set_debug_format(__underlying_);
98
99    if (__has_range_underlying_spec) {
100      // range-underlying-spec:
101      //   :  format-spec
102      ++__begin;
103      if (__begin == __end)
104        return __begin;
105
106      __parse_ctx.advance_to(__begin);
107      __begin = __underlying_.parse(__parse_ctx);
108    }
109
110    if (__begin != __end && *__begin != _CharT('}'))
111      std::__throw_format_error("The format-spec should consume the input or end with a '}'");
112
113    return __begin;
114  }
115
116  template <ranges::input_range _Rp, class _FormatContext>
117    requires formattable<ranges::range_reference_t<_Rp>, _CharT> &&
118             same_as<remove_cvref_t<ranges::range_reference_t<_Rp>>, _Tp>
119  _LIBCPP_HIDE_FROM_ABI typename _FormatContext::iterator format(_Rp&& __range, _FormatContext& __ctx) const {
120    __format_spec::__parsed_specifications<_CharT> __specs = __parser_.__get_parsed_std_specifications(__ctx);
121
122    if (!__specs.__has_width())
123      return __format_range(__range, __ctx, __specs);
124
125    // The size of the buffer needed is:
126    // - open bracket characters
127    // - close bracket character
128    // - n elements where every element may have a different size
129    // - (n -1) separators
130    // The size of the element is hard to predict, knowing the type helps but
131    // it depends on the format-spec. As an initial estimate we guess 6
132    // characters.
133    // Typically both brackets are 1 character and the separator is 2
134    // characters. Which means there will be
135    //   (n - 1) * 2 + 1 + 1 = n * 2 character
136    // So estimate 8 times the range size as buffer.
137    std::size_t __capacity_hint = 0;
138    if constexpr (std::ranges::sized_range<_Rp>)
139      __capacity_hint = 8 * ranges::size(__range);
140    __format::__retarget_buffer<_CharT> __buffer{__capacity_hint};
141    basic_format_context<typename __format::__retarget_buffer<_CharT>::__iterator, _CharT> __c{
142        __buffer.__make_output_iterator(), __ctx};
143
144    __format_range(__range, __c, __specs);
145
146    return __formatter::__write_string_no_precision(__buffer.__view(), __ctx.out(), __specs);
147  }
148
149  template <ranges::input_range _Rp, class _FormatContext>
150  typename _FormatContext::iterator _LIBCPP_HIDE_FROM_ABI
151  __format_range(_Rp&& __range, _FormatContext& __ctx, __format_spec::__parsed_specifications<_CharT> __specs) const {
152    if constexpr (same_as<_Tp, _CharT>) {
153      switch (__specs.__std_.__type_) {
154      case __format_spec::__type::__string:
155      case __format_spec::__type::__debug:
156        return __format_as_string(__range, __ctx, __specs.__std_.__type_ == __format_spec::__type::__debug);
157      default:
158        return __format_as_sequence(__range, __ctx);
159      }
160    } else
161      return __format_as_sequence(__range, __ctx);
162  }
163
164  template <ranges::input_range _Rp, class _FormatContext>
165  _LIBCPP_HIDE_FROM_ABI typename _FormatContext::iterator
166  __format_as_string(_Rp&& __range, _FormatContext& __ctx, bool __debug_format) const {
167    // When the range is contiguous use a basic_string_view instead to avoid a
168    // copy of the underlying data. The basic_string_view formatter
169    // specialization is the "basic" string formatter in libc++.
170    if constexpr (ranges::contiguous_range<_Rp> && std::ranges::sized_range<_Rp>) {
171      std::formatter<basic_string_view<_CharT>, _CharT> __formatter;
172      if (__debug_format)
173        __formatter.set_debug_format();
174      return __formatter.format(
175          basic_string_view<_CharT>{
176              ranges::data(__range),
177              ranges::size(__range),
178          },
179          __ctx);
180    } else {
181      std::formatter<basic_string<_CharT>, _CharT> __formatter;
182      if (__debug_format)
183        __formatter.set_debug_format();
184      // P2106's from_range has not been implemented yet. Instead use a simple
185      // copy operation.
186      // TODO FMT use basic_string's "from_range" constructor.
187      // return std::formatter<basic_string<_CharT>, _CharT>{}.format(basic_string<_CharT>{from_range, __range}, __ctx);
188      basic_string<_CharT> __str;
189      ranges::copy(__range, back_insert_iterator{__str});
190      return __formatter.format(__str, __ctx);
191    }
192  }
193
194  template <ranges::input_range _Rp, class _FormatContext>
195  _LIBCPP_HIDE_FROM_ABI typename _FormatContext::iterator
196  __format_as_sequence(_Rp&& __range, _FormatContext& __ctx) const {
197    __ctx.advance_to(ranges::copy(__opening_bracket_, __ctx.out()).out);
198    bool __use_separator = false;
199    for (auto&& __e : __range) {
200      if (__use_separator)
201        __ctx.advance_to(ranges::copy(__separator_, __ctx.out()).out);
202      else
203        __use_separator = true;
204
205      __ctx.advance_to(__underlying_.format(__e, __ctx));
206    }
207
208    return ranges::copy(__closing_bracket_, __ctx.out()).out;
209  }
210
211  __format_spec::__parser<_CharT> __parser_{.__alignment_ = __format_spec::__alignment::__left};
212
213private:
214  _LIBCPP_HIDE_FROM_ABI constexpr void __parse_type(const _CharT*& __begin, const _CharT* __end) {
215    switch (*__begin) {
216    case _CharT('m'):
217      if constexpr (__fmt_pair_like<_Tp>) {
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("The range-format-spec type m requires two elements for a pair or tuple");
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("The range-format-spec type s requires formatting a character type");
231      break;
232
233    case _CharT('?'):
234      ++__begin;
235      if (__begin == __end || *__begin != _CharT('s'))
236        std::__throw_format_error("The format-spec 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("The range-format-spec type ?s requires formatting a character type");
242    }
243  }
244
245  formatter<_Tp, _CharT> __underlying_;
246  basic_string_view<_CharT> __separator_       = _LIBCPP_STATICALLY_WIDEN(_CharT, ", ");
247  basic_string_view<_CharT> __opening_bracket_ = _LIBCPP_STATICALLY_WIDEN(_CharT, "[");
248  basic_string_view<_CharT> __closing_bracket_ = _LIBCPP_STATICALLY_WIDEN(_CharT, "]");
249};
250
251#endif //_LIBCPP_STD_VER > 20
252
253_LIBCPP_END_NAMESPACE_STD
254
255#endif // _LIBCPP___FORMAT_RANGE_FORMATTER_H
256