1#!/usr/bin/env python
2
3import os
4from builtins import range
5from functools import reduce
6
7def get_libcxx_paths():
8  utils_path = os.path.dirname(os.path.abspath(__file__))
9  script_name = os.path.basename(__file__)
10  assert os.path.exists(utils_path)
11  src_root = os.path.dirname(utils_path)
12  include_path = os.path.join(src_root, 'include')
13  assert os.path.exists(include_path)
14  docs_path = os.path.join(src_root, 'docs')
15  assert os.path.exists(docs_path)
16  macro_test_path = os.path.join(src_root, 'test', 'std', 'language.support',
17                            'support.limits', 'support.limits.general')
18  assert os.path.exists(macro_test_path)
19  assert os.path.exists(os.path.join(macro_test_path, 'version.version.compile.pass.cpp'))
20  return script_name, src_root, include_path, docs_path, macro_test_path
21
22script_name, source_root, include_path, docs_path, macro_test_path = get_libcxx_paths()
23
24def has_header(h):
25  h_path = os.path.join(include_path, h)
26  return os.path.exists(h_path)
27
28def add_version_header(tc):
29  tc["headers"].append("version")
30  return tc
31
32# ================  ============================================================
33# Field             Description
34# ================  ============================================================
35# name              The name of the feature-test macro.
36# values            A dict whose keys are C++ versions and whose values are the
37#                   value of the feature-test macro for that C++ version.
38#                   (TODO: This isn't a very clean model for feature-test
39#                   macros affected by multiple papers.)
40# headers           An array with the headers that should provide the
41#                   feature-test macro.
42# test_suite_guard  An optional string field. When this field is provided,
43#                   `libcxx_guard` must also be provided. This field is used
44#                   only to generate the unit tests for the feature-test macros.
45#                   It can't depend on macros defined in <__config> because the
46#                   `test/std/` parts of the test suite are intended to be
47#                   portable to any C++ standard library implementation, not
48#                   just libc++. It may depend on
49#                    * macros defined by the compiler itself, or
50#                    * macros generated by CMake.
51#                   In some cases we add
52#                   `&& !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM_...)`
53#                   in order to make libc++ pass the tests on OSX; see D94983.
54# libcxx_guard      An optional string field. When this field is provided,
55#                   `test_suite_guard` must also be provided. This field is used
56#                   only to guard the feature-test macro in <version>. It may
57#                   be the same as `test_suite_guard`, or it may depend on
58#                   macros defined in <__config>.
59# unimplemented     An optional Boolean field with the value `True`. This field
60#                   is only used when a feature isn't fully implemented. Once
61#                   you've fully implemented the feature, you should remove
62#                   this field.
63# ================  ============================================================
64feature_test_macros = [ add_version_header(x) for x in [
65  {
66    "name": "__cpp_lib_adaptor_iterator_pair_constructor",
67    "values": { "c++2b": 202106 },
68    "headers": ["queue", "stack"],
69  }, {
70    "name": "__cpp_lib_addressof_constexpr",
71    "values": { "c++17": 201603 },
72    "headers": ["memory"],
73  }, {
74    "name": "__cpp_lib_allocate_at_least",
75    "values": { "c++2b": 202106 },
76    "headers": ["memory"],
77  }, {
78    "name": "__cpp_lib_allocator_traits_is_always_equal",
79    "values": { "c++17": 201411 },
80    "headers": ["deque", "forward_list", "list", "map", "memory", "scoped_allocator", "set", "string", "unordered_map", "unordered_set", "vector"],
81  }, {
82    "name": "__cpp_lib_any",
83    "values": { "c++17": 201606 },
84    "headers": ["any"],
85  }, {
86    "name": "__cpp_lib_apply",
87    "values": { "c++17": 201603 },
88    "headers": ["tuple"],
89  }, {
90    "name": "__cpp_lib_array_constexpr",
91    "values": { "c++17": 201603, "c++20": 201811 },
92    "headers": ["array", "iterator"],
93  }, {
94    "name": "__cpp_lib_as_const",
95    "values": { "c++17": 201510 },
96    "headers": ["utility"],
97  }, {
98    "name": "__cpp_lib_associative_heterogeneous_erasure",
99    "values": { "c++2b": 202110 },
100    "headers": ["map", "set", "unordered_map", "unordered_set"],
101    "unimplemented": True,
102  }, {
103    "name": "__cpp_lib_assume_aligned",
104    "values": { "c++20": 201811 },
105    "headers": ["memory"],
106  }, {
107    "name": "__cpp_lib_atomic_flag_test",
108    "values": { "c++20": 201907 },
109    "headers": ["atomic"],
110  }, {
111    "name": "__cpp_lib_atomic_float",
112    "values": { "c++20": 201711 },
113    "headers": ["atomic"],
114    "unimplemented": True,
115  }, {
116    "name": "__cpp_lib_atomic_is_always_lock_free",
117    "values": { "c++17": 201603 },
118    "headers": ["atomic"],
119  }, {
120    "name": "__cpp_lib_atomic_lock_free_type_aliases",
121    "values": { "c++20": 201907 },
122    "headers": ["atomic"],
123  }, {
124    "name": "__cpp_lib_atomic_ref",
125    "values": { "c++20": 201806 },
126    "headers": ["atomic"],
127    "unimplemented": True,
128  }, {
129    "name": "__cpp_lib_atomic_shared_ptr",
130    "values": { "c++20": 201711 },
131    "headers": ["atomic"],
132    "unimplemented": True,
133  }, {
134    "name": "__cpp_lib_atomic_value_initialization",
135    "values": { "c++20": 201911 },
136    "headers": ["atomic", "memory"],
137  }, {
138    "name": "__cpp_lib_atomic_wait",
139    "values": { "c++20": 201907 },
140    "headers": ["atomic"],
141    "test_suite_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_atomic_wait)",
142    "libcxx_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_atomic_wait)",
143  }, {
144    "name": "__cpp_lib_barrier",
145    "values": { "c++20": 201907 },
146    "headers": ["barrier"],
147    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_barrier)",
148    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_barrier)",
149  }, {
150    "name": "__cpp_lib_bind_back",
151    "values": { "c++2b": 202202 },
152    "headers": ["functional"],
153    "unimplemented": True,
154  }, {
155    "name": "__cpp_lib_bind_front",
156    "values": { "c++20": 201907 },
157    "headers": ["functional"],
158  }, {
159    "name": "__cpp_lib_bit_cast",
160    "values": { "c++20": 201806 },
161    "headers": ["bit"],
162  }, {
163    "name": "__cpp_lib_bitops",
164    "values": { "c++20": 201907 },
165    "headers": ["bit"],
166    "unimplemented": True,
167  }, {
168    "name": "__cpp_lib_bool_constant",
169    "values": { "c++17": 201505 },
170    "headers": ["type_traits"],
171  }, {
172    "name": "__cpp_lib_bounded_array_traits",
173    "values": { "c++20": 201902 },
174    "headers": ["type_traits"],
175  }, {
176    "name": "__cpp_lib_boyer_moore_searcher",
177    "values": { "c++17": 201603 },
178    "headers": ["functional"],
179  }, {
180    "name": "__cpp_lib_byte",
181    "values": { "c++17": 201603 },
182    "headers": ["cstddef"],
183  }, {
184    "name": "__cpp_lib_byteswap",
185    "values": { "c++2b": 202110 },
186    "headers": ["bit"],
187  }, {
188    "name": "__cpp_lib_char8_t",
189    "values": { "c++20": 201907 },
190    "headers": ["atomic", "filesystem", "istream", "limits", "locale", "ostream", "string", "string_view"],
191    "test_suite_guard": "defined(__cpp_char8_t)",
192    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_CHAR8_T)",
193  }, {
194    "name": "__cpp_lib_chrono",
195    "values": { "c++17": 201611 },
196    "headers": ["chrono"],
197  }, {
198    "name": "__cpp_lib_chrono_udls",
199    "values": { "c++14": 201304 },
200    "headers": ["chrono"],
201  }, {
202    "name": "__cpp_lib_clamp",
203    "values": { "c++17": 201603 },
204    "headers": ["algorithm"],
205  }, {
206    "name": "__cpp_lib_complex_udls",
207    "values": { "c++14": 201309 },
208    "headers": ["complex"],
209  }, {
210    "name": "__cpp_lib_concepts",
211    "values": { "c++20": 202002 },
212    "headers": ["concepts"],
213  }, {
214    "name": "__cpp_lib_constexpr_algorithms",
215    "values": { "c++20": 201806 },
216    "headers": ["algorithm"],
217  }, {
218    "name": "__cpp_lib_constexpr_cmath",
219    "values": { "c++2b": 202202 },
220    "headers": ["cmath", "cstdlib"],
221    "unimplemented": True,
222  }, {
223    "name": "__cpp_lib_constexpr_complex",
224    "values": { "c++20": 201711 },
225    "headers": ["complex"],
226    "unimplemented": True,
227  }, {
228    "name": "__cpp_lib_constexpr_dynamic_alloc",
229    "values": { "c++20": 201907 },
230    "headers": ["memory"],
231  }, {
232    "name": "__cpp_lib_constexpr_functional",
233    "values": { "c++20": 201907 },
234    "headers": ["functional"],
235  }, {
236    "name": "__cpp_lib_constexpr_iterator",
237    "values": { "c++20": 201811 },
238    "headers": ["iterator"],
239  }, {
240    "name": "__cpp_lib_constexpr_memory",
241    "values": { "c++20": 201811 },
242    "headers": ["memory"],
243  }, {
244    "name": "__cpp_lib_constexpr_numeric",
245    "values": { "c++20": 201911 },
246    "headers": ["numeric"],
247  }, {
248    "name": "__cpp_lib_constexpr_string",
249    "values": { "c++20": 201907 },
250    "headers": ["string"],
251  }, {
252    "name": "__cpp_lib_constexpr_string_view",
253    "values": { "c++20": 201811 },
254    "headers": ["string_view"],
255  }, {
256    "name": "__cpp_lib_constexpr_tuple",
257    "values": { "c++20": 201811 },
258    "headers": ["tuple"],
259  }, {
260    "name": "__cpp_lib_constexpr_typeinfo",
261    "values": { "c++2b": 202106 },
262    "headers": ["typeinfo"],
263    "unimplemented": True,
264  }, {
265    "name": "__cpp_lib_constexpr_utility",
266    "values": { "c++20": 201811 },
267    "headers": ["utility"],
268  }, {
269    "name": "__cpp_lib_constexpr_vector",
270    "values": { "c++20": 201907 },
271    "headers": ["vector"],
272    "unimplemented": True,
273  }, {
274    "name": "__cpp_lib_coroutine",
275    "values": { "c++20": 201902 },
276    "headers": ["coroutine"],
277  }, {
278    "name": "__cpp_lib_destroying_delete",
279    "values": { "c++20": 201806 },
280    "headers": ["new"],
281    "test_suite_guard": "TEST_STD_VER > 17 && defined(__cpp_impl_destroying_delete) && __cpp_impl_destroying_delete >= 201806L",
282    "libcxx_guard": "_LIBCPP_STD_VER > 17 && defined(__cpp_impl_destroying_delete) && __cpp_impl_destroying_delete >= 201806L",
283  }, {
284    "name": "__cpp_lib_enable_shared_from_this",
285    "values": { "c++17": 201603 },
286    "headers": ["memory"],
287  }, {
288    "name": "__cpp_lib_endian",
289    "values": { "c++20": 201907 },
290    "headers": ["bit"],
291  }, {
292    "name": "__cpp_lib_erase_if",
293    "values": { "c++20": 202002 },
294    "headers": ["deque", "forward_list", "list", "map", "set", "string", "unordered_map", "unordered_set", "vector"],
295  }, {
296    "name": "__cpp_lib_exchange_function",
297    "values": { "c++14": 201304 },
298    "headers": ["utility"],
299  }, {
300    "name": "__cpp_lib_execution",
301    "values": { "c++17": 201603, "c++20": 201902 },
302    "headers": ["execution"],
303    "unimplemented": True,
304  }, {
305    "name": "__cpp_lib_filesystem",
306    "values": { "c++17": 201703 },
307    "headers": ["filesystem"],
308    "test_suite_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_filesystem)",
309    "libcxx_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_filesystem)"
310  }, {
311    "name": "__cpp_lib_format",
312    "values": {
313        # "c++20": 201907 Not implemented P1361R2 Integration of chrono with text formatting
314        # "c++20": 202106 Fully implemented
315        # "c++20": 202110 Not implemented P2372R3 Fixing locale handling in chrono formatters
316        "c++20": 202106,
317        # "c++23": 202207, Not implemented P2419R2 Clarify handling of encodings in localized formatting of chrono types
318        },
319    "headers": ["format"],
320    "test_suite_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_format) && !defined(_LIBCPP_HAS_NO_INCOMPLETE_FORMAT)",
321    "libcxx_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_format) && !defined(_LIBCPP_HAS_NO_INCOMPLETE_FORMAT)",
322    "unimplemented": True,
323  }, {
324    "name": "__cpp_lib_gcd_lcm",
325    "values": { "c++17": 201606 },
326    "headers": ["numeric"],
327  }, {
328    "name": "__cpp_lib_generic_associative_lookup",
329    "values": { "c++14": 201304 },
330    "headers": ["map", "set"],
331  }, {
332    "name": "__cpp_lib_generic_unordered_lookup",
333    "values": { "c++20": 201811 },
334    "headers": ["unordered_map", "unordered_set"],
335  }, {
336    "name": "__cpp_lib_hardware_interference_size",
337    "values": { "c++17": 201703 },
338    "test_suite_guard": "defined(__GCC_DESTRUCTIVE_SIZE) && defined(__GCC_CONSTRUCTIVE_SIZE)",
339    "libcxx_guard": "defined(__GCC_DESTRUCTIVE_SIZE) && defined(__GCC_CONSTRUCTIVE_SIZE)",
340    "headers": ["new"],
341  }, {
342    "name": "__cpp_lib_has_unique_object_representations",
343    "values": { "c++17": 201606 },
344    "headers": ["type_traits"],
345  }, {
346    "name": "__cpp_lib_hypot",
347    "values": { "c++17": 201603 },
348    "headers": ["cmath"],
349  }, {
350    "name": "__cpp_lib_incomplete_container_elements",
351    "values": { "c++17": 201505 },
352    "headers": ["forward_list", "list", "vector"],
353  }, {
354    "name": "__cpp_lib_int_pow2",
355    "values": { "c++20": 202002 },
356    "headers": ["bit"],
357  }, {
358    "name": "__cpp_lib_integer_comparison_functions",
359    "values": { "c++20": 202002 },
360    "headers": ["utility"],
361  }, {
362    "name": "__cpp_lib_integer_sequence",
363    "values": { "c++14": 201304 },
364    "headers": ["utility"],
365  }, {
366    "name": "__cpp_lib_integral_constant_callable",
367    "values": { "c++14": 201304 },
368    "headers": ["type_traits"],
369  }, {
370    "name": "__cpp_lib_interpolate",
371    "values": { "c++20": 201902 },
372    "headers": ["cmath", "numeric"],
373  }, {
374    "name": "__cpp_lib_invoke",
375    "values": { "c++17": 201411 },
376    "headers": ["functional"],
377  }, {
378    "name": "__cpp_lib_invoke_r",
379    "values": { "c++2b": 202106 },
380    "headers": ["functional"],
381    "unimplemented": True,
382  }, {
383    "name": "__cpp_lib_is_aggregate",
384    "values": { "c++17": 201703 },
385    "headers": ["type_traits"],
386  }, {
387    "name": "__cpp_lib_is_constant_evaluated",
388    "values": { "c++20": 201811 },
389    "headers": ["type_traits"],
390  }, {
391    "name": "__cpp_lib_is_final",
392    "values": { "c++14": 201402 },
393    "headers": ["type_traits"],
394  }, {
395    "name": "__cpp_lib_is_invocable",
396    "values": { "c++17": 201703 },
397    "headers": ["type_traits"],
398  }, {
399    "name": "__cpp_lib_is_layout_compatible",
400    "values": { "c++20": 201907 },
401    "headers": ["type_traits"],
402    "unimplemented": True,
403  }, {
404    "name": "__cpp_lib_is_nothrow_convertible",
405    "values": { "c++20": 201806 },
406    "headers": ["type_traits"],
407  }, {
408    "name": "__cpp_lib_is_null_pointer",
409    "values": { "c++14": 201309 },
410    "headers": ["type_traits"],
411  }, {
412    "name": "__cpp_lib_is_pointer_interconvertible",
413    "values": { "c++20": 201907 },
414    "headers": ["type_traits"],
415    "unimplemented": True,
416  }, {
417    "name": "__cpp_lib_is_scoped_enum",
418    "values": { "c++2b": 202011 },
419    "headers": ["type_traits"],
420  }, {
421    "name": "__cpp_lib_is_swappable",
422    "values": { "c++17": 201603 },
423    "headers": ["type_traits"],
424  }, {
425    "name": "__cpp_lib_jthread",
426    "values": { "c++20": 201911 },
427    "headers": ["stop_token", "thread"],
428    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS)",
429    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS)",
430    "unimplemented": True,
431  }, {
432    "name": "__cpp_lib_latch",
433    "values": { "c++20": 201907 },
434    "headers": ["latch"],
435    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch)",
436    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch)",
437  }, {
438    "name": "__cpp_lib_launder",
439    "values": { "c++17": 201606 },
440    "headers": ["new"],
441  }, {
442    "name": "__cpp_lib_list_remove_return_type",
443    "values": { "c++20": 201806 },
444    "headers": ["forward_list", "list"],
445  }, {
446    "name": "__cpp_lib_logical_traits",
447    "values": { "c++17": 201510 },
448    "headers": ["type_traits"],
449  }, {
450    "name": "__cpp_lib_make_from_tuple",
451    "values": { "c++17": 201606 },
452    "headers": ["tuple"],
453  }, {
454    "name": "__cpp_lib_make_reverse_iterator",
455    "values": { "c++14": 201402 },
456    "headers": ["iterator"],
457  }, {
458    "name": "__cpp_lib_make_unique",
459    "values": { "c++14": 201304 },
460    "headers": ["memory"],
461  }, {
462    "name": "__cpp_lib_map_try_emplace",
463    "values": { "c++17": 201411 },
464    "headers": ["map"],
465  }, {
466    "name": "__cpp_lib_math_constants",
467    "values": { "c++20": 201907 },
468    "headers": ["numbers"],
469  }, {
470    "name": "__cpp_lib_math_special_functions",
471    "values": { "c++17": 201603 },
472    "headers": ["cmath"],
473    "unimplemented": True,
474  }, {
475    "name": "__cpp_lib_memory_resource",
476    "values": { "c++17": 201603 },
477    "headers": ["memory_resource"],
478    "unimplemented": True,
479  }, {
480    "name": "__cpp_lib_move_only_function",
481    "values": { "c++2b": 202110 },
482    "headers": ["functional"],
483    "unimplemented": True,
484  }, {
485    "name": "__cpp_lib_node_extract",
486    "values": { "c++17": 201606 },
487    "headers": ["map", "set", "unordered_map", "unordered_set"],
488  }, {
489    "name": "__cpp_lib_nonmember_container_access",
490    "values": { "c++17": 201411 },
491    "headers": ["array", "deque", "forward_list", "iterator", "list", "map", "regex", "set", "string", "unordered_map", "unordered_set", "vector"],
492  }, {
493    "name": "__cpp_lib_not_fn",
494    "values": { "c++17": 201603 },
495    "headers": ["functional"],
496  }, {
497    "name": "__cpp_lib_null_iterators",
498    "values": { "c++14": 201304 },
499    "headers": ["iterator"],
500  }, {
501    "name": "__cpp_lib_optional",
502    "values": { "c++17": 201606, "c++2b": 202110 },
503    "headers": ["optional"],
504  }, {
505    "name": "__cpp_lib_out_ptr",
506    "values": { "c++2b": 202106 },
507    "headers": ["memory"],
508    "unimplemented": True,
509  }, {
510    "name": "__cpp_lib_parallel_algorithm",
511    "values": { "c++17": 201603 },
512    "headers": ["algorithm", "numeric"],
513    "unimplemented": True,
514  }, {
515    "name": "__cpp_lib_polymorphic_allocator",
516    "values": { "c++20": 201902 },
517    "headers": ["memory_resource"],
518    "unimplemented": True,
519  }, {
520    "name": "__cpp_lib_quoted_string_io",
521    "values": { "c++14": 201304 },
522    "headers": ["iomanip"],
523  }, {
524    "name": "__cpp_lib_ranges",
525    "values": { "c++20": 201811 },
526    "headers": ["algorithm", "functional", "iterator", "memory", "ranges"],
527    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)",
528    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)",
529  }, {
530    "name": "__cpp_lib_ranges_chunk",
531    "values": { "c++2b": 202202 },
532    "headers": ["ranges"],
533    "unimplemented": True,
534  }, {
535    "name": "__cpp_lib_ranges_chunk_by",
536    "values": { "c++2b": 202202 },
537    "headers": ["ranges"],
538    "unimplemented": True,
539  }, {
540    "name": "__cpp_lib_ranges_iota",
541    "values": { "c++2b": 202202 },
542    "headers": ["numeric"],
543    "unimplemented": True,
544  }, {
545    "name": "__cpp_lib_ranges_join_with",
546    "values": { "c++2b": 202202 },
547    "headers": ["ranges"],
548    "unimplemented": True,
549  }, {
550    "name": "__cpp_lib_ranges_slide",
551    "values": { "c++2b": 202202 },
552    "headers": ["ranges"],
553    "unimplemented": True,
554  }, {
555    "name": "__cpp_lib_ranges_starts_ends_with",
556    "values": { "c++2b": 202106 },
557    "headers": ["algorithm"],
558    "unimplemented": True,
559  }, {
560    "name": "__cpp_lib_ranges_to_container",
561    "values": { "c++2b": 202202 },
562    "headers": ["deque", "forward_list", "list", "map", "priority_queue", "queue", "set", "stack", "string", "unordered_map", "unordered_set", "vector"],
563    "unimplemented": True,
564  }, {
565    "name": "__cpp_lib_ranges_zip",
566    "values": { "c++2b": 202110 },
567    "headers": ["ranges", "tuple", "utility"],
568    "unimplemented": True,
569  }, {
570    "name": "__cpp_lib_raw_memory_algorithms",
571    "values": { "c++17": 201606 },
572    "headers": ["memory"],
573  }, {
574    "name": "__cpp_lib_reference_from_temporary",
575    "values": { "c++2b": 202202 },
576    "headers": ["type_traits"],
577    "unimplemented": True,
578  }, {
579    "name": "__cpp_lib_remove_cvref",
580    "values": { "c++20": 201711 },
581    "headers": ["type_traits"],
582  }, {
583    "name": "__cpp_lib_result_of_sfinae",
584    "values": { "c++14": 201210 },
585    "headers": ["functional", "type_traits"],
586  }, {
587    "name": "__cpp_lib_robust_nonmodifying_seq_ops",
588    "values": { "c++14": 201304 },
589    "headers": ["algorithm"],
590  }, {
591    "name": "__cpp_lib_sample",
592    "values": { "c++17": 201603 },
593    "headers": ["algorithm"],
594  }, {
595    "name": "__cpp_lib_scoped_lock",
596    "values": { "c++17": 201703 },
597    "headers": ["mutex"],
598  }, {
599    "name": "__cpp_lib_semaphore",
600    "values": { "c++20": 201907 },
601    "headers": ["semaphore"],
602    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore)",
603    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore)",
604  }, {
605    "name": "__cpp_lib_shared_mutex",
606    "values": { "c++17": 201505 },
607    "headers": ["shared_mutex"],
608    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex)",
609    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex)",
610  }, {
611    "name": "__cpp_lib_shared_ptr_arrays",
612    "values": { "c++17": 201611, "c++20": 201707 },
613    "headers": ["memory"],
614  }, {
615    "name": "__cpp_lib_shared_ptr_weak_type",
616    "values": { "c++17": 201606 },
617    "headers": ["memory"],
618  }, {
619    "name": "__cpp_lib_shared_timed_mutex",
620    "values": { "c++14": 201402 },
621    "headers": ["shared_mutex"],
622    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex)",
623    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex)",
624  }, {
625    "name": "__cpp_lib_shift",
626    "values": { "c++20": 201806 },
627    "headers": ["algorithm"],
628  }, {
629    "name": "__cpp_lib_smart_ptr_for_overwrite",
630    "values": { "c++20": 202002 },
631    "headers": ["memory"],
632    "unimplemented": True,
633  }, {
634    "name": "__cpp_lib_source_location",
635    "values": { "c++20": 201907 },
636    "headers": ["source_location"],
637    "unimplemented": True,
638  }, {
639    "name": "__cpp_lib_span",
640    "values": { "c++20": 202002 },
641    "headers": ["span"],
642  }, {
643    "name": "__cpp_lib_spanstream",
644    "values": { "c++2b": 202106 },
645    "headers": ["spanstream"],
646    "unimplemented": True,
647  }, {
648    "name": "__cpp_lib_ssize",
649    "values": { "c++20": 201902 },
650    "headers": ["iterator"],
651  }, {
652    "name": "__cpp_lib_stacktrace",
653    "values": { "c++2b": 202011 },
654    "headers": ["stacktrace"],
655    "unimplemented": True,
656  }, {
657    "name": "__cpp_lib_starts_ends_with",
658    "values": { "c++20": 201711 },
659    "headers": ["string", "string_view"],
660  }, {
661    "name": "__cpp_lib_stdatomic_h",
662    "values": { "c++2b": 202011 },
663    "headers": ["stdatomic.h"],
664  }, {
665    "name": "__cpp_lib_string_contains",
666    "values": { "c++2b": 202011 },
667    "headers": ["string", "string_view"],
668  }, {
669    "name": "__cpp_lib_string_resize_and_overwrite",
670    "values": { "c++2b": 202110 },
671    "headers": ["string"],
672  }, {
673    "name": "__cpp_lib_string_udls",
674    "values": { "c++14": 201304 },
675    "headers": ["string"],
676  }, {
677    "name": "__cpp_lib_string_view",
678    "values": { "c++17": 201606, "c++20": 201803 },
679    "headers": ["string", "string_view"],
680  }, {
681    "name": "__cpp_lib_syncbuf",
682    "values": { "c++20": 201803 },
683    "headers": ["syncstream"],
684    "unimplemented": True,
685  }, {
686    "name": "__cpp_lib_three_way_comparison",
687    "values": { "c++20": 201907 },
688    "headers": ["compare"],
689    "unimplemented": True,
690  }, {
691    "name": "__cpp_lib_to_address",
692    "values": { "c++20": 201711 },
693    "headers": ["memory"],
694  }, {
695    "name": "__cpp_lib_to_array",
696    "values": { "c++20": 201907 },
697    "headers": ["array"],
698  }, {
699    "name": "__cpp_lib_to_chars",
700    "values": { "c++17": 201611 },
701    "headers": ["charconv"],
702    "unimplemented": True,
703  }, {
704    "name": "__cpp_lib_to_underlying",
705    "values": { "c++2b": 202102 },
706    "headers": ["utility"],
707  }, {
708    "name": "__cpp_lib_transformation_trait_aliases",
709    "values": { "c++14": 201304 },
710    "headers": ["type_traits"],
711  }, {
712    "name": "__cpp_lib_transparent_operators",
713    "values": { "c++14": 201210, "c++17": 201510 },
714    "headers": ["functional", "memory"],
715  }, {
716    "name": "__cpp_lib_tuple_element_t",
717    "values": { "c++14": 201402 },
718    "headers": ["tuple"],
719  }, {
720    "name": "__cpp_lib_tuples_by_type",
721    "values": { "c++14": 201304 },
722    "headers": ["tuple", "utility"],
723  }, {
724    "name": "__cpp_lib_type_identity",
725    "values": { "c++20": 201806 },
726    "headers": ["type_traits"],
727  }, {
728    "name": "__cpp_lib_type_trait_variable_templates",
729    "values": { "c++17": 201510 },
730    "headers": ["type_traits"],
731  }, {
732    "name": "__cpp_lib_uncaught_exceptions",
733    "values": { "c++17": 201411 },
734    "headers": ["exception"],
735  }, {
736    "name": "__cpp_lib_unordered_map_try_emplace",
737    "values": { "c++17": 201411 },
738    "headers": ["unordered_map"],
739  }, {
740    "name": "__cpp_lib_unreachable",
741    "values": { "c++2b": 202202 },
742    "headers": ["utility"],
743  }, {
744    "name": "__cpp_lib_unwrap_ref",
745    "values": { "c++20": 201811 },
746    "headers": ["functional"],
747  }, {
748    "name": "__cpp_lib_variant",
749    "values": { "c++17": 202102 },
750    "headers": ["variant"],
751  }, {
752    "name": "__cpp_lib_void_t",
753    "values": { "c++17": 201411 },
754    "headers": ["type_traits"],
755  }
756]]
757
758assert feature_test_macros == sorted(feature_test_macros, key=lambda tc: tc["name"])
759assert all(tc["headers"] == sorted(tc["headers"]) for tc in feature_test_macros)
760assert all(("libcxx_guard" in tc) == ("test_suite_guard" in tc) for tc in feature_test_macros)
761assert all(all(key in ["name", "values", "headers", "libcxx_guard", "test_suite_guard", "unimplemented"] for key in tc.keys()) for tc in feature_test_macros)
762
763# Map from each header to the Lit annotations that should be used for
764# tests that include that header.
765#
766# For example, when threads are not supported, any test that includes
767# <thread> should be marked as UNSUPPORTED, because including <thread>
768# is a hard error in that case.
769lit_markup = {
770  "barrier": ["UNSUPPORTED: no-threads"],
771  "filesystem": ["UNSUPPORTED: no-filesystem"],
772  "format": ["UNSUPPORTED: libcpp-has-no-incomplete-format"],
773  "iomanip": ["UNSUPPORTED: no-localization"],
774  "ios": ["UNSUPPORTED: no-localization"],
775  "iostream": ["UNSUPPORTED: no-localization"],
776  "istream": ["UNSUPPORTED: no-localization"],
777  "latch": ["UNSUPPORTED: no-threads"],
778  "locale": ["UNSUPPORTED: no-localization"],
779  "mutex": ["UNSUPPORTED: no-threads"],
780  "ostream": ["UNSUPPORTED: no-localization"],
781  "ranges": ["UNSUPPORTED: libcpp-has-no-incomplete-ranges"],
782  "regex": ["UNSUPPORTED: no-localization"],
783  "semaphore": ["UNSUPPORTED: no-threads"],
784  "shared_mutex": ["UNSUPPORTED: no-threads"],
785  "stdatomic.h": ["UNSUPPORTED: no-threads"],
786  "thread": ["UNSUPPORTED: no-threads"],
787}
788
789def get_std_dialects():
790  std_dialects = ['c++14', 'c++17', 'c++20', 'c++2b']
791  return list(std_dialects)
792
793def get_first_std(d):
794    for s in get_std_dialects():
795        if s in d.keys():
796            return s
797    return None
798
799def get_last_std(d):
800  rev_dialects = get_std_dialects()
801  rev_dialects.reverse()
802  for s in rev_dialects:
803    if s in d.keys():
804      return s
805  return None
806
807def get_std_before(d, std):
808  std_dialects = get_std_dialects()
809  candidates = std_dialects[0:std_dialects.index(std)]
810  candidates.reverse()
811  for cand in candidates:
812    if cand in d.keys():
813      return cand
814  return None
815
816def get_value_before(d, std):
817  new_std = get_std_before(d, std)
818  if new_std is None:
819    return None
820  return d[new_std]
821
822def get_for_std(d, std):
823  # This catches the C++11 case for which there should be no defined feature
824  # test macros.
825  std_dialects = get_std_dialects()
826  if std not in std_dialects:
827    return None
828  # Find the value for the newest C++ dialect between C++14 and std
829  std_list = list(std_dialects[0:std_dialects.index(std)+1])
830  std_list.reverse()
831  for s in std_list:
832    if s in d.keys():
833      return d[s]
834  return None
835
836def get_std_number(std):
837    return std.replace('c++', '')
838
839"""
840  Functions to produce the <version> header
841"""
842
843def produce_macros_definition_for_std(std):
844  result = ""
845  indent = 55
846  for tc in feature_test_macros:
847    if std not in tc["values"]:
848      continue
849    inner_indent = 1
850    if 'test_suite_guard' in tc.keys():
851      result += "# if %s\n" % tc["libcxx_guard"]
852      inner_indent += 2
853    if get_value_before(tc["values"], std) is not None:
854      assert 'test_suite_guard' not in tc.keys()
855      result += "# undef  %s\n" % tc["name"]
856    line = "#%sdefine %s" % ((" " * inner_indent), tc["name"])
857    line += " " * (indent - len(line))
858    line += " %sL" % tc["values"][std]
859    if 'unimplemented' in tc.keys():
860      line = "// " + line
861    result += line
862    result += "\n"
863    if 'test_suite_guard' in tc.keys():
864      result += "# endif\n"
865  return result.strip()
866
867def produce_macros_definitions():
868  macro_definition_template = """#if _LIBCPP_STD_VER > {previous_std_number}
869{macro_definition}
870#endif"""
871
872  macros_definitions = []
873  previous_std_number = '11'
874  for std in get_std_dialects():
875    macros_definitions.append(
876      macro_definition_template.format(previous_std_number=previous_std_number,
877                                       macro_definition=produce_macros_definition_for_std(std)))
878    previous_std_number = get_std_number(std)
879
880  return '\n\n'.join(macros_definitions)
881
882def chunks(l, n):
883  """Yield successive n-sized chunks from l."""
884  for i in range(0, len(l), n):
885    yield l[i:i + n]
886
887def produce_version_synopsis():
888  indent = 56
889  header_indent = 56 + len("20XXYYL ")
890  result = ""
891  def indent_to(s, val):
892    if len(s) >= val:
893      return s
894    s += " " * (val - len(s))
895    return s
896  line = indent_to("Macro name", indent) + "Value"
897  line = indent_to(line, header_indent) + "Headers"
898  result += line + "\n"
899  for tc in feature_test_macros:
900    prev_defined_std = get_last_std(tc["values"])
901    line = "{name: <{indent}}{value}L ".format(name=tc['name'], indent=indent,
902                                               value=tc["values"][prev_defined_std])
903    headers = list(tc["headers"])
904    headers.remove("version")
905    for chunk in chunks(headers, 3):
906      line = indent_to(line, header_indent)
907      chunk = ['<%s>' % header for header in chunk]
908      line += ' '.join(chunk)
909      result += line
910      result += "\n"
911      line = ""
912    while True:
913      prev_defined_std = get_std_before(tc["values"], prev_defined_std)
914      if prev_defined_std is None:
915        break
916      result += "%s%sL // %s\n" % (indent_to("", indent), tc["values"][prev_defined_std],
917                                prev_defined_std.replace("c++", "C++"))
918  return result
919
920
921def produce_version_header():
922  template="""// -*- C++ -*-
923//===----------------------------------------------------------------------===//
924//
925// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
926// See https://llvm.org/LICENSE.txt for license information.
927// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
928//
929//===----------------------------------------------------------------------===//
930
931#ifndef _LIBCPP_VERSIONH
932#define _LIBCPP_VERSIONH
933
934/*
935  version synopsis
936
937{synopsis}
938
939*/
940
941#include <__assert> // all public C++ headers provide the assertion handler
942#include <__config>
943
944#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
945#  pragma GCC system_header
946#endif
947
948// clang-format off
949
950{cxx_macros}
951
952// clang-format on
953
954#endif // _LIBCPP_VERSIONH
955"""
956
957  version_str = template.format(
958      synopsis=produce_version_synopsis().strip(),
959      cxx_macros=produce_macros_definitions())
960  version_header_path = os.path.join(include_path, 'version')
961  with open(version_header_path, 'w', newline='\n') as f:
962    f.write(version_str)
963
964
965"""
966    Functions to produce test files
967"""
968
969test_types = {
970  "undefined": """
971# ifdef {name}
972#   error "{name} should not be defined before {std_first}"
973# endif
974""",
975
976  "test_suite_guard": """
977# if {test_suite_guard}
978#   ifndef {name}
979#     error "{name} should be defined in {std}"
980#   endif
981#   if {name} != {value}
982#     error "{name} should have the value {value} in {std}"
983#   endif
984# else
985#   ifdef {name}
986#     error "{name} should not be defined when {test_suite_guard} is not defined!"
987#   endif
988# endif
989""",
990
991  "unimplemented": """
992# if !defined(_LIBCPP_VERSION)
993#   ifndef {name}
994#     error "{name} should be defined in {std}"
995#   endif
996#   if {name} != {value}
997#     error "{name} should have the value {value} in {std}"
998#   endif
999# else // _LIBCPP_VERSION
1000#   ifdef {name}
1001#     error "{name} should not be defined because it is unimplemented in libc++!"
1002#   endif
1003# endif
1004""",
1005
1006  "defined": """
1007# ifndef {name}
1008#   error "{name} should be defined in {std}"
1009# endif
1010# if {name} != {value}
1011#   error "{name} should have the value {value} in {std}"
1012# endif
1013"""
1014}
1015
1016def generate_std_test(test_list, std):
1017  result = ""
1018  for tc in test_list:
1019    val = get_for_std(tc["values"], std)
1020    if val is not None:
1021      val = "%sL" % val
1022    if val is None:
1023      result += test_types["undefined"].format(name=tc["name"], std_first=get_first_std(tc["values"]))
1024    elif 'unimplemented' in tc.keys():
1025      result += test_types["unimplemented"].format(name=tc["name"], value=val, std=std)
1026    elif "test_suite_guard" in tc.keys():
1027      result += test_types["test_suite_guard"].format(name=tc["name"], value=val, std=std, test_suite_guard=tc["test_suite_guard"])
1028    else:
1029      result +=  test_types["defined"].format(name=tc["name"], value=val, std=std)
1030  return result.strip()
1031
1032def generate_std_tests(test_list):
1033  std_tests_template = """#if TEST_STD_VER < {first_std_number}
1034
1035{pre_std_test}
1036
1037{other_std_tests}
1038
1039#elif TEST_STD_VER > {penultimate_std_number}
1040
1041{last_std_test}
1042
1043#endif // TEST_STD_VER > {penultimate_std_number}"""
1044
1045  std_dialects = get_std_dialects()
1046  assert not get_std_number(std_dialects[-1]).isnumeric()
1047
1048  other_std_tests = []
1049  for std in std_dialects[:-1]:
1050    other_std_tests.append('#elif TEST_STD_VER == ' + get_std_number(std))
1051    other_std_tests.append(generate_std_test(test_list, std))
1052
1053  std_tests = std_tests_template.format(first_std_number=get_std_number(std_dialects[0]),
1054                                        pre_std_test=generate_std_test(test_list, 'c++11'),
1055                                        other_std_tests='\n\n'.join(other_std_tests),
1056                                        penultimate_std_number=get_std_number(std_dialects[-2]),
1057                                        last_std_test=generate_std_test(test_list, std_dialects[-1]))
1058
1059  return std_tests
1060
1061def generate_synopsis(test_list):
1062    max_name_len = max([len(tc["name"]) for tc in test_list])
1063    indent = max_name_len + 8
1064    def mk_line(prefix, suffix):
1065        return "{prefix: <{max_len}}{suffix}\n".format(prefix=prefix, suffix=suffix,
1066        max_len=indent)
1067    result = ""
1068    result += mk_line("/*  Constant", "Value")
1069    for tc in test_list:
1070        prefix = "    %s" % tc["name"]
1071        for std in [s for s in get_std_dialects() if s in tc["values"].keys()]:
1072            result += mk_line(prefix, "%sL [%s]" % (tc["values"][std], std.replace("c++", "C++")))
1073            prefix = ""
1074    result += "*/"
1075    return result
1076
1077def produce_tests():
1078  headers = set([h for tc in feature_test_macros for h in tc["headers"]])
1079  for h in headers:
1080    test_list = [tc for tc in feature_test_macros if h in tc["headers"]]
1081    if not has_header(h):
1082      for tc in test_list:
1083        assert 'unimplemented' in tc.keys()
1084      continue
1085    markup = '\n'.join('// ' + tag for tag in lit_markup.get(h, []))
1086    test_body = \
1087"""//===----------------------------------------------------------------------===//
1088//
1089// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
1090// See https://llvm.org/LICENSE.txt for license information.
1091// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
1092//
1093//===----------------------------------------------------------------------===//
1094//
1095// WARNING: This test was generated by {script_name}
1096// and should not be edited manually.
1097//
1098// clang-format off
1099{markup}
1100// <{header}>
1101
1102// Test the feature test macros defined by <{header}>
1103
1104{synopsis}
1105
1106#include <{header}>
1107#include "test_macros.h"
1108
1109{cxx_tests}
1110
1111""".format(script_name=script_name,
1112           header=h,
1113           markup=('\n{}\n'.format(markup) if markup else ''),
1114           synopsis=generate_synopsis(test_list),
1115           cxx_tests=generate_std_tests(test_list))
1116    test_name = "{header}.version.compile.pass.cpp".format(header=h)
1117    out_path = os.path.join(macro_test_path, test_name)
1118    with open(out_path, 'w', newline='\n') as f:
1119      f.write(test_body)
1120
1121"""
1122    Produce documentation for the feature test macros
1123"""
1124
1125def make_widths(grid):
1126  widths = []
1127  for i in range(0, len(grid[0])):
1128    cell_width = 2 + max(reduce(lambda x,y: x+y, [[len(row[i])] for row in grid], []))
1129    widths += [cell_width]
1130  return widths
1131
1132def create_table(grid, indent):
1133  indent_str = ' '*indent
1134  col_widths = make_widths(grid)
1135  result = [indent_str + add_divider(col_widths, 2)]
1136  header_flag = 2
1137  for row_i in range(0, len(grid)):
1138    row = grid[row_i]
1139    line = indent_str + ' '.join([pad_cell(row[i], col_widths[i]) for i in range(0, len(row))])
1140    result.append(line.rstrip())
1141    is_cxx_header = row[0].startswith('**')
1142    if row_i == len(grid) - 1:
1143      header_flag = 2
1144    separator = indent_str + add_divider(col_widths, 1 if is_cxx_header else header_flag)
1145    result.append(separator.rstrip())
1146    header_flag = 0
1147  return '\n'.join(result)
1148
1149def add_divider(widths, header_flag):
1150  if header_flag == 2:
1151    return ' '.join(['='*w for w in widths])
1152  if header_flag == 1:
1153    return '-'.join(['-'*w for w in widths])
1154  else:
1155    return ' '.join(['-'*w for w in widths])
1156
1157def pad_cell(s, length, left_align=True):
1158  padding = ((length - len(s)) * ' ')
1159  return s + padding
1160
1161
1162def get_status_table():
1163  table = [["Macro Name", "Value"]]
1164  for std in get_std_dialects():
1165    table += [["**" + std.replace("c++", "C++ ") + "**", ""]]
1166    for tc in feature_test_macros:
1167      if std not in tc["values"].keys():
1168        continue
1169      value = "``%sL``" % tc["values"][std]
1170      if 'unimplemented' in tc.keys():
1171        value = '*unimplemented*'
1172      table += [["``%s``" % tc["name"], value]]
1173  return table
1174
1175def produce_docs():
1176  doc_str = """.. _FeatureTestMacroTable:
1177
1178==========================
1179Feature Test Macro Support
1180==========================
1181
1182.. contents::
1183   :local:
1184
1185Overview
1186========
1187
1188This file documents the feature test macros currently supported by libc++.
1189
1190.. _feature-status:
1191
1192Status
1193======
1194
1195.. table:: Current Status
1196    :name: feature-status-table
1197    :widths: auto
1198
1199{status_tables}
1200
1201""".format(status_tables=create_table(get_status_table(), 4))
1202
1203  table_doc_path = os.path.join(docs_path, 'FeatureTestMacroTable.rst')
1204  with open(table_doc_path, 'w', newline='\n') as f:
1205    f.write(doc_str)
1206
1207def main():
1208  produce_version_header()
1209  produce_tests()
1210  produce_docs()
1211
1212
1213if __name__ == '__main__':
1214  main()
1215