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_PARSER_STD_FORMAT_SPEC_H
11 #define _LIBCPP___FORMAT_PARSER_STD_FORMAT_SPEC_H
12 
13 #include <__algorithm/find_if.h>
14 #include <__algorithm/min.h>
15 #include <__config>
16 #include <__debug>
17 #include <__format/format_arg.h>
18 #include <__format/format_error.h>
19 #include <__format/format_string.h>
20 #include <__variant/monostate.h>
21 #include <bit>
22 #include <concepts>
23 #include <cstdint>
24 #include <type_traits>
25 
26 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
27 # pragma GCC system_header
28 #endif
29 
30 _LIBCPP_PUSH_MACROS
31 #include <__undef_macros>
32 
33 _LIBCPP_BEGIN_NAMESPACE_STD
34 
35 #if _LIBCPP_STD_VER > 17
36 
37 // TODO FMT Remove this once we require compilers with proper C++20 support.
38 // If the compiler has no concepts support, the format header will be disabled.
39 // Without concepts support enable_if needs to be used and that too much effort
40 // to support compilers with partial C++20 support.
41 # if !defined(_LIBCPP_HAS_NO_CONCEPTS)
42 
43 namespace __format_spec {
44 
45 /**
46  * Contains the flags for the std-format-spec.
47  *
48  * Some format-options can only be used for specific C++types and may depend on
49  * the selected format-type.
50  * * The C++type filtering can be done using the proper policies for
51  *   @ref __parser_std.
52  * * The format-type filtering needs to be done post parsing in the parser
53  *   derived from @ref __parser_std.
54  */
55 class _LIBCPP_TYPE_VIS _Flags {
56 public:
57   enum class _LIBCPP_ENUM_VIS _Alignment : uint8_t {
58     /**
59      * No alignment is set in the format string.
60      *
61      * Zero-padding is ignored when an alignment is selected.
62      * The default alignment depends on the selected format-type.
63      */
64     __default,
65     __left,
66     __center,
67     __right
68   };
69   enum class _LIBCPP_ENUM_VIS _Sign : uint8_t {
70     /**
71      * No sign is set in the format string.
72      *
73      * The sign isn't allowed for certain format-types. By using this value
74      * it's possible to detect whether or not the user explicitly set the sign
75      * flag. For formatting purposes it behaves the same as @ref __minus.
76      */
77     __default,
78     __minus,
79     __plus,
80     __space
81   };
82 
83   _Alignment __alignment : 2 {_Alignment::__default};
84   _Sign __sign : 2 {_Sign::__default};
85   uint8_t __alternate_form : 1 {false};
86   uint8_t __zero_padding : 1 {false};
87   uint8_t __locale_specific_form : 1 {false};
88 
89   enum class _LIBCPP_ENUM_VIS _Type : uint8_t {
90     __default,
91     __string,
92     __binary_lower_case,
93     __binary_upper_case,
94     __octal,
95     __decimal,
96     __hexadecimal_lower_case,
97     __hexadecimal_upper_case,
98     __pointer,
99     __char,
100     __float_hexadecimal_lower_case,
101     __float_hexadecimal_upper_case,
102     __scientific_lower_case,
103     __scientific_upper_case,
104     __fixed_lower_case,
105     __fixed_upper_case,
106     __general_lower_case,
107     __general_upper_case
108   };
109 
110   _Type __type{_Type::__default};
111 };
112 
113 namespace __detail {
114 template <class _CharT>
115 _LIBCPP_HIDE_FROM_ABI constexpr bool
116 __parse_alignment(_CharT __c, _Flags& __flags) noexcept {
117   switch (__c) {
118   case _CharT('<'):
119     __flags.__alignment = _Flags::_Alignment::__left;
120     return true;
121 
122   case _CharT('^'):
123     __flags.__alignment = _Flags::_Alignment::__center;
124     return true;
125 
126   case _CharT('>'):
127     __flags.__alignment = _Flags::_Alignment::__right;
128     return true;
129   }
130   return false;
131 }
132 } // namespace __detail
133 
134 template <class _CharT>
135 class _LIBCPP_TEMPLATE_VIS __parser_fill_align {
136 public:
137   // TODO FMT The standard doesn't specify this character is a Unicode
138   // character. Validate what fmt and MSVC have implemented.
139   _CharT __fill{_CharT(' ')};
140 
141 protected:
142   _LIBCPP_HIDE_FROM_ABI constexpr const _CharT*
143   __parse(const _CharT* __begin, const _CharT* __end, _Flags& __flags) {
144     _LIBCPP_ASSERT(__begin != __end,
145                    "When called with an empty input the function will cause "
146                    "undefined behavior by evaluating data not in the input");
147     if (__begin + 1 != __end) {
148       if (__detail::__parse_alignment(*(__begin + 1), __flags)) {
149         if (*__begin == _CharT('{') || *__begin == _CharT('}'))
150           __throw_format_error(
151               "The format-spec fill field contains an invalid character");
152         __fill = *__begin;
153         return __begin + 2;
154       }
155     }
156 
157     if (__detail::__parse_alignment(*__begin, __flags))
158       return __begin + 1;
159 
160     return __begin;
161   }
162 };
163 
164 template <class _CharT>
165 _LIBCPP_HIDE_FROM_ABI constexpr const _CharT*
166 __parse_sign(const _CharT* __begin, _Flags& __flags) noexcept {
167   switch (*__begin) {
168   case _CharT('-'):
169     __flags.__sign = _Flags::_Sign::__minus;
170     break;
171   case _CharT('+'):
172     __flags.__sign = _Flags::_Sign::__plus;
173     break;
174   case _CharT(' '):
175     __flags.__sign = _Flags::_Sign::__space;
176     break;
177   default:
178     return __begin;
179   }
180   return __begin + 1;
181 }
182 
183 template <class _CharT>
184 _LIBCPP_HIDE_FROM_ABI constexpr const _CharT*
185 __parse_alternate_form(const _CharT* __begin, _Flags& __flags) noexcept {
186   if (*__begin == _CharT('#')) {
187     __flags.__alternate_form = true;
188     ++__begin;
189   }
190 
191   return __begin;
192 }
193 
194 template <class _CharT>
195 _LIBCPP_HIDE_FROM_ABI constexpr const _CharT*
196 __parse_zero_padding(const _CharT* __begin, _Flags& __flags) noexcept {
197   if (*__begin == _CharT('0')) {
198     __flags.__zero_padding = true;
199     ++__begin;
200   }
201 
202   return __begin;
203 }
204 
205 template <class _CharT>
206 _LIBCPP_HIDE_FROM_ABI constexpr __format::__parse_number_result< _CharT>
207 __parse_arg_id(const _CharT* __begin, const _CharT* __end, auto& __parse_ctx) {
208   // This function is a wrapper to call the real parser. But it does the
209   // validation for the pre-conditions and post-conditions.
210   if (__begin == __end)
211     __throw_format_error("End of input while parsing format-spec arg-id");
212 
213   __format::__parse_number_result __r =
214       __format::__parse_arg_id(__begin, __end, __parse_ctx);
215 
216   if (__r.__ptr == __end || *__r.__ptr != _CharT('}'))
217     __throw_format_error("Invalid arg-id");
218 
219   ++__r.__ptr;
220   return __r;
221 }
222 
223 template <class _Context>
224 _LIBCPP_HIDE_FROM_ABI constexpr uint32_t
225 __substitute_arg_id(basic_format_arg<_Context> __arg) {
226   return visit_format_arg(
227       [](auto __arg) -> uint32_t {
228         using _Type = decltype(__arg);
229         if constexpr (integral<_Type>) {
230           if constexpr (signed_integral<_Type>) {
231             if (__arg < 0)
232               __throw_format_error("A format-spec arg-id replacement shouldn't "
233                                    "have a negative value");
234           }
235 
236           using _CT = common_type_t<_Type, decltype(__format::__number_max)>;
237           if (static_cast<_CT>(__arg) >
238               static_cast<_CT>(__format::__number_max))
239             __throw_format_error("A format-spec arg-id replacement exceeds "
240                                  "the maximum supported value");
241 
242           return __arg;
243         } else if constexpr (same_as<_Type, monostate>)
244           __throw_format_error("Argument index out of bounds");
245         else
246           __throw_format_error("A format-spec arg-id replacement argument "
247                                "isn't an integral type");
248       },
249       __arg);
250 }
251 
252 class _LIBCPP_TYPE_VIS __parser_width {
253 public:
254   /** Contains a width or an arg-id. */
255   uint32_t __width : 31 {0};
256   /** Determines whether the value stored is a width or an arg-id. */
257   uint32_t __width_as_arg : 1 {0};
258 
259 protected:
260   /**
261    * Does the supplied std-format-spec contain a width field?
262    *
263    * When the field isn't present there's no padding required. This can be used
264    * to optimize the formatting.
265    */
266   constexpr bool __has_width_field() const noexcept {
267     return __width_as_arg || __width;
268   }
269 
270   /**
271    * Does the supplied width field contain an arg-id?
272    *
273    * If @c true the formatter needs to call @ref __substitute_width_arg_id.
274    */
275   constexpr bool __width_needs_substitution() const noexcept {
276     return __width_as_arg;
277   }
278 
279   template <class _CharT>
280   _LIBCPP_HIDE_FROM_ABI constexpr const _CharT*
281   __parse(const _CharT* __begin, const _CharT* __end, auto& __parse_ctx) {
282     if (*__begin == _CharT('0'))
283       __throw_format_error(
284           "A format-spec width field shouldn't have a leading zero");
285 
286     if (*__begin == _CharT('{')) {
287       __format::__parse_number_result __r =
288           __parse_arg_id(++__begin, __end, __parse_ctx);
289       __width = __r.__value;
290       __width_as_arg = 1;
291       return __r.__ptr;
292     }
293 
294     if (*__begin < _CharT('0') || *__begin > _CharT('9'))
295       return __begin;
296 
297     __format::__parse_number_result __r =
298         __format::__parse_number(__begin, __end);
299     __width = __r.__value;
300     _LIBCPP_ASSERT(__width != 0,
301                    "A zero value isn't allowed and should be impossible, "
302                    "due to validations in this function");
303     return __r.__ptr;
304   }
305 
306   _LIBCPP_HIDE_FROM_ABI constexpr void __substitute_width_arg_id(auto __arg) {
307     _LIBCPP_ASSERT(__width_as_arg == 1,
308                    "Substitute width called when no substitution is required");
309 
310     // The clearing of the flag isn't required but looks better when debugging
311     // the code.
312     __width_as_arg = 0;
313     __width = __substitute_arg_id(__arg);
314     if (__width == 0)
315       __throw_format_error(
316           "A format-spec width field replacement should have a positive value");
317   }
318 };
319 
320 class _LIBCPP_TYPE_VIS __parser_precision {
321 public:
322   /** Contains a precision or an arg-id. */
323   uint32_t __precision : 31 {__format::__number_max};
324   /**
325    * Determines whether the value stored is a precision or an arg-id.
326    *
327    * @note Since @ref __precision == @ref __format::__number_max is a valid
328    * value, the default value contains an arg-id of INT32_MAX. (This number of
329    * arguments isn't supported by compilers.)  This is used to detect whether
330    * the std-format-spec contains a precision field.
331    */
332   uint32_t __precision_as_arg : 1 {1};
333 
334 protected:
335   /**
336    * Does the supplied std-format-spec contain a precision field?
337    *
338    * When the field isn't present there's no truncating required. This can be
339    * used to optimize the formatting.
340    */
341   constexpr bool __has_precision_field() const noexcept {
342 
343     return __precision_as_arg == 0 ||             // Contains a value?
344            __precision != __format::__number_max; // The arg-id is valid?
345   }
346 
347   /**
348    * Does the supplied precision field contain an arg-id?
349    *
350    * If @c true the formatter needs to call @ref __substitute_precision_arg_id.
351    */
352   constexpr bool __precision_needs_substitution() const noexcept {
353     return __precision_as_arg && __precision != __format::__number_max;
354   }
355 
356   template <class _CharT>
357   _LIBCPP_HIDE_FROM_ABI constexpr const _CharT*
358   __parse(const _CharT* __begin, const _CharT* __end, auto& __parse_ctx) {
359     if (*__begin != _CharT('.'))
360       return __begin;
361 
362     ++__begin;
363     if (__begin == __end)
364       __throw_format_error("End of input while parsing format-spec precision");
365 
366     if (*__begin == _CharT('{')) {
367       __format::__parse_number_result __arg_id =
368           __parse_arg_id(++__begin, __end, __parse_ctx);
369       _LIBCPP_ASSERT(__arg_id.__value != __format::__number_max,
370                      "Unsupported number of arguments, since this number of "
371                      "arguments is used a special value");
372       __precision = __arg_id.__value;
373       return __arg_id.__ptr;
374     }
375 
376     if (*__begin < _CharT('0') || *__begin > _CharT('9'))
377       __throw_format_error(
378           "The format-spec precision field doesn't contain a value or arg-id");
379 
380     __format::__parse_number_result __r =
381         __format::__parse_number(__begin, __end);
382     __precision = __r.__value;
383     __precision_as_arg = 0;
384     return __r.__ptr;
385   }
386 
387   _LIBCPP_HIDE_FROM_ABI constexpr void __substitute_precision_arg_id(
388       auto __arg) {
389     _LIBCPP_ASSERT(
390         __precision_as_arg == 1 && __precision != __format::__number_max,
391         "Substitute precision called when no substitution is required");
392 
393     // The clearing of the flag isn't required but looks better when debugging
394     // the code.
395     __precision_as_arg = 0;
396     __precision = __substitute_arg_id(__arg);
397   }
398 };
399 
400 template <class _CharT>
401 _LIBCPP_HIDE_FROM_ABI constexpr const _CharT*
402 __parse_locale_specific_form(const _CharT* __begin, _Flags& __flags) noexcept {
403   if (*__begin == _CharT('L')) {
404     __flags.__locale_specific_form = true;
405     ++__begin;
406   }
407 
408   return __begin;
409 }
410 
411 template <class _CharT>
412 _LIBCPP_HIDE_FROM_ABI constexpr const _CharT*
413 __parse_type(const _CharT* __begin, _Flags& __flags) {
414 
415   // Determines the type. It does not validate whether the selected type is
416   // valid. Most formatters have optional fields that are only allowed for
417   // certain types. These parsers need to do validation after the type has
418   // been parsed. So its easier to implement the validation for all types in
419   // the specific parse function.
420   switch (*__begin) {
421   case 'A':
422     __flags.__type = _Flags::_Type::__float_hexadecimal_upper_case;
423     break;
424   case 'B':
425     __flags.__type = _Flags::_Type::__binary_upper_case;
426     break;
427   case 'E':
428     __flags.__type = _Flags::_Type::__scientific_upper_case;
429     break;
430   case 'F':
431     __flags.__type = _Flags::_Type::__fixed_upper_case;
432     break;
433   case 'G':
434     __flags.__type = _Flags::_Type::__general_upper_case;
435     break;
436   case 'X':
437     __flags.__type = _Flags::_Type::__hexadecimal_upper_case;
438     break;
439   case 'a':
440     __flags.__type = _Flags::_Type::__float_hexadecimal_lower_case;
441     break;
442   case 'b':
443     __flags.__type = _Flags::_Type::__binary_lower_case;
444     break;
445   case 'c':
446     __flags.__type = _Flags::_Type::__char;
447     break;
448   case 'd':
449     __flags.__type = _Flags::_Type::__decimal;
450     break;
451   case 'e':
452     __flags.__type = _Flags::_Type::__scientific_lower_case;
453     break;
454   case 'f':
455     __flags.__type = _Flags::_Type::__fixed_lower_case;
456     break;
457   case 'g':
458     __flags.__type = _Flags::_Type::__general_lower_case;
459     break;
460   case 'o':
461     __flags.__type = _Flags::_Type::__octal;
462     break;
463   case 'p':
464     __flags.__type = _Flags::_Type::__pointer;
465     break;
466   case 's':
467     __flags.__type = _Flags::_Type::__string;
468     break;
469   case 'x':
470     __flags.__type = _Flags::_Type::__hexadecimal_lower_case;
471     break;
472   default:
473     return __begin;
474   }
475   return ++__begin;
476 }
477 
478 /**
479  * The parser for the std-format-spec.
480  *
481  * [format.string.std]/1 specifies the std-format-spec:
482  *   fill-and-align sign # 0 width precision L type
483  *
484  * All these fields are optional. Whether these fields can be used depend on:
485  * - The type supplied to the format string.
486  *   E.g. A string never uses the sign field so the field may not be set.
487  *   This constrain is validated by the parsers in this file.
488  * - The supplied value for the optional type field.
489  *   E.g. A int formatted as decimal uses the sign field.
490  *   When formatted as a char the sign field may no longer be set.
491  *   This constrain isn't validated by the parsers in this file.
492  *
493  * The base classes are ordered to minimize the amount of padding.
494  *
495  * This implements the parser for the string types.
496  */
497 template <class _CharT>
498 class _LIBCPP_TEMPLATE_VIS __parser_string
499     : public __parser_width,              // provides __width(|as_arg)
500       public __parser_precision,          // provides __precision(|as_arg)
501       public __parser_fill_align<_CharT>, // provides __fill and uses __flags
502       public _Flags                       // provides __flags
503 {
504 public:
505   using char_type = _CharT;
506 
507   _LIBCPP_HIDE_FROM_ABI constexpr __parser_string() {
508     this->__alignment = _Flags::_Alignment::__left;
509   }
510 
511   /**
512    * The low-level std-format-spec parse function.
513    *
514    * @pre __begin points at the beginning of the std-format-spec. This means
515    * directly after the ':'.
516    * @pre The std-format-spec parses the entire input, or the first unmatched
517    * character is a '}'.
518    *
519    * @returns The iterator pointing at the last parsed character.
520    */
521   _LIBCPP_HIDE_FROM_ABI constexpr auto parse(auto& __parse_ctx)
522       -> decltype(__parse_ctx.begin()) {
523     auto __it = __parse(__parse_ctx);
524     __process_display_type();
525     return __it;
526   }
527 
528 private:
529   /**
530    * Parses the std-format-spec.
531    *
532    * @throws __throw_format_error When @a __parse_ctx contains an ill-formed
533    *                               std-format-spec.
534    *
535    * @returns An iterator to the end of input or point at the closing '}'.
536    */
537   _LIBCPP_HIDE_FROM_ABI constexpr auto __parse(auto& __parse_ctx)
538       -> decltype(__parse_ctx.begin()) {
539 
540     auto __begin = __parse_ctx.begin();
541     auto __end = __parse_ctx.end();
542     if (__begin == __end)
543       return __begin;
544 
545     __begin = __parser_fill_align<_CharT>::__parse(__begin, __end,
546                                                    static_cast<_Flags&>(*this));
547     if (__begin == __end)
548       return __begin;
549 
550     __begin = __parser_width::__parse(__begin, __end, __parse_ctx);
551     if (__begin == __end)
552       return __begin;
553 
554     __begin = __parser_precision::__parse(__begin, __end, __parse_ctx);
555     if (__begin == __end)
556       return __begin;
557 
558     __begin = __parse_type(__begin, static_cast<_Flags&>(*this));
559 
560     if (__begin != __end && *__begin != _CharT('}'))
561       __throw_format_error(
562           "The format-spec should consume the input or end with a '}'");
563 
564     return __begin;
565   }
566 
567   /** Processes the parsed std-format-spec based on the parsed display type. */
568   _LIBCPP_HIDE_FROM_ABI constexpr void __process_display_type() {
569     switch (this->__type) {
570     case _Flags::_Type::__default:
571     case _Flags::_Type::__string:
572       break;
573 
574     default:
575       __throw_format_error("The format-spec type has a type not supported for "
576                            "a string argument");
577     }
578   }
579 };
580 
581 /**
582  * The parser for the std-format-spec.
583  *
584  * This implements the parser for the integral types. This includes the
585  * character type and boolean type.
586  *
587  * See @ref __parser_string.
588  */
589 template <class _CharT>
590 class _LIBCPP_TEMPLATE_VIS __parser_integral
591     : public __parser_width,              // provides __width(|as_arg)
592       public __parser_fill_align<_CharT>, // provides __fill and uses __flags
593       public _Flags                       // provides __flags
594 {
595 public:
596   using char_type = _CharT;
597 
598 protected:
599   /**
600    * The low-level std-format-spec parse function.
601    *
602    * @pre __begin points at the beginning of the std-format-spec. This means
603    * directly after the ':'.
604    * @pre The std-format-spec parses the entire input, or the first unmatched
605    * character is a '}'.
606    *
607    * @returns The iterator pointing at the last parsed character.
608    */
609   _LIBCPP_HIDE_FROM_ABI constexpr auto __parse(auto& __parse_ctx)
610       -> decltype(__parse_ctx.begin()) {
611     auto __begin = __parse_ctx.begin();
612     auto __end = __parse_ctx.end();
613     if (__begin == __end)
614       return __begin;
615 
616     __begin = __parser_fill_align<_CharT>::__parse(__begin, __end,
617                                                    static_cast<_Flags&>(*this));
618     if (__begin == __end)
619       return __begin;
620 
621     __begin = __parse_sign(__begin, static_cast<_Flags&>(*this));
622     if (__begin == __end)
623       return __begin;
624 
625     __begin = __parse_alternate_form(__begin, static_cast<_Flags&>(*this));
626     if (__begin == __end)
627       return __begin;
628 
629     __begin = __parse_zero_padding(__begin, static_cast<_Flags&>(*this));
630     if (__begin == __end)
631       return __begin;
632 
633     __begin = __parser_width::__parse(__begin, __end, __parse_ctx);
634     if (__begin == __end)
635       return __begin;
636 
637     __begin =
638         __parse_locale_specific_form(__begin, static_cast<_Flags&>(*this));
639     if (__begin == __end)
640       return __begin;
641 
642     __begin = __parse_type(__begin, static_cast<_Flags&>(*this));
643 
644     if (__begin != __end && *__begin != _CharT('}'))
645       __throw_format_error(
646           "The format-spec should consume the input or end with a '}'");
647 
648     return __begin;
649   }
650 
651   /**
652    * Handles the post-parsing updates for the integer types.
653    *
654    * Updates the zero-padding and alignment for integer types.
655    *
656    * [format.string.std]/13
657    *   If the 0 character and an align option both appear, the 0 character is
658    *   ignored.
659    *
660    * For the formatter a @ref __default alignment means zero-padding. Update
661    * the alignment based on parsed format string.
662    */
663   _LIBCPP_HIDE_FROM_ABI constexpr void __handle_integer() noexcept {
664     this->__zero_padding &= this->__alignment == _Flags::_Alignment::__default;
665     if (!this->__zero_padding &&
666         this->__alignment == _Flags::_Alignment::__default)
667       this->__alignment = _Flags::_Alignment::__right;
668   }
669 
670   /**
671    * Handles the post-parsing updates for the character types.
672    *
673    * Sets the alignment and validates the format flags set for a character type.
674    *
675    * At the moment the validation for a character and a Boolean behave the
676    * same, but this may change in the future.
677    * Specifically at the moment the locale-specific form is allowed for the
678    * char output type, but it has no effect on the output.
679    */
680   _LIBCPP_HIDE_FROM_ABI constexpr void __handle_char() { __handle_bool(); }
681 
682   /**
683    * Handles the post-parsing updates for the Boolean types.
684    *
685    * Sets the alignment and validates the format flags set for a Boolean type.
686    */
687   _LIBCPP_HIDE_FROM_ABI constexpr void __handle_bool() {
688     if (this->__sign != _Flags::_Sign::__default)
689       __throw_format_error("A sign field isn't allowed in this format-spec");
690 
691     if (this->__alternate_form)
692       __throw_format_error(
693           "An alternate form field isn't allowed in this format-spec");
694 
695     if (this->__zero_padding)
696       __throw_format_error(
697           "A zero-padding field isn't allowed in this format-spec");
698 
699     if (this->__alignment == _Flags::_Alignment::__default)
700       this->__alignment = _Flags::_Alignment::__left;
701   }
702 };
703 
704 // TODO FMT Add a parser for floating-point values.
705 // TODO FMT Add a parser for pointer values.
706 
707 /** Helper struct returned from @ref __get_string_alignment. */
708 template <class _CharT>
709 struct _LIBCPP_TEMPLATE_VIS __string_alignment {
710   /** Points beyond the last character to write to the output. */
711   const _CharT* __last;
712   /**
713    * The estimated number of columns in the output or 0.
714    *
715    * Only when the output needs to be aligned it's required to know the exact
716    * number of columns in the output. So if the formatted output has only a
717    * minimum width the exact size isn't important. It's only important to know
718    * the minimum has been reached. The minimum width is the width specified in
719    * the format-spec.
720    *
721    * For example in this code @code std::format("{:10}", MyString); @endcode
722    * the width estimation can stop once the algorithm has determined the output
723    * width is 10 columns.
724    *
725    * So if:
726    * * @ref __align == @c true the @ref __size is the estimated number of
727    *   columns required.
728    * * @ref __align == @c false the @ref __size is the estimated number of
729    *   columns required or 0 when the estimation algorithm stopped prematurely.
730    */
731   ptrdiff_t __size;
732   /**
733    * Does the output need to be aligned.
734    *
735    * When alignment is needed the output algorithm needs to add the proper
736    * padding. Else the output algorithm just needs to copy the input up to
737    * @ref __last.
738    */
739   bool __align;
740 };
741 
742 #ifndef _LIBCPP_HAS_NO_UNICODE
743 namespace __detail {
744 
745 /**
746  * Unicode column width estimates.
747  *
748  * Unicode can be stored in several formats: UTF-8, UTF-16, and UTF-32.
749  * Depending on format the relation between the number of code units stored and
750  * the number of output columns differs. The first relation is the number of
751  * code units forming a code point. (The text assumes the code units are
752  * unsigned.)
753  * - UTF-8 The number of code units is between one and four. The first 127
754  *   Unicode code points match the ASCII character set. When the highest bit is
755  *   set it means the code point has more than one code unit.
756  * - UTF-16: The number of code units is between 1 and 2. When the first
757  *   code unit is in the range [0xd800,0xdfff) it means the code point uses two
758  *   code units.
759  * - UTF-32: The number of code units is always one.
760  *
761  * The code point to the number of columns isn't well defined. The code uses the
762  * estimations defined in [format.string.std]/11. This list might change in the
763  * future.
764  *
765  * The algorithm of @ref __get_string_alignment uses two different scanners:
766  * - The simple scanner @ref __estimate_column_width_fast. This scanner assumes
767  *   1 code unit is 1 column. This scanner stops when it can't be sure the
768  *   assumption is valid:
769  *   - UTF-8 when the code point is encoded in more than 1 code unit.
770  *   - UTF-16 and UTF-32 when the first multi-column code point is encountered.
771  *     (The code unit's value is lower than 0xd800 so the 2 code unit encoding
772  *     is irrelevant for this scanner.)
773  *   Due to these assumptions the scanner is faster than the full scanner. It
774  *   can process all text only containing ASCII. For UTF-16/32 it can process
775  *   most (all?) European languages. (Note the set it can process might be
776  *   reduced in the future, due to updates in the scanning rules.)
777  * - The full scanner @ref __estimate_column_width. This scanner, if needed,
778  *   converts multiple code units into one code point then converts the code
779  *   point to a column width.
780  *
781  * See also:
782  * - [format.string.general]/11
783  * - https://en.wikipedia.org/wiki/UTF-8#Encoding
784  * - https://en.wikipedia.org/wiki/UTF-16#U+D800_to_U+DFFF
785  */
786 
787 /**
788  * The first 2 column code point.
789  *
790  * This is the point where the fast UTF-16/32 scanner needs to stop processing.
791  */
792 inline constexpr uint32_t __two_column_code_point = 0x1100;
793 
794 /** Helper concept for an UTF-8 character type. */
795 template <class _CharT>
796 concept __utf8_character = same_as<_CharT, char> || same_as<_CharT, char8_t>;
797 
798 /** Helper concept for an UTF-16 character type. */
799 template <class _CharT>
800 concept __utf16_character = (same_as<_CharT, wchar_t> && sizeof(wchar_t) == 2) || same_as<_CharT, char16_t>;
801 
802 /** Helper concept for an UTF-32 character type. */
803 template <class _CharT>
804 concept __utf32_character = (same_as<_CharT, wchar_t> && sizeof(wchar_t) == 4) || same_as<_CharT, char32_t>;
805 
806 /** Helper concept for an UTF-16 or UTF-32 character type. */
807 template <class _CharT>
808 concept __utf16_or_32_character = __utf16_character<_CharT> || __utf32_character<_CharT>;
809 
810 /**
811  * Converts a code point to the column width.
812  *
813  * The estimations are conforming to [format.string.general]/11
814  *
815  * This version expects a value less than 0x1'0000, which is a 3-byte UTF-8
816  * character.
817  */
818 _LIBCPP_HIDE_FROM_ABI inline constexpr int __column_width_3(uint32_t __c) noexcept {
819   _LIBCPP_ASSERT(__c < 0x1'0000,
820                  "Use __column_width_4 or __column_width for larger values");
821 
822   // clang-format off
823   return 1 + (__c >= 0x1100 && (__c <= 0x115f ||
824              (__c >= 0x2329 && (__c <= 0x232a ||
825              (__c >= 0x2e80 && (__c <= 0x303e ||
826              (__c >= 0x3040 && (__c <= 0xa4cf ||
827              (__c >= 0xac00 && (__c <= 0xd7a3 ||
828              (__c >= 0xf900 && (__c <= 0xfaff ||
829              (__c >= 0xfe10 && (__c <= 0xfe19 ||
830              (__c >= 0xfe30 && (__c <= 0xfe6f ||
831              (__c >= 0xff00 && (__c <= 0xff60 ||
832              (__c >= 0xffe0 && (__c <= 0xffe6
833              ))))))))))))))))))));
834   // clang-format on
835 }
836 
837 /**
838  * @overload
839  *
840  * This version expects a value greater than or equal to 0x1'0000, which is a
841  * 4-byte UTF-8 character.
842  */
843 _LIBCPP_HIDE_FROM_ABI inline constexpr int __column_width_4(uint32_t __c) noexcept {
844   _LIBCPP_ASSERT(__c >= 0x1'0000,
845                  "Use __column_width_3 or __column_width for smaller values");
846 
847   // clang-format off
848   return 1 + (__c >= 0x1'f300 && (__c <= 0x1'f64f ||
849              (__c >= 0x1'f900 && (__c <= 0x1'f9ff ||
850              (__c >= 0x2'0000 && (__c <= 0x2'fffd ||
851              (__c >= 0x3'0000 && (__c <= 0x3'fffd
852              ))))))));
853   // clang-format on
854 }
855 
856 /**
857  * @overload
858  *
859  * The general case, accepting all values.
860  */
861 _LIBCPP_HIDE_FROM_ABI inline constexpr int __column_width(uint32_t __c) noexcept {
862   if (__c < 0x1'0000)
863     return __column_width_3(__c);
864 
865   return __column_width_4(__c);
866 }
867 
868 /**
869  * Estimate the column width for the UTF-8 sequence using the fast algorithm.
870  */
871 template <__utf8_character _CharT>
872 _LIBCPP_HIDE_FROM_ABI constexpr const _CharT*
873 __estimate_column_width_fast(const _CharT* __first,
874                              const _CharT* __last) noexcept {
875   return _VSTD::find_if(__first, __last,
876                         [](unsigned char __c) { return __c & 0x80; });
877 }
878 
879 /**
880  * @overload
881  *
882  * The implementation for UTF-16/32.
883  */
884 template <__utf16_or_32_character _CharT>
885 _LIBCPP_HIDE_FROM_ABI constexpr const _CharT*
886 __estimate_column_width_fast(const _CharT* __first,
887                              const _CharT* __last) noexcept {
888   return _VSTD::find_if(__first, __last,
889                         [](uint32_t __c) { return __c >= 0x1100; });
890 }
891 
892 template <class _CharT>
893 struct _LIBCPP_TEMPLATE_VIS __column_width_result {
894   /** The number of output columns. */
895   size_t __width;
896   /**
897    * The last parsed element.
898    *
899    * This limits the original output to fit in the wanted number of columns.
900    */
901   const _CharT* __ptr;
902 };
903 
904 /**
905  * Small helper to determine the width of malformed Unicode.
906  *
907  * @note This function's only needed for UTF-8. During scanning UTF-8 there
908  * are multiple place where it can be detected that the Unicode is malformed.
909  * UTF-16 only requires 1 test and UTF-32 requires no testing.
910  */
911 template <__utf8_character _CharT>
912 _LIBCPP_HIDE_FROM_ABI constexpr __column_width_result<_CharT>
913 __estimate_column_width_malformed(const _CharT* __first, const _CharT* __last,
914                                   size_t __maximum, size_t __result) noexcept {
915   size_t __size = __last - __first;
916   size_t __n = _VSTD::min(__size, __maximum);
917   return {__result + __n, __first + __n};
918 }
919 
920 /**
921  * Determines the number of output columns needed to render the input.
922  *
923  * @note When the scanner encounters malformed Unicode it acts as-if every code
924  * unit at the end of the input is one output column. It's expected the output
925  * terminal will replace these malformed code units with a one column
926  * replacement characters.
927  *
928  * @param __first   Points to the first element of the input range.
929  * @param __last    Points beyond the last element of the input range.
930  * @param __maximum The maximum number of output columns. The returned number
931  *                  of estimated output columns will not exceed this value.
932  */
933 template <__utf8_character _CharT>
934 _LIBCPP_HIDE_FROM_ABI constexpr __column_width_result<_CharT>
935 __estimate_column_width(const _CharT* __first, const _CharT* __last,
936                         size_t __maximum) noexcept {
937   size_t __result = 0;
938 
939   while (__first != __last) {
940     // Based on the number of leading 1 bits the number of code units in the
941     // code point can be determined. See
942     // https://en.wikipedia.org/wiki/UTF-8#Encoding
943     switch (_VSTD::countl_one(static_cast<unsigned char>(*__first))) {
944     case 0: // 1-code unit encoding: all 1 column
945       ++__result;
946       ++__first;
947       break;
948 
949     case 2: // 2-code unit encoding: all 1 column
950       // Malformed Unicode.
951       if (__last - __first < 2) [[unlikely]]
952         return __estimate_column_width_malformed(__first, __last, __maximum,
953                                                  __result);
954       __first += 2;
955       ++__result;
956       break;
957 
958     case 3: // 3-code unit encoding: either 1 or 2 columns
959       // Malformed Unicode.
960       if (__last - __first < 3) [[unlikely]]
961         return __estimate_column_width_malformed(__first, __last, __maximum,
962                                                  __result);
963       {
964         uint32_t __c = static_cast<unsigned char>(*__first++) & 0x0f;
965         __c <<= 6;
966         __c |= static_cast<unsigned char>(*__first++) & 0x3f;
967         __c <<= 6;
968         __c |= static_cast<unsigned char>(*__first++) & 0x3f;
969         __result += __column_width_3(__c);
970         if (__result > __maximum)
971           return {__result - 2, __first - 3};
972       }
973       break;
974     case 4: // 4-code unit encoding: either 1 or 2 columns
975       // Malformed Unicode.
976       if (__last - __first < 4) [[unlikely]]
977         return __estimate_column_width_malformed(__first, __last, __maximum,
978                                                  __result);
979       {
980         uint32_t __c = static_cast<unsigned char>(*__first++) & 0x07;
981         __c <<= 6;
982         __c |= static_cast<unsigned char>(*__first++) & 0x3f;
983         __c <<= 6;
984         __c |= static_cast<unsigned char>(*__first++) & 0x3f;
985         __c <<= 6;
986         __c |= static_cast<unsigned char>(*__first++) & 0x3f;
987         __result += __column_width_4(__c);
988         if (__result > __maximum)
989           return {__result - 2, __first - 4};
990       }
991       break;
992     default:
993       // Malformed Unicode.
994       return __estimate_column_width_malformed(__first, __last, __maximum,
995                                                __result);
996     }
997 
998     if (__result >= __maximum)
999       return {__result, __first};
1000   }
1001   return {__result, __first};
1002 }
1003 
1004 template <__utf16_character _CharT>
1005 _LIBCPP_HIDE_FROM_ABI constexpr __column_width_result<_CharT>
1006 __estimate_column_width(const _CharT* __first, const _CharT* __last,
1007                         size_t __maximum) noexcept {
1008   size_t __result = 0;
1009 
1010   while (__first != __last) {
1011     uint32_t __c = *__first;
1012     // Is the code unit part of a surrogate pair? See
1013     // https://en.wikipedia.org/wiki/UTF-16#U+D800_to_U+DFFF
1014     if (__c >= 0xd800 && __c <= 0xDfff) {
1015       // Malformed Unicode.
1016       if (__last - __first < 2) [[unlikely]]
1017         return {__result + 1, __first + 1};
1018 
1019       __c -= 0xd800;
1020       __c <<= 10;
1021       __c += (*(__first + 1) - 0xdc00);
1022       __c += 0x10'000;
1023 
1024       __result += __column_width_4(__c);
1025       if (__result > __maximum)
1026         return {__result - 2, __first};
1027       __first += 2;
1028     } else {
1029       __result += __column_width_3(__c);
1030       if (__result > __maximum)
1031         return {__result - 2, __first};
1032       ++__first;
1033     }
1034 
1035     if (__result >= __maximum)
1036       return {__result, __first};
1037   }
1038 
1039   return {__result, __first};
1040 }
1041 
1042 template <__utf32_character _CharT>
1043 _LIBCPP_HIDE_FROM_ABI constexpr __column_width_result<_CharT>
1044 __estimate_column_width(const _CharT* __first, const _CharT* __last,
1045                         size_t __maximum) noexcept {
1046   size_t __result = 0;
1047 
1048   while (__first != __last) {
1049     wchar_t __c = *__first;
1050     __result += __column_width(__c);
1051 
1052     if (__result > __maximum)
1053       return {__result - 2, __first};
1054 
1055     ++__first;
1056     if (__result >= __maximum)
1057       return {__result, __first};
1058   }
1059 
1060   return {__result, __first};
1061 }
1062 
1063 } // namespace __detail
1064 
1065 template <class _CharT>
1066 _LIBCPP_HIDE_FROM_ABI constexpr __string_alignment<_CharT>
1067 __get_string_alignment(const _CharT* __first, const _CharT* __last,
1068                        ptrdiff_t __width, ptrdiff_t __precision) noexcept {
1069   _LIBCPP_ASSERT(__width != 0 || __precision != -1,
1070                  "The function has no effect and shouldn't be used");
1071 
1072   // TODO FMT There might be more optimizations possible:
1073   // If __precision == __format::__number_max and the encoding is:
1074   // * UTF-8  : 4 * (__last - __first) >= __width
1075   // * UTF-16 : 2 * (__last - __first) >= __width
1076   // * UTF-32 : (__last - __first) >= __width
1077   // In these cases it's certain the output is at least the requested width.
1078   // It's unknown how often this happens in practice. For now the improvement
1079   // isn't implemented.
1080 
1081   /*
1082    * First assume there are no special Unicode code units in the input.
1083    * - Apply the precision (this may reduce the size of the input). When
1084    *   __precison == -1 this step is omitted.
1085    * - Scan for special code units in the input.
1086    * If our assumption was correct the __pos will be at the end of the input.
1087    */
1088   const ptrdiff_t __length = __last - __first;
1089   const _CharT* __limit =
1090       __first +
1091       (__precision == -1 ? __length : _VSTD::min(__length, __precision));
1092   ptrdiff_t __size = __limit - __first;
1093   const _CharT* __pos =
1094       __detail::__estimate_column_width_fast(__first, __limit);
1095 
1096   if (__pos == __limit)
1097     return {__limit, __size, __size < __width};
1098 
1099   /*
1100    * Our assumption was wrong, there are special Unicode code units.
1101    * The range [__first, __pos) contains a set of code units with the
1102    * following property:
1103    *      Every _CharT in the range will be rendered in 1 column.
1104    *
1105    * If there's no maximum width and the parsed size already exceeds the
1106    *   minimum required width. The real size isn't important. So bail out.
1107    */
1108   if (__precision == -1 && (__pos - __first) >= __width)
1109     return {__last, 0, false};
1110 
1111   /* If there's a __precision, truncate the output to that width. */
1112   ptrdiff_t __prefix = __pos - __first;
1113   if (__precision != -1) {
1114     _LIBCPP_ASSERT(__precision > __prefix, "Logic error.");
1115     auto __lengh_info = __detail::__estimate_column_width(
1116         __pos, __last, __precision - __prefix);
1117     __size = __lengh_info.__width + __prefix;
1118     return {__lengh_info.__ptr, __size, __size < __width};
1119   }
1120 
1121   /* Else use __width to determine the number of required padding characters. */
1122   _LIBCPP_ASSERT(__width > __prefix, "Logic error.");
1123   /*
1124    * The column width is always one or two columns. For the precision the wanted
1125    * column width is the maximum, for the width it's the minimum. Using the
1126    * width estimation with its truncating behavior will result in the wrong
1127    * result in the following case:
1128    * - The last code unit processed requires two columns and exceeds the
1129    *   maximum column width.
1130    * By increasing the __maximum by one avoids this issue. (It means it may
1131    * pass one code point more than required to determine the proper result;
1132    * that however isn't a problem for the algorithm.)
1133    */
1134   size_t __maximum = 1 + __width - __prefix;
1135   auto __lengh_info =
1136       __detail::__estimate_column_width(__pos, __last, __maximum);
1137   if (__lengh_info.__ptr != __last) {
1138     // Consumed the width number of code units. The exact size of the string
1139     // is unknown. We only know we don't need to align the output.
1140     _LIBCPP_ASSERT(static_cast<ptrdiff_t>(__lengh_info.__width + __prefix) >=
1141                        __width,
1142                    "Logic error");
1143     return {__last, 0, false};
1144   }
1145 
1146   __size = __lengh_info.__width + __prefix;
1147   return {__last, __size, __size < __width};
1148 }
1149 #else  // _LIBCPP_HAS_NO_UNICODE
1150 template <class _CharT>
1151 _LIBCPP_HIDE_FROM_ABI constexpr __string_alignment<_CharT>
1152 __get_string_alignment(const _CharT* __first, const _CharT* __last,
1153                        ptrdiff_t __width, ptrdiff_t __precision) noexcept {
1154   const ptrdiff_t __length = __last - __first;
1155   const _CharT* __limit =
1156       __first +
1157       (__precision == -1 ? __length : _VSTD::min(__length, __precision));
1158   ptrdiff_t __size = __limit - __first;
1159   return {__limit, __size, __size < __width};
1160 }
1161 #endif // _LIBCPP_HAS_NO_UNICODE
1162 
1163 } // namespace __format_spec
1164 
1165 # endif // !defined(_LIBCPP_HAS_NO_CONCEPTS)
1166 
1167 #endif //_LIBCPP_STD_VER > 17
1168 
1169 _LIBCPP_END_NAMESPACE_STD
1170 
1171 _LIBCPP_POP_MACROS
1172 
1173 #endif // _LIBCPP___FORMAT_PARSER_STD_FORMAT_SPEC_H
1174