aboutsummaryrefslogtreecommitdiff
path: root/libstdc++-v3/include
AgeCommit message (Collapse)AuthorFilesLines
2025-05-07libstdc++: Implement std::extents [PR107761].Luc Grosheintz1-0/+261
This implements std::extents from <mdspan> according to N4950 and contains partial progress towards PR107761. If an extent changes its type, there's a precondition in the standard, that the value is representable in the target integer type. This precondition is not checked at runtime. The precondition for 'extents::{static_,}extent' is that '__r < rank()'. For extents<T> this precondition is always violated and results in calling __builtin_trap. For all other specializations it's checked via __glibcxx_assert. PR libstdc++/107761 libstdc++-v3/ChangeLog: * include/std/mdspan (extents): New class. * src/c++23/std.cc.in: Add 'using std::extents'. Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-05-07libstdc++: Add header mdspan to the build-system.Luc Grosheintz4-0/+51
Creates a nearly empty header mdspan and adds it to the build-system and Doxygen config file. libstdc++-v3/ChangeLog: * doc/doxygen/user.cfg.in: Add <mdspan>. * include/Makefile.am: Ditto. * include/Makefile.in: Ditto. * include/precompiled/stdc++.h: Ditto. * include/std/mdspan: New file. Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-05-07libstdc++: Setup internal FTM for mdspan.Luc Grosheintz2-0/+18
Uses the FTM infrastructure to create an internal feature testing macro for partial availability of mdspan; which is then used to hide the contents of the header mdspan when compiling against a standard prior to C++23. libstdc++-v3/ChangeLog: * include/bits/version.def: Add internal feature testing macro __glibcxx_mdspan. * include/bits/version.h: Regenerate. Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-05-07libstdc++: Fix width computation for the chrono formatting [PR120114]Tomasz Kamiński1-2/+7
Use `__unicode::_field_width` to compute the field width of the output when writting the formatted output for std::chrono::types. This applies both to characters copied from format string, and one produced by localized formatting. We also use _Str_sink::view() instead of get(), which avoids copying the content of the buffer to std::string in case of small output. PR libstdc++/120114 libstdc++-v3/ChangeLog: * include/bits/chrono_io.h (__formatter_chrono::_M_format): Use __field_width. * testsuite/std/time/format/pr120114.cc: New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-05-06libstdc++: Rewrite atomic builtin checks [PR70560]Jonathan Wakely1-2/+2
Currently the GLIBCXX_ENABLE_ATOMIC_BUILTINS macro checks for a variety of __atomic built-ins for bool, short and int. If all those checks pass, then it defines _GLIBCXX_ATOMIC_BUILTINS and uses the definitions from config/cpu/generic/atomicity_builtins/atomicity.h for the non-inline versions of __exchange_and_add and __atomic_add that get compiled into libsupc++. However, the config/cpu/generic/atomicity_builtins/atomicity.h definitions only depend on __atomic_fetch_add not on __atomic_test_and_set or __atomic_compare_exchange. And they only operate on a variable of type _Atomic word, which is not necessarily one of bool, short or int (e.g. for sparcv9 _Atomic_word is 64-bit long). This means that for a target where _Atomic_word is int but there are no 1-byte or 2-byte atomic instructions, GLIBCXX_ENABLE_ATOMIC_BUILTINS will fail the checks for bool and short and not define the macro _GLIBCXX_ATOMIC_BUILTINS. That means that we will use a single global mutex for reference counting in the COW std::string and std::locale, even though we could use __atomic_fetch_add to do it lock-free. This commit removes most of the GLIBCXX_ENABLE_ATOMIC_BUILTINS checks, so that it only checks __atomic_fetch_add on _Atomic_word. The macro defined by GLIBCXX_ENABLE_ATOMIC_BUILTINS is renamed from _GLIBCXX_ATOMIC_BUILTINS to _GLIBCXX_ATOMIC_WORD_BUILTINS to better reflect what it really means. This will enable the inline versions of __exchange_and_add and __atomic_add for more targets. This is not an ABI change, because targets which didn't previously use the inline definitions of those functions made non-inlined calls to the functions in the library. If the definitions of those functions now start using atomics, that doesn't change the semantics for the code calling those functions. On affected targets, new code compiled after this change will see the _GLIBCXX_ATOMIC_WORD_BUILTINS macro and so will use the always-inline versions of __exchange_and_add and __atomic_add, which use __atomic_fetch_add directly. That is also compatible with older code which still calls the non-inline definitions, because those non-inline definitions now also use __atomic_fetch_add. The only configuration where this could be an ABI change is for a target which previously defined _GLIBCXX_ATOMIC_BUILTINS (because all the atomic built-ins for bool, short and int are supported), but which defines _Atomic_word to some other type for which __atomic_fetch_add is /not/ supported. Such a target would have called the inline functions using __atomic_fetch_add, which would actually have depended on libatomic (which is what the configure checks were supposed to prevent!). After this change, that target would not define the new macro, _GLIBCXX_ATOMIC_WORD_BUILTINS, and so would make non-inline calls into the library where __exchange_and_add and __atomic_add would use the global mutex. That would be an ABI break. I don't consider that a realistic scenario, because it wouldn't have made any sense to define _Atomic_word to a wider type than int, when doing so would have required libatomic to make libstdc++.so work. Surely such a target would have just used int for its _Atomic_word type. The GLIBCXX_ENABLE_BACKTRACE macro currently uses the glibcxx_ac_atomic_int variable defined by the checks that this commit removes from GLIBCXX_ENABLE_ATOMIC_BUILTINS. That wasn't a good check anyway, because libbacktrace actually depends on atomic loads+stores for pointers as well as int, and for atomic stores for size_t. This commit replaces the glibcxx_ac_atomic_int check with a proper test for all the required atomic operations on all three of int, void* and size_t. This ensures that the libbacktrace code used for std::stacktrace will either use native atomics, or implement those loads and stores only in terms of __sync_bool_compare_and_swap (possibly requiring that to come from libatomic or elsewhere). libstdc++-v3/ChangeLog: PR libstdc++/70560 PR libstdc++/119667 * acinclude.m4 (GLIBCXX_ENABLE_ATOMIC_BUILTINS): Only check for __atomic_fetch_add on _Atomic_word. Define new macro _GLIBCXX_ATOMIC_WORD_BUILTINS and stop defining macro _GLIBCXX_ATOMIC_BUILTINS. (GLIBCXX_ENABLE_BACKTRACE): Check for __atomic_load_n and __atomic_store_n on int, void* and size_t. * config.h.in: Regenerate. * configure: Regenerate. * configure.host: Fix typo in comment. * include/ext/atomicity.h (__exchange_and_add, __atomic_add): Depend on _GLIBCXX_ATOMIC_WORD_BUILTINS macro instead of old _GLIBCXX_ATOMIC_BUILTINS macro.
2025-05-06libstdc++: Fix <numeric> parallel algos for move-only values [PR117905]Jonathan Wakely3-29/+29
All of reduce, transform_reduce, exclusive_scan, and inclusive_scan, transform_exclusive_scan, and transform_inclusive_scan have a precondition that the type of init meets the Cpp17MoveConstructible requirements. It isn't required to be copy constructible, so when passing it to the next internal function it needs to be moved, not copied. We also need to move when creating local variables on the stack, and when returning as part of a pair. libstdc++-v3/ChangeLog: PR libstdc++/117905 * include/pstl/glue_numeric_impl.h (reduce, transform_reduce) (transform_reduce, inclusive_scan, transform_exclusive_scan) (transform_inclusive_scan): Use std::move for __init parameter. * include/pstl/numeric_impl.h (__brick_transform_reduce) (__pattern_transform_reduce, __brick_transform_scan) (__pattern_transform_scan): Likewise. * include/std/numeric (inclusive_scan, transform_exclusive_scan): Use std::move to create local copy of the first element. * testsuite/26_numerics/pstl/numeric_ops/108236.cc: Move test using move-only type to ... * testsuite/26_numerics/pstl/numeric_ops/move_only.cc: New test.
2025-05-06libstdc++: Fix -Wmismatched-tags warnings for _Safe_iterator [PR120112]Jonathan Wakely2-2/+2
This causes an ICE as shown in the PR, but it should be fixed in the library code anyway. libstdc++-v3/ChangeLog: PR c++/120112 * include/bits/ptr_traits.h (_Safe_iterator_base): Use class keyword in class-head of declaration. * include/debug/debug.h (_Safe_iterator): Likewise.
2025-05-06libstdc++: Add noexcept to some std::counted_iterator operationsJonathan Wakely1-6/+6
This was inspired by LWG 4245 but goes further. Anything which only reads or writes the _M_length member can be noexcept. That member is an iterator difference_type which means it's a signed integer type or the __max_diff_type integer-like class type, so all arithmetic and comparisons are non-throwing. libstdc++-v3/ChangeLog: * include/bits/stl_iterator.h (counted_iterator): Add noexcept to friend operators which only access the _M_length member. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-05-02libstdc++: Add missing feature-test macro in <memory>Dhruv Chawla1-0/+1
Per version.syn#2, <memory> is required to define __cpp_lib_addressof_constexpr as 201603L. Bootstrapped and tested on aarch64-linux-gnu. Signed-off-by: Dhruv Chawla <dhruvc@nvidia.com> libstdc++-v3/ChangeLog: * include/std/memory: Define __glibcxx_want_addressof_constexpr. * testsuite/20_util/headers/memory/version.cc: Test for macro value.
2025-04-30libstdc++: Fix _Padding_sink in case when predicted width is between ↵Tomasz Kamiński1-3/+4
padwidth and maxwidth [PR109162] The _Padding_sink was behaving incorrectly, when the predicted width (based on code units count) was higher than _M_maxwidth, but lower than _M_padwidth. In this case _M_update() returned without calling _M_force_update() and computing field width for Unicode encoding, because _M_buffering() returned 'true'. As a consequence we switched to _M_ignoring() mode, while storing a sequence with more code units but smaller field width than _M_maxwidth. We now call _M_force_update() if predicted width is greater or equal to either _M_padwidth or _M_maxwidth. This happened for existing test case on 32bit architecture. PR libstdc++/109162 libstdc++-v3/ChangeLog: * include/std/format (_Padding_sink::_M_update): Fixed condition for calling _M_force_update. * testsuite/std/format/debug.cc: Add test that reproduces this issue on 64bit architecture. * testsuite/std/format/ranges/sequence.cc: Another edge value test.
2025-04-29libstdc++: Use no_stdname for make_obj_using_allocator feature test macroJonathan Wakely2-1/+1
This is a non-standard feature test macro only used internally, so use the new no_stdname property for it. libstdc++-v3/ChangeLog: * include/bits/version.def (make_obj_using_allocator): Use no_stdname. * include/bits/version.h: Regenerate.
2025-04-29libstdc++: Use constexpr-if to slightly simplify <regex>Jonathan Wakely3-46/+40
This will hardly make a dent in the very slow compile times for <regex> but it seems worth doing anyway. libstdc++-v3/ChangeLog: * include/bits/regex_compiler.h: Replace _GLIBCXX17_CONSTEXPR with constexpr and disable diagnostics with pragmas. (_AnyMatcher::operator()): Use constexpr-if instead of tag dispatching. Postpone calls to _M_translate until after checking result of earlier calls. (_AnyMatcher::_M_apply): Remove both overloads. (_BracketMatcher::operator(), _BracketMatcher::_M_ready): Replace tag dispatching with 'if constexpr'. (_BracketMatcher::_M_apply(_CharT, true_type)): Remove. (_BracketMatcher::_M_apply(_CharT, false_type)): Remove second parameter. (_BracketMatcher::_M_make_cache): Remove both overloads. * include/bits/regex_compiler.tcc (_BracketMatcher::_M_apply): Remove second parameter. * include/bits/regex_executor.tcc: Replace _GLIBCXX17_CONSTEXPR with constexpr and disable diagnostics with pragmas. (_Executor::_M_handle_backref): Replace __glibcxx_assert with static_assert. (_Executor::_M_handle_accept): Mark _S_opcode_backref case as unreachable for non-DFS mode and do not instantiate _M_handle_backref for that case. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-29libstdc++: Optimize removal from unique assoc containers [PR112934]Barnabás Pőcze3-2/+19
Previously, calling erase(key) on both std::map and std::set would execute that same code that std::multi{map,set} would. However, doing that is unnecessary because std::{map,set} guarantee that all elements are unique. It is reasonable to expect that erase(key) is equivalent or better than: auto it = m.find(key); if (it != m.end()) m.erase(it); However, this was not the case. Fix that by adding a new function _Rb_tree<>::_M_erase_unique() that is essentially equivalent to the above snippet, and use this from both std::map and std::set. libstdc++-v3/ChangeLog: PR libstdc++/112934 * include/bits/stl_map.h (map::erase): Use _M_erase_unique. * include/bits/stl_set.h (set::erase): Likewise. * include/bits/stl_tree.h (_Rb_tree::_M_erase_unique): Add.
2025-04-29libstdc++: Fix availability of std::erase_if(std::flat_foo) [PR119427]Patrick Palka2-11/+45
These std::erase_if overloads were wrongly implemented as hidden friends, visible only via ADL, so erase_if(x) would work but not std::erase_if(x). PR libstdc++/119427 libstdc++-v3/ChangeLog: * include/std/flat_map (_Flat_map_impl::erase_if): Replace this hidden friend with ... (_Flat_map_impl::_M_erase_if): ... this member function. (flat_map): Export _Flat_map_impl::_M_erase_if. (erase_if(flat_map)): Define. (flat_multimap): Export _Flat_map_impl::_M_erase_if. (erase_if(flat_multimap)): Define. * include/std/flat_set (_Flat_set_impl::erase_if): Replace with ... (_Flat_set_impl::_M_erase_if): ... this member function. (flat_set): Export _Flat_set_impl::_M_erase_if. (erase_if(flat_set)): Define. (flat_multiset): Export _Flat_set_impl::_M_erase_if. (erase_if(flat_multiset)): Define. * testsuite/23_containers/flat_map/1.cc (test07): New test. * testsuite/23_containers/flat_multimap/1.cc (test07): New test. * testsuite/23_containers/flat_multiset/1.cc (test09): New test. * testsuite/23_containers/flat_set/1.cc (test09): New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com>
2025-04-29libstdc++: Use constexpr-if for C++11 and C++14Jonathan Wakely13-41/+86
Replace remaining uses of _GLIBCXX17_CONSTEXPR for constexpr-if, so that we always use constexpr-if in C++11 and C++14. Diagnostic pragmas are used to suppress diagnostics. libstdc++-v3/ChangeLog: * include/bits/char_traits.h (char_traits::assign): Use constexpr-if unconditionally for C++11 and C++14. * include/bits/locale_conv.h (__do_str_codecvt): Likewise. * include/bits/ostream.h (basic_ostream::_S_cast_flt): Likewise. * include/bits/random.tcc (shuffle_order_engine::operator()) (seed_seq::seed_seq(Iter, Iter)): Likewise. * include/bits/shared_ptr_base.h (_Sp_counted_base::_M_release): Likewise. * include/bits/stl_tree.h (_Rb_tree::_M_move_data): Likewise. * include/bits/uniform_int_dist.h (uniform_int_distribution::operator()): Likewise. * include/bits/valarray_array.h (__valarray_default_construct) (__valarray_fill_construct, __valarray_copy_construct) (__valarray_copy_construct, __valarray_destroy_elements): Likewise. * include/experimental/numeric (lcm): Likewise. * include/std/bit (__rotl, __rotr, __countl_zero, __countr_zero) (__popcount, __bit_ceil) Likewise.: * include/std/bitset (operator>>): Likewise. * include/std/charconv (__to_chars_8, __to_chars_i) (__from_chars_alnum_to_val, from_chars): Likewise. * include/tr2/dynamic_bitset (__dynamic_bitset_base): Likewise. * testsuite/26_numerics/random/pr60037-neg.cc: Adjust dg-error line number. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-29libstdc++: Use constexpr-if in std::function for C++11 and C++14Jonathan Wakely1-22/+9
This allows removing the _Target_handler class template, because it's no longer needed to prevent instantiating invalid specializations of _Function_handler. libstdc++-v3/ChangeLog: * include/bits/std_function.h (_Target_handler): Remove. (function::target): Use constexpr-if for C++11 and C++14, with diagnostic pragmas to suppress warnings. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-29libstdc++: Use constexpr-if to simplify std::vector relocationJonathan Wakely2-33/+34
Simplify std::vector's use of std::__relocate_a by using 'if constexpr' even in C++11 and C++14, with diagnostic pragmas to disable warnings. This allows us to call std::__relocate_a directly, instead of via _S_relocate and tag distpatching. Preserve _S_relocate so that explicit instantiations still get it, but make it a no-op when _S_use_relocate() is false, so that we don't instantiate __relocate_a if it isn't needed. libstdc++-v3/ChangeLog: * include/bits/stl_vector.h (_S_do_relocate): Remove. (_S_relocate): Remove tag dispatching path. * include/bits/vector.tcc (reserve, _M_realloc_insert) (_M_realloc_append, _M_default_append): Add diagnostic pragmas and use 'if constexpr' in C++11 and C++14. Call std::__relocate_a directly instead of _S_relocate. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-29libstdc++: Fix allocator propagation for rvalue+rvalue string concatenationJonathan Wakely1-4/+6
I made a last-minute change to Nina's r10-200-gf4e678ef74b272 implementation of P1165R1 (consistent allocator propagation for operator+ on strings), so that the rvalue+rvalue case assumes that COW strings do not support stateful allocators. I don't think that was true when the change went in, and isn't true now. COW strings don't support allocator propagation on assignment and swap, but they do support non-equal stateful allocators, which are correctly propagated on move construction. This removes the preprocessor conditional in the rvalue+rvalue overload so that COW strings are handled equivalently. Also use constexpr-if unconditionally, disabling diagnostics with pragmas. libstdc++-v3/ChangeLog: * include/bits/basic_string.h (operator+(string&&, string&&)): Do not assume that COW strings have equal allocators. Use constexpr-if unconditionally. * testsuite/21_strings/basic_string/allocator/char/operator_plus.cc: Remove cxx11_abi effective-target check. * testsuite/21_strings/basic_string/allocator/wchar_t/operator_plus.cc: Likewise. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-28libstdc++: Fix mingw build by using _M_span [PR119970]Tomasz Kamiński2-2/+2
The r16-142-g01e5ef3e8b9128 chagned return type of _Str_sink::view() to basic_string_view<_CharT>. The mutable access is provided by _M_span function, that is now used for mingw path. PR libstdc++/119970 libstdc++-v3/ChangeLog: * include/std/ostream (vprint_unicode) [_WIN32 && !__CYGWIN__]: Call _Str_sink::_M_span instead of view. * include/std/print (vprint_unicode) [_WIN32 && !__CYGWIN__]: Call _Str_sink::_M_span instead of view.
2025-04-28libstdc++: Strip reference and cv-qual in range deduction guides for maps.Tomasz Kamiński2-6/+9
This implements part of LWG4223 that adjust the deduction guides for maps types (map, unordered_map, flat_map and non-unique equivalent) from "range" (std::from_range, iterator pair), such that referience and cv qualification are stripped from the element of the pair-like value_type. In combination with r15-8296-gd50171bc07006d, the LWG4223 is fully implemented now. libstdc++-v3/ChangeLog: * include/bits/ranges_base.h (__detail::__range_key_type): Replace remove_const_t with remove_cvref_t. (__detail::__range_mapped_type): Apply remove_cvref_t. * include/bits/stl_iterator.h: (__detail::__iter_key_t): Replace remove_const_t with __remove_cvref_t. (__detail::__iter_val_t): Apply __remove_cvref_t. * testsuite/23_containers/flat_map/1.cc: New tests. * testsuite/23_containers/flat_multimap/1.cc: New tests. * testsuite/23_containers/map/cons/deduction.cc: New tests. * testsuite/23_containers/map/cons/from_range.cc: New tests. * testsuite/23_containers/multimap/cons/deduction.cc: New tests. * testsuite/23_containers/multimap/cons/from_range.cc: New tests. * testsuite/23_containers/unordered_map/cons/deduction.cc: New tests. * testsuite/23_containers/unordered_map/cons/from_range.cc: New tests. * testsuite/23_containers/unordered_multimap/cons/deduction.cc: New tests. * testsuite/23_containers/unordered_multimap/cons/from_range.cc: New tests. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-28libstdc++: Implement missing allocator-aware constructors for unordered ↵Tomasz Kamiński4-0/+177
containers. This patch implements remainder of LWG2713 (after r15-8293-g64f5c854597759) by adding missing allocator aware version of unordered associative containers constructors accepting pair of iterators or initializer_list, and corresponding deduction guides. libstdc++-v3/ChangeLog: * include/bits/unordered_map.h (unordered_map): Define constructors accepting: (_InputIterator, _InputIterator, const allocator_type&), (initializer_list<value_type>, const allocator_type&), (unordered_multimap): Likewise. * include/debug/unordered_map (unordered_map): Likewise. (unordered_multimap): Likewise. * include/bits/unordered_set.h (unordered_set): Define constructors and deduction guide accepting: (_InputIterator, _InputIterator, const allocator_type&), (initializer_list<value_type>, const allocator_type&), (unordered_multiset): Likewise. * include/debug/unordered_set (unordered_set): Likewise. (unordered_multiset): Likewise. * testsuite/23_containers/unordered_map/cons/66055.cc: New tests. * testsuite/23_containers/unordered_map/cons/deduction.cc: New tests. * testsuite/23_containers/unordered_multimap/cons/66055.cc: New tests. * testsuite/23_containers/unordered_multimap/cons/deduction.cc: New tests. * testsuite/23_containers/unordered_multiset/cons/66055.cc: New tests. * testsuite/23_containers/unordered_multiset/cons/deduction.cc: New tests. * testsuite/23_containers/unordered_set/cons/66055.cc: New tests. * testsuite/23_containers/unordered_set/cons/deduction.cc: New tests. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-25libstdc++: Use markdown in some Doxygen commentsJonathan Wakely1-3/+3
libstdc++-v3/ChangeLog: * include/bits/ptr_traits.h (to_address): Use markdown for formatting in Doxygen comments.
2025-04-25libstdc++: Micro-optimization for std::addressofJonathan Wakely1-1/+1
Currently std::addressof calls std::__addressof which uses __builtin_addressof. This leads to me prefering std::__addressof in some code, to avoid the extra hop. But it's not as though the implementation of std::__addressof is complicated and reusing it avoids any code duplication. So let's just make std::addressof use the built-in directly, and then we only need to use std::__addressof in C++98 code. (Transitioning existing uses of std::__addressof to std::addressof isn't included in this change.) The front end does fold std::addressof with -ffold-simple-inlines but this change still seems worthwhile. libstdc++-v3/ChangeLog: * include/bits/move.h (addressof): Use __builtin_addressof directly.
2025-04-25libstdc++: Rename std::latch data memberJonathan Wakely1-6/+6
Rename _M_a to match the name of the exposition-only data member shown in the standard, i.e. 'counter'. libstdc++-v3/ChangeLog: * include/std/latch (latch::_M_a): Rename to _M_counter. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-25libstdc++: Minimalize temporary allocations when width is specified [PR109162]Tomasz Kamiński2-101/+306
When width parameter is specified for formatting range, tuple or escaped presentation of string, we used to format characters to temporary string, and write produce sequence padded according to the spec. However, once the estimated width of formatted representation of input is larger than the value of spec width, it can be written directly to the output. This limits size of required allocation, especially for large ranges. Similarly, if precision (maximum) width is provided for string presentation, only a prefix of sequence with estimated width not greater than precision, needs to be buffered. To realize above, this commit implements a new _Padding_sink specialization. This sink holds an output iterator, a value of padding width, (optionally) maximum width and a string buffer inherited from _Str_sink. Then any incoming characters are treated in one of following ways, depending of estimated width W of written sequence: * written to string if W is smaller than padding width and maximum width (if present) * ignored, if W is greater than maximum width * written to output iterator, if W is greater than padding width The padding sink is used instead of _Str_sink in __format::__format_padded, __formatter_str::_M_format_escaped functions. Furthermore __formatter_str::_M_format implementation was reworked, to: * reduce number of instantiations by delegating to _Rg& and const _Rg& overloads, * non-debug presentation is written to _Out directly or via _Padding_sink * if maximum width is specified for debug format with non-unicode encoding, string size is limited to that number. PR libstdc++/109162 libstdc++-v3/ChangeLog: * include/bits/formatfwd.h (__simply_formattable_range): Moved from std/format. * include/std/format (__formatter_str::_format): Extracted escaped string handling to separate method... (__formatter_str::_M_format_escaped): Use __Padding_sink. (__formatter_str::_M_format): Adjusted implementation. (__formatter_str::_S_trunc): Extracted as namespace function... (__format::_truncate): Extracted from __formatter_str::_S_trunc. (__format::_Seq_sink): Removed forward declarations, made members protected and non-final. (_Seq_sink::_M_trim): Define. (_Seq_sink::_M_span): Renamed from view. (_Seq_sink::view): Returns string_view instead of span. (__format::_Str_sink): Moved after _Seq_sink. (__format::__format_padded): Use _Padding_sink. * testsuite/std/format/debug.cc: Add timeout and new tests. * testsuite/std/format/ranges/sequence.cc: Specify unicode as encoding and new tests. * testsuite/std/format/ranges/string.cc: Likewise. * testsuite/std/format/tuple.cc: Likewise. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-25libstdc++: Constrain formatter for thread::id [PR119918]Tomasz Kamiński3-143/+180
This patch add constraint __formatter::__char to _CharT type parameter of formatter<thread::id, _CharT> specialization, matching the constraint of formatting of integer/pointers that are used as native handles. The dependency on <format> header, is changed to <bits/formatfwd.h>. To achieve that, formatting of pointers is extracted from void const* specialization to internal __formatter_ptr<_CharT>, that can be forward declared. Finally, the handle representation is now printed directly to __fc.out(), by the formatter for handle type. To support this, internal formatters can now be constructed from _Spec object as alternative to invoking parse method. PR libstdc++/119918 libstdc++-v3/ChangeLog: * include/bits/formatfwd.h (__format::_Align): Moved from std/format. (std::__throw_format_error, __format::__formatter_str) (__format::__formatter_ptr): Declare. * include/std/format (__format::_Align): Moved to bits/formatfwd.h. (__formatter_int::__formatter_int): Define. (__format::__formatter_ptr): Extracted from formatter for const void*. (std::formatter<const void*, _CharT>, formatter<void*, _CharT>) (std::formatter<nullptr_t, _CharT>): Delegate to __formatter_ptr<_CharT>. * include/std/thread (std::formatter<thread::id, _CharT>): Constrain _CharT template parameter. (formatter<thread::id, _CharT>::parse): Specify default aligment, and qualify __throw_format_error to disable ADL. (formatter<thread::id, _CharT>::format): Use formatters to write directly to output. * testsuite/30_threads/thread/id/output.cc: Tests for formatting thread::id representing not-a-thread with padding and formattable concept. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-25libstdc++: Define __cpp_lib_format_ranges in format header [PR109162]Tomasz Kamiński2-3/+3
As P2286R8 and P2585R1 as now fully implemented, we now define __cpp_lib_format_ranges feature test macro with __cpp_lib_format_ranges. This macro is provided only in <format>. Uses of internal __glibcxx_format_ranges are also updated. PR libstdc++/109162 libstdc++-v3/ChangeLog: * include/bits/version.def (format_ranges): Remove no_stdname and update value. * include/bits/version.h: Regenerate. * src/c++23/std.cc.in: Replace __glibcxx_format_ranges with __cpp_lib_format_ranges. * testsuite/std/format/formatter/lwg3944.cc: Likewise. * testsuite/std/format/parse_ctx.cc: Likewise. * testsuite/std/format/string.cc: Likewise. * testsuite/std/format/ranges/feature_test.cc: New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-25libstdc++: Implement formatters for queue, priority_queue and stack [PR109162]Tomasz Kamiński6-74/+231
This patch implements formatter specializations for standard container adaptors (queue, priority_queue and stack) from P2286R8. To be able to access the protected `c` member, the adaptors befriend corresponding formatter specializations. Note that such specialization may be disable if the container is formattable, in such case specializations are unharmful. As in the case of previous commits, the signatures of the user-facing parse and format methods of the provided formatters deviate from the standard by constraining types of parameters: * _CharT is constrained __formatter::__char * basic_format_parse_context<_CharT> for parse argument * basic_format_context<_Out, _CharT> for format second argument The standard specifies all above as unconstrained types. In particular _CharT constrain, allow us to befriend all allowed specializations. Furthermore the standard specifies these formatters as delegating to formatter<ranges::ref_view<const? _Container>, charT>, which in turn delegates to range_formatter. This patch avoids one level of indirection, and dependency of ranges::ref_view. This is technically observable if user specializes formatter<std::ref_view<PD>> where PD is program defined container, but I do not think this is the case worth extra indirection. This patch also moves the formattable and it's dependencies to the formatfwd.h, so it can be used in adapters formatters, without including format header. The definition of _Iter_for is changed from alias to denoting back_insert_iterator<basic_string<_CharT>>, to struct with type nested typedef that points to same type, that is forward declared. PR libstdc++/109162 libstdc++-v3/ChangeLog: * include/bits/formatfwd.h (__format::__parsable_with) (__format::__formattable_with, __format::__formattable_impl) (__format::__has_debug_format, __format::__const_formattable_range) (__format::__maybe_const_range, __format::__maybe_const) (std::formattable): Moved from std/format. (__format::Iter_for, std::range_formatter): Forward declare. * include/bits/stl_queue.h (std::formatter): Forward declare. (std::queue, std::priority_queue): Befriend formatter specializations. * include/bits/stl_stack.h (std::formatter): Forward declare. (std::stack): Befriend formatter specializations. * include/std/format (__format::_Iter_for): Define as struct with (__format::__parsable_with, __format::__formattable_with) (__format::__formattable_impl, __format::__has_debug_format) (_format::__const_formattable_range, __format::__maybe_const_range) (__format::__maybe_const, std::formattable): Moved to bits/formatfwd.h. (std::range_formatter): Remove default argument specified in declaration in bits/formatfwd.h. * include/std/queue: Include bits/version.h before bits/stl_queue.h. (formatter<queue<_Tp, _Container, _Compare>, _CharT>) (formatter<priority_queue<_Tp, _Container, _Compare>, _CharT>): Define. * include/std/stack: Include bits/version.h before bits/stl_stack.h (formatter<stack<_Tp, _Container, _Compare>, _CharT>): Define. * testsuite/std/format/ranges/adaptors.cc: New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-25libstdc++: Improve diagnostics for std::packaged_task invocable checksJonathan Wakely1-34/+32
Moving the static_assert that checks is_invocable_r_v into _Task_state means it is checked when we instantiate that class template. Replacing the __create_task_state function with a static member function _Task_state::_S_create ensures we instantiate _Task_state and trigger the static_assert immediately, not deep inside the implementation of std::allocate_shared. This results in shorter diagnostics that don't show deeply-nested template instantiations before the static_assert failure. Placing the static_assert at class scope also helps us to fail earlier than waiting until when the _Task_state::_M_run virtual function is instantiated. That also makes the diagnostics shorter and easier to read (although for C++11 and C++14 modes the class-scope static_assert doesn't check is_invocable_r, so dangling references aren't detected until _M_run is instantiated). libstdc++-v3/ChangeLog: * include/std/future (__future_base::_Task_state): Check invocable requirement here. (__future_base::_Task_state::_S_create): New static member function. (__future_base::_Task_state::_M_reset): Use _S_create. (__create_task_state): Remove. (packaged_task): Use _Task_state::_S_create instead of __create_task_state. * testsuite/30_threads/packaged_task/cons/dangling_ref.cc: Adjust dg-error patterns. * testsuite/30_threads/packaged_task/cons/lwg4154_neg.cc: Likewise. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-25libstdc++: Add _M_key_compare helper to associative containersJonathan Wakely1-57/+49
In r10-452-ge625ccc21a91f3 I noted that we don't have an accessor for invoking _M_impl._M_key_compare in the associative containers. That meant that the static assertions to check for valid comparison functions were squirrelled away in _Rb_tree::_S_key instead. As Jason noted in https://gcc.gnu.org/pipermail/gcc-patches/2025-April/681436.html this means that the static assertions fail later than we'd like. This change adds a new _Rb_tree::_M_key_compare member function which invokes the _M_impl._M_key_compare function object, and then moves the static_assert from _S_key into _M_key_compare. Now if the static_assert fails, that's the first error we get, before the "no match for call" and and "invalid conversion" errors. Because the new function is const-qualified, we now treat LWG 2542 as a DR for older standards, requiring the comparison function to be const invocable. Previously we only enforced the LWG 2542 rule for C++17 and later. I did consider deprecating support for comparisons which aren't const invocable, something like this: // Before LWG 2542 it wasn't strictly necessary for _Compare to be // const invocable, if you only used non-const container members. // Define a non-const overload for pre-C++17, deprecated for C++11/14. #if __cplusplus < 201103L bool _M_key_compare(const _Key& __k1, const _Key& __k2) { return _M_impl._M_key_compare(__k1, __k2); } #elif __cplusplus < 201703L template<typename _Key1, typename _Key2> [[__deprecated__("support for comparison functions that are not " "const invocable is deprecated")]] __enable_if_t< __and_<__is_invocable<_Compare&, const _Key1&, const _Key2&>, __not_<__is_invocable<const _Compare&, const _Key1&, const _Key2&>>>::value, bool> _M_key_compare(const _Key1& __k1, const _Key2& __k2) { static_assert( __is_invocable<_Compare&, const _Key&, const _Key&>::value, "comparison object must be invocable with two arguments of key type" ); return _M_impl._M_key_compare(__k1, __k2); } #endif But I decided that this isn't necessary, because we've been enforcing the C++17 rule since GCC 8.4 and 9.2, and C++17 has been the default since GCC 11.1. Users have had plenty of time to fix their invalid comparison functions. libstdc++-v3/ChangeLog: * include/bits/stl_tree.h (_Rb_tree::_M_key_compare): New member function to invoke comparison function. (_Rb_tree): Use new member function instead of accessing the comparison function directly. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-24libstdc++: Add lvalue overload for generator::yield_valueJonathan Wakely1-0/+10
This was approved in Wrocław as LWG 3899. This avoids creating a new coroutine frame to co_yield the elements of an lvalue generator. libstdc++-v3/ChangeLog: * include/std/generator (generator::yield_value): Add overload taking lvalue element_of view, as per LWG 3899. * testsuite/24_iterators/range_generators/lwg3899.cc: New test. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Reviewed-by: Arsen Arsenović <arsen@aarsen.me>
2025-04-22Revert "libstdc++: Optimize std::projected<I, std::identity>" [PR119888]Patrick Palka1-5/+0
This non-standard optimization breaks real-world code that expects the result of std::projected to always (be a class type and) have a value_type member, which isn't true for e.g. I=int*, so revert it for now. PR libstdc++/119888 This reverts commit 51761c50f843d5be4e24172535e4524b5072f24c.
2025-04-17libstdc++: Fixed signed comparision in _M_parse_fill_and_align [PR119840]Tomasz Kamiński1-2/+2
Explicitly cast elements of __not_fill to _CharT. Only '{' and ':' are used as `__not_fill`, so they are never negative. PR libstdc++/119840 libstdc++-v3/ChangeLog: * include/std/format (_M_parse_fill_and_align): Cast elements of __not_fill to _CharT.
2025-04-17libstdc++: Do not use 'not' alternative token in <format>Jonathan Wakely1-1/+4
This fixes: FAIL: 17_intro/headers/c++1998/operator_names.cc -std=gnu++23 (test for excess errors) FAIL: 17_intro/headers/c++1998/operator_names.cc -std=gnu++26 (test for excess errors) The purpose of 'not defined<format_kind<R>>' is to be ill-formed (as required by [format.range.fmtkind]) and to give an error that includes the string "not defined<format_kind<R>>". That was intended to tell you that format_kind<R> is not defined, just like it says! But user code can use -fno-operator-names so we can't use 'not' here, and "! defined" in the diagnostic doesn't seem as user-friendly. It also raises questions about whether it was intended to be the preprocessor token 'defined' (it's not) or where 'defined' is defined (it's not). Replace it with __primary_template_not_defined<format_kind<R>> and a comment, which seems to give a fairly clear diagnostic with both GCC and Clang. The diagnostic now looks like: .../include/c++/15.0.1/format:5165:7: error: use of 'std::format_kind<int>' before deduction of 'auto' 5165 | format_kind<_Rg> // you can specialize this for non-const input ranges | ^~~~~~~~~~~~~~~~ .../include/c++/15.0.1/format:5164:35: error: '__primary_template_not_defined' was not declared in this scope 5164 | __primary_template_not_defined( | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^ 5165 | format_kind<_Rg> // you can specialize this for non-const input ranges | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5166 | ); | ~ libstdc++-v3/ChangeLog: * include/std/format (format_kind): Do not use 'not' alternative token to make the primary template ill-formed. Use the undeclared identifier __primary_template_not_defined and a comment that will appear in diagnostics. * testsuite/std/format/ranges/format_kind_neg.cc: New test.
2025-04-17libstdc++: Remove dead code in range_formatter::format [PR109162]Tomasz Kamiński1-7/+12
Because the _M_format(__rg, __fc) were placed outside of if constexpr, these method and its children where instantiated, even if _M_format<const _Range> could be used. To simplify the if constexpr chain, we introduce a __simply_formattable_range (name based on simple-view) exposition only concept, that checks if range is const and mutable formattable and uses same formatter specialization for references in each case. PR libstdc++/109162 libstdc++-v3/ChangeLog: * include/std/format (__format::__simply_formattable_range): Define. (range_formatter::format): Do not instantiate _M_format for mutable _Rg if const _Rg can be used. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-16libstdc++: Fix constification in range_formatter::format [PR109162]Tomasz Kamiński1-3/+8
The _Rg is deduced to lvalue reference for the lvalue arguments, and in such case __format::__maybe_const_range<_Rg, _CharT> is always _Rg (adding const to reference does not change behavior). Now we correctly check if _Range = remove_reference_t<_Rg> is const formattable range, furthermore as range_formatter<T> can only format ranges of values of type (possibly const) _Tp, we additional check if the remove_cvref_t<range_reference_t<const _Range>> is _Tp. The range_reference_t<R> and range_reference_t<const R> have different types (modulo remove_cvref_t) for std::vector<bool> (::reference and bool) or flat_map<T, U> (pair<const T&, U&> and pair<const T&, const U&>). PR libstdc++/109162 libstdc++-v3/ChangeLog: * include/std/format (range_formatter::format): Format const range, only if reference type is not changed. * testsuite/std/format/ranges/formatter.cc: New tests. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-16libstdc++: Implement formatters for pair and tuple [PR109162]Tomasz Kamiński1-74/+303
This patch implements formatter specializations for pair and tuple form P2286R8. In addition using 'm` and range_format::map (from P2585R1) for ranges are now supported. The formatters for pairs and tuples whose corresponding elements are the same (after applying remove_cvref_t) derive from the same __tuple_formatter class. This reduce the code duplication, as most of the parsing and formatting is the same in such cases. We use a custom reduced implementation of the tuple (__formatters_storage) to store the elements formatters. Handling of the padding (width and fill) options, is extracted to __format::__format_padded function, that is used both by __tuple_formatter and range_formatter. To reduce number of instantations range_formatter::format triggers, we cast incoming range to __format::__maybe_const_range<_Rg, _CharT>&, before formatting it. As in the case of previous commits, the signatures of the user-facing parse and format methods of the provided formatters deviate from the standard by constraining types of parameters: * _CharT is constrained __formatter::__char * basic_format_parse_context<_CharT> for parse argument * basic_format_context<_Out, _CharT> for format second argument The standard specifies last three of above as unconstrained types. Finally, test for tuple-like std::array and std::ranges::subrange, that illustrate that they remain formatted as ranges. PR libstdc++/109162 libstdc++-v3/ChangeLog: * include/std/format (__formatter_int::_M_format_character_escaped) (__formatter_str::format): Use __sink.out() to produce _Sink_iter. (__format::__const_formattable_range): Moved closer to range_formatter. (__format::__maybe_const_range): Use `__conditional_t` and moved closer to range_formatter. (__format::__format_padded, __format::maybe_const) (__format::__indexed_formatter_storage, __format::__tuple_formatter) (std::formatter<pair<_Fp, _Sp>, _CharT>>) (std::formatter<tuple<_Tps...>, _CharT): Define. (std::formatter<_Rg, _CharT>::format): Cast incoming range to __format::__maybe_const_range<_Rg, _CharT>&. (std::formatter<_Rg, _CharT>::_M_format): Extracted from format, and use __format_padded. (std::formatter<_Rg, _CharT>::_M_format_no_padding): Rename... (std::formatter<_Rg, _CharT>::_M_format_elems): ...to this. (std::formatter<_Rg, _CharT>::_M_format_with_padding): Extracted as __format_padded. * testsuite/util/testsuite_iterators.h (test_input_range_nocopy): Define. * testsuite/std/format/ranges/formatter.cc: Tests for `m` specifier. * testsuite/std/format/ranges/sequence.cc: Tests for array and subrange. * testsuite/std/format/ranges/map.cc: New test. * testsuite/std/format/tuple.cc: New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-15libstdc++: Do not define __cpp_lib_ranges_iota in <ranges>Jonathan Wakely1-1/+0
In r14-7153-gadbc46942aee75 we removed a duplicate definition of __glibcxx_want_range_iota from <ranges>, but __cpp_lib_ranges_iota should be defined in <ranges> at all. libstdc++-v3/ChangeLog: * include/std/ranges (__glibcxx_want_ranges_iota): Do not define.
2025-04-15libstdc++: Do not declare namespace ranges in <numeric> unconditionallyJonathan Wakely1-5/+3
Move namespace ranges inside the feature test macro guard, because 'ranges' is not a reserved name before C++20. libstdc++-v3/ChangeLog: * include/std/numeric (ranges): Only declare namespace for C++23 and later. (ranges::iota_result): Fix indentation. * testsuite/17_intro/names.cc: Check ranges is not used as an identifier before C++20.
2025-04-15libstdc++: Implement formatter for ranges and range_formatter [PR109162]Tomasz Kamiński1-57/+448
This patch implements formatter specialization for input_ranges and range_formatter class from P2286R8, as adjusted by P2585R1. The formatter for pair/tuple is not yet provided, making maps not formattable. This introduces an new _M_format_range member to internal __formatter_str, that formats range as _CharT as string, according to the format spec. This function transform any contiguous range into basic_string_view directly, by computing size if necessary. Otherwise, for ranges for which size can be computed (forward_range or sized_range) we use a stack buffer, if they are sufficiently small. Finally, we create a basic_string<_CharT> from the range, and format its content. In case when padding is specified, this is handled by firstly formatting the content of the range to the temporary string object. However, this can be only implemented if the iterator of the basic_format_context is internal type-erased iterator used by implementation. Otherwise a new basic_format_context would need to be created, which would require rebinding of handles stored in the arguments: note that format spec for element type could retrieve any format argument from format context, visit and use handle to format it. As basic_format_context provide no user-facing constructor, the user are not able to construct object of that type with arbitrary iterators. The signatures of the user-facing parse and format methods of the provided formatters deviate from the standard by constraining types of params: * _CharT is constrained __formatter::__char * basic_format_parse_context<_CharT> for parse argument * basic_format_context<_Out, _CharT> for format second argument The standard specifies last three of above as unconstrained types. These types are later passed to possibly user-provided formatter specializations, that are required via formattable concept to only accept above types. Finally, the formatter<input_range, _CharT> specialization is implemented without using specialization of range-default-formatter exposition only template as base class, while providing same functionality. PR libstdc++/109162 libstdc++-v3/ChangeLog: * include/std/format (__format::__has_debug_format, _Pres_type::_Pres_seq) (_Pres_type::_Pres_str, __format::__Stackbuf_size): Define. (_Separators::_S_squares, _Separators::_S_parens, _Separators::_S_comma) (_Separators::_S_colon): Define additional constants. (_Spec::_M_parse_fill_and_align): Define overload accepting list of excluded characters for fill, and forward existing overload. (__formatter_str::_M_format_range): Define. (__format::_Buf_sink) Use __Stackbuf_size for size of array. (__format::__is_map_formattable, std::range_formatter) (std::formatter<_Rg, _CharT>): Define. * src/c++23/std.cc.in (std::format_kind, std::range_format) (std::range_formatter): Export. * testsuite/std/format/formatter/lwg3944.cc: Guarded tests with __glibcxx_format_ranges. * testsuite/std/format/formatter/requirements.cc: Adjusted for standard behavior. * testsuite/23_containers/vector/bool/format.cc: Test vector<bool> formatting. * testsuite/std/format/ranges/format_kind.cc: New test. * testsuite/std/format/ranges/formatter.cc: New test. * testsuite/std/format/ranges/sequence.cc: New test. * testsuite/std/format/ranges/string.cc: New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-15libstdc++: Fix std::string construction from volatile char* [PR119748]Jonathan Wakely3-13/+31
My recent r15-9381-g648d5c26e25497 change assumes that a contiguous iterator with the correct value_type can be converted to a const charT* but that's not true for volatile charT*. The optimization should only be done if it can be converted to the right pointer type. Additionally, some generic loops for non-contiguous iterators need an explicit cast to deal with iterator reference types that do not bind to the const charT& parameter of traits_type::assign. libstdc++-v3/ChangeLog: PR libstdc++/119748 * include/bits/basic_string.h (_S_copy_chars): Only optimize for contiguous iterators that are convertible to const charT*. Use explicit conversion to charT after dereferencing iterator. (_S_copy_range): Likewise for contiguous ranges. * include/bits/basic_string.tcc (_M_construct): Use explicit conversion to charT after dereferencing iterator. * include/bits/cow_string.h (_S_copy_chars): Likewise. (basic_string(from_range_t, R&&, const Allocator&)): Likewise. Only optimize for contiguous iterators that are convertible to const charT*. * testsuite/21_strings/basic_string/cons/char/119748.cc: New test. * testsuite/21_strings/basic_string/cons/wchar_t/119748.cc: New test. Reviewed-by: Tomasz Kaminski <tkaminsk@redhat.com>
2025-04-11libstdc++: Use constexpr-if for std::basic_string::_S_copy_charsJonathan Wakely1-8/+23
For C++11 and later we can remove four overloads of _S_copy_chars and use constexpr-if in the generic _S_copy_chars. This simplifies overload resolution for _S_copy_chars, and also means that we use the optimized memcpy path for other iterators such as std::vector<char>::iterator. We still need all the _S_copy_chars overloads to be part of the explicit instantiation definition, so make them depend on the macro that is defined by src/c++11/string-inst.cc for that purpose. For C++98 the _S_copy_chars overloads are still needed, but the macros _GLIBCXX_NOEXCEPT and _GLIBCXX20_CONSTEXPR do nothing for C++98, so this change removes them from those overloads. When instantiated in src/c++11/string-inst.cc the removed _GLIBCXX_NOEXCEPT macros would expand to 'noexcept', but in practice that doesn't make any difference for those instantiations. At -O2 the instantiations inline all the calls to _S_copy_chars and the presence or absence of noexcept doesn't change anything in the generated code. libstdc++-v3/ChangeLog: * include/bits/basic_string.h (_S_copy_chars): Replace overloads with constexpr-if and extend optimization to all contiguous iterators. * src/c++11/string-inst.cc: Extend comment. Reviewed-by: Tomasz Kaminski <tkaminsk@redhat.com>
2025-04-11libstdc++: Define __cpp_lib_containers_ranges in appropriate headers [PR111055]Tomasz Kamiński41-134/+157
This is final piece of P1206R7, adding a feature test macros, as range constructors and member operations are now implemented for all containers and adaptors. For consistency with the proposal, all new container operations and helpers are now defined if __glibcxx_containers_ranges, instead of __glibcxx_ranges_to_container. PR libstdc++/111055 libstdc++-v3/ChangeLog: * include/bits/version.def (containers_ranges): Define. * include/bits/version.h: Regenerate. * include/bits/ranges_base.h (__detail::__container_compatible_range) (__detail::__range_to_alloc_type, __detail::__range_mapped_type) (__detail::__range_key_type): Depend on __glibcxx_containers_ranges instead of __glibcxx_ranges_to_container. * include/bits/basic_string.h: Replace __glibcxx_ranges_to_container with __glibcxx_containers_ranges. * include/bits/cow_string.h: Likewise. * include/bits/deque.tcc: Likewise. * include/bits/forward_list.h: Likewise. * include/bits/stl_bvector.h: Likewise. * include/bits/stl_deque.h: Likewise. * include/bits/stl_list.h: Likewise. * include/bits/stl_map.h: Likewise. * include/bits/stl_multimap.h: Likewise. * include/bits/stl_multiset.h: Likewise. * include/bits/stl_queue.h: Likewise. * include/bits/stl_set.h: Likewise. * include/bits/stl_stack.h: Likewise. * include/bits/stl_vector.h: Likewise. * include/bits/unordered_map.h: Likewise. * include/bits/unordered_set.h: Likewise. * include/bits/vector.tcc: Likewise. * include/debug/deque: Likewise. * include/debug/forward_list: Likewise. * include/debug/list: Likewise. * include/debug/map.h: Likewise. * include/debug/multimap.h: Likewise. * include/debug/multiset.h: Likewise. * include/debug/set.h: Likewise. * include/debug/unordered_map: Likewise. * include/debug/unordered_set: Likewise. * include/debug/vector: Likewise. * include/std/deque: Provide __cpp_lib_containers_ranges. * include/std/forward_list: Likewise. * include/std/list: Likewise. * include/std/map: Likewise. * include/std/queue: Likewise. * include/std/set: Likewise. * include/std/stack: Likewise. * include/std/string: Likewise. * include/std/unordered_map: Likewise. * include/std/unordered_set: Likewise. * include/std/vector: Likewise. * testsuite/21_strings/basic_string/cons/from_range.cc: Test for value __cpp_lib_containers_ranges. * testsuite/23_containers/deque/cons/from_range.cc: Likewise. * testsuite/23_containers/forward_list/cons/from_range.cc: Likewise. * testsuite/23_containers/list/cons/from_range.cc: Likewise. * testsuite/23_containers/map/cons/from_range.cc: Likewise. * testsuite/23_containers/multimap/cons/from_range.cc: Likewise. * testsuite/23_containers/multiset/cons/from_range.cc: Likewise. * testsuite/23_containers/priority_queue/cons_from_range.cc: Likewise. * testsuite/23_containers/queue/cons_from_range.cc: Likewise. * testsuite/23_containers/set/cons/from_range.cc: Likewise. * testsuite/23_containers/stack/cons_from_range.cc: Likewise. * testsuite/23_containers/unordered_map/cons/from_range.cc: Likewise. * testsuite/23_containers/unordered_multimap/cons/from_range.cc: Likewise. * testsuite/23_containers/unordered_multiset/cons/from_range.cc: Likewise. * testsuite/23_containers/unordered_set/cons/from_range.cc: Likewise. * testsuite/23_containers/vector/bool/cons/from_range.cc: Likewise. * testsuite/23_containers/vector/cons/from_range.cc: Likewise. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-11libstdc++: Add P1206R7 from_range members to std::string [PR111055]Jonathan Wakely2-0/+297
This is the last piece of P1206R7, adding new members to std::basic_string. libstdc++-v3/ChangeLog: PR libstdc++/111055 * include/bits/basic_string.h (_S_copy_range): New function. (basic_string(from_range_t, R%%, const Alloc&)): New constructor. (append_range, assign_range, insert_range, replace_with_range): New functions. * include/bits/cow_string.h: Likewise. * testsuite/21_strings/basic_string/cons/from_range.cc: New test. * testsuite/21_strings/basic_string/modifiers/append/append_range.cc: New test. * testsuite/21_strings/basic_string/modifiers/assign/assign_range.cc: New test. * testsuite/21_strings/basic_string/modifiers/insert/insert_range.cc: New test. * testsuite/21_strings/basic_string/modifiers/replace/replace_with_range.cc: New test. Co-authored-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-11libstdc++: Implement debug format for strings and characters formatters ↵Tomasz Kamiński4-77/+708
[PR109162] This patch implements part P2286R8 that specified debug (escaped) format for the strings and characters sequences. This include both handling of the '?' format specifier and set_debug_format member. To indicate partial support we define __glibcxx_format_ranges macro value 1, without defining __cpp_lib_format_ranges. We provide two separate escaping routines depending on the literal encoding for the corresponding character types. If the character encoding is Unicode, we follow the specification for the standard (__format::__write_escaped_unicode). For other encodings, we escape only characters in range [0x00, 0x80), interpreting them as ASCII values: [0x00, 0x20), 0x7f and '\t', '\r', '\n', '\\', '"', '\'' are escaped. We assume every character outside this range is printable (__format::_write_escaped_ascii). In particular we do not yet implement special handling of shift sequences. For Unicode escaping a new __unicode::__escape_edges table is introduced, that encodes information if character belongs to General_Category that is escaped by the standard (Control or Other). This table is generated from DerivedGeneralCategory.txt provided by Unicode. Only boolean flag is preserved to reduce the number of entries. The additional rules for escaping are handled by __format::__should_escape_unicode. When width or precision is specified, we emit escaped string to the temporary buffer and format the resulting string according to the format spec. For characters use a fixed size stack buffer, for which a new _Fixedbuf_sink is introduced. For strings, we use _Str_sink and to avoid allocations, we compute the estimated size of (possibly truncated) input, and if it is larger than width field we print directly. PR libstdc++/109162 contrib/ChangeLog: * unicode/README: Mentioned DerivedGeneralCategory.txt. * unicode/gen_libstdcxx_unicode_data.py: Generation __escape_edges table from DerivedGeneralCategory.txt. Update file name in comments. * unicode/DerivedGeneralCategory.txt: Copy of file distributed by Unicode Consortium. libstdc++-v3/ChangeLog: * include/bits/chrono_io.h (__detail::_Widen): Moved to std/format file. * include/bits/unicode-data.h: Regnerate. * include/bits/unicode.h (__unicode::_Utf_iterator::_M_units) (__unicode::__should_escape_category): Define. * include/std/format (_GLIBCXX_WIDEN_, _GLIBCXX_WIDEN): Copied from include/bits/chrono_io.h. (__format::_Widen): Moved from include/bits/chrono_io.h. (__format::_Term_char, __format::_Escapes, __format::_Separators) (__format::__should_escape_ascii, __format::__should_escape_unicode) (__format::__write_escape_seq, __format::__write_escaped_char) (__format::__write_escaped_acii, __format::__write_escaped_unicode) (__format::__write_escaped): Define. (__formatter_str::_S_trunc): Extracted truncation of character sequences. (__formatter_str::format): Handle _Pres_esc. (__formatter_int::_M_do_parse) [__glibcxx_format_ranges]: Parse '?'. (__formatter_int::_M_format_character_escaped): Define. (formatter<_CharT, _CharT>::format, formatter<char, wchar_t>::format): Handle _Pres_esc. (__formatter_str::set_debug_format, formatter<...>::set_debug_format) Guard with __glibcxx_format_ranges. (__format::_Fixedbuf_sink): Define. * testsuite/23_containers/vector/bool/format.cc: Use __format::_Widen and remove unnecessary <chrono> include. * testsuite/std/format/debug.cc: New test. * testsuite/std/format/debug_nonunicode.cc: New test. * testsuite/std/format/parse_ctx.cc (escaped_strings_supported): Define to true if __glibcxx_format_ranges is defined. * testsuite/std/format/string.cc (escaped_strings_supported): Define to true if __glibcxx_format_ranges is defined. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-04-10libstdc++: Adjust value of __cpp_lib_constrained_equality for C++20Jonathan Wakely2-2/+12
The P3379R0 bump to __cpp_lib_constrained_equality relates to changes that only affect std::expected, so there's no reason to define the updated value in C++20. This change restores the previous value (202403) for C++20, and only uses the new value (202411) for C++23 and later. Also remove the TODO comments, because I correctly predicted that the final value would be 202411. libstdc++-v3/ChangeLog: * include/bits/version.def (constrained_equality): Only define as 202411 for C++23 and later, use 202403 for C++20. * include/bits/version.h: Regenerate. * testsuite/20_util/expected/equality_constrained.cc: Remove TODO comment.
2025-04-09libstdc++: Fix constraint recursion in basic_const_iterator operator- [PR115046]Patrick Palka1-2/+2
It was proposed in PR112490 to also adjust basic_const_iterator's friend operator-(sent, iter) overload alongside the r15-7757-g4342c50ca84ae5 adjustments to its comparison operators, but we lacked a concrete testcase demonstrating fixable constraint recursion there. It turns out Hewill Kang's PR115046 is such a testcase! So this patch makes the same adjustments to that overload as well, fixing PR115046. The LWG 4218 P/R will need to get adjusted too. PR libstdc++/115046 PR libstdc++/112490 libstdc++-v3/ChangeLog: * include/bits/stl_iterator.h (basic_const_iterator::operator-): Replace non-dependent basic_const_iterator function parameter with a dependent one of type basic_const_iterator<_It2> where _It2 matches _It. * testsuite/std/ranges/adaptors/as_const/1.cc (test04): New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com>
2025-04-08libstdc++: Fix use-after-free in std::format [PR119671]Jonathan Wakely1-3/+3
When formatting floating-point values to wide strings there's a case where we invalidate a std::wstring buffer while a std::wstring_view is still referring to it. libstdc++-v3/ChangeLog: PR libstdc++/119671 * include/std/format (__formatter_fp::format): Do not invalidate __wstr unless _M_localized returns a valid string. * testsuite/std/format/functions/format.cc: Check wide string formatting of floating-point types with classic locale. Reviewed-by: Tomasz Kaminski <tkaminsk@redhat.com>
2025-04-07libstdc++: Remove stray pragma in new header [PR119642]Jonathan Wakely1-1/+0
libstdc++-v3/ChangeLog: PR libstdc++/119642 * include/bits/formatfwd.h: Remove stray pragma.
2025-04-07libstdc++: Add new headers to <bits/stdc++.h> for PCHJonathan Wakely1-3/+3
This adds the new C23 headers to the PCH, and also removes the __has_include check for <stacktrace> because we provide that unconditionally now. libstdc++-v3/ChangeLog: * include/precompiled/stdc++.h: Include <stdbit.h> and <stdckdint.h>. Include <stacktrace> unconditionally.