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.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    "unimplemented": True,
78  }, {
79    "name": "__cpp_lib_allocator_traits_is_always_equal",
80    "values": { "c++17": 201411 },
81    "headers": ["deque", "forward_list", "list", "map", "memory", "scoped_allocator", "set", "string", "unordered_map", "unordered_set", "vector"],
82  }, {
83    "name": "__cpp_lib_any",
84    "values": { "c++17": 201606 },
85    "headers": ["any"],
86  }, {
87    "name": "__cpp_lib_apply",
88    "values": { "c++17": 201603 },
89    "headers": ["tuple"],
90  }, {
91    "name": "__cpp_lib_array_constexpr",
92    "values": { "c++17": 201603, "c++20": 201811 },
93    "headers": ["array", "iterator"],
94  }, {
95    "name": "__cpp_lib_as_const",
96    "values": { "c++17": 201510 },
97    "headers": ["utility"],
98  }, {
99    "name": "__cpp_lib_associative_heterogeneous_erasure",
100    "values": { "c++2b": 202110 },
101    "headers": ["map", "set", "unordered_map", "unordered_set"],
102    "unimplemented": True,
103  }, {
104    "name": "__cpp_lib_assume_aligned",
105    "values": { "c++20": 201811 },
106    "headers": ["memory"],
107    "unimplemented": True,
108  }, {
109    "name": "__cpp_lib_atomic_flag_test",
110    "values": { "c++20": 201907 },
111    "headers": ["atomic"],
112  }, {
113    "name": "__cpp_lib_atomic_float",
114    "values": { "c++20": 201711 },
115    "headers": ["atomic"],
116    "unimplemented": True,
117  }, {
118    "name": "__cpp_lib_atomic_is_always_lock_free",
119    "values": { "c++17": 201603 },
120    "headers": ["atomic"],
121  }, {
122    "name": "__cpp_lib_atomic_lock_free_type_aliases",
123    "values": { "c++20": 201907 },
124    "headers": ["atomic"],
125  }, {
126    "name": "__cpp_lib_atomic_ref",
127    "values": { "c++20": 201806 },
128    "headers": ["atomic"],
129    "unimplemented": True,
130  }, {
131    "name": "__cpp_lib_atomic_shared_ptr",
132    "values": { "c++20": 201711 },
133    "headers": ["atomic"],
134    "unimplemented": True,
135  }, {
136    "name": "__cpp_lib_atomic_value_initialization",
137    "values": { "c++20": 201911 },
138    "headers": ["atomic", "memory"],
139  }, {
140    "name": "__cpp_lib_atomic_wait",
141    "values": { "c++20": 201907 },
142    "headers": ["atomic"],
143    "test_suite_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_atomic_wait)",
144    "libcxx_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_atomic_wait)",
145  }, {
146    "name": "__cpp_lib_barrier",
147    "values": { "c++20": 201907 },
148    "headers": ["barrier"],
149    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_barrier)",
150    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_barrier)",
151  }, {
152    "name": "__cpp_lib_bind_back",
153    "values": { "c++2b": 202202 },
154    "headers": ["functional"],
155    "unimplemented": True,
156  }, {
157    "name": "__cpp_lib_bind_front",
158    "values": { "c++20": 201907 },
159    "headers": ["functional"],
160  }, {
161    "name": "__cpp_lib_bit_cast",
162    "values": { "c++20": 201806 },
163    "headers": ["bit"],
164  }, {
165    "name": "__cpp_lib_bitops",
166    "values": { "c++20": 201907 },
167    "headers": ["bit"],
168    "unimplemented": True,
169  }, {
170    "name": "__cpp_lib_bool_constant",
171    "values": { "c++17": 201505 },
172    "headers": ["type_traits"],
173  }, {
174    "name": "__cpp_lib_bounded_array_traits",
175    "values": { "c++20": 201902 },
176    "headers": ["type_traits"],
177  }, {
178    "name": "__cpp_lib_boyer_moore_searcher",
179    "values": { "c++17": 201603 },
180    "headers": ["functional"],
181    "unimplemented": True,
182  }, {
183    "name": "__cpp_lib_byte",
184    "values": { "c++17": 201603 },
185    "headers": ["cstddef"],
186  }, {
187    "name": "__cpp_lib_byteswap",
188    "values": { "c++2b": 202110 },
189    "headers": ["bit"],
190  }, {
191    "name": "__cpp_lib_char8_t",
192    "values": { "c++20": 201811 },
193    "headers": ["atomic", "filesystem", "istream", "limits", "locale", "ostream", "string", "string_view"],
194    "test_suite_guard": "defined(__cpp_char8_t)",
195    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_CHAR8_T)",
196  }, {
197    "name": "__cpp_lib_chrono",
198    "values": { "c++17": 201611 },
199    "headers": ["chrono"],
200  }, {
201    "name": "__cpp_lib_chrono_udls",
202    "values": { "c++14": 201304 },
203    "headers": ["chrono"],
204  }, {
205    "name": "__cpp_lib_clamp",
206    "values": { "c++17": 201603 },
207    "headers": ["algorithm"],
208  }, {
209    "name": "__cpp_lib_complex_udls",
210    "values": { "c++14": 201309 },
211    "headers": ["complex"],
212  }, {
213    "name": "__cpp_lib_concepts",
214    "values": { "c++20": 202002 },
215    "headers": ["concepts"],
216  }, {
217    "name": "__cpp_lib_constexpr_algorithms",
218    "values": { "c++20": 201806 },
219    "headers": ["algorithm"],
220  }, {
221    "name": "__cpp_lib_constexpr_cmath",
222    "values": { "c++2b": 202202 },
223    "headers": ["cmath", "cstdlib"],
224    "unimplemented": True,
225  }, {
226    "name": "__cpp_lib_constexpr_complex",
227    "values": { "c++20": 201711 },
228    "headers": ["complex"],
229    "unimplemented": True,
230  }, {
231    "name": "__cpp_lib_constexpr_dynamic_alloc",
232    "values": { "c++20": 201907 },
233    "headers": ["memory"],
234  }, {
235    "name": "__cpp_lib_constexpr_functional",
236    "values": { "c++20": 201907 },
237    "headers": ["functional"],
238  }, {
239    "name": "__cpp_lib_constexpr_iterator",
240    "values": { "c++20": 201811 },
241    "headers": ["iterator"],
242  }, {
243    "name": "__cpp_lib_constexpr_memory",
244    "values": { "c++20": 201811 },
245    "headers": ["memory"],
246  }, {
247    "name": "__cpp_lib_constexpr_numeric",
248    "values": { "c++20": 201911 },
249    "headers": ["numeric"],
250  }, {
251    "name": "__cpp_lib_constexpr_string",
252    "values": { "c++20": 201811 },  # because P1032R1 is implemented; but should become 201907 after P0980R1
253    "headers": ["string"],
254  }, {
255    "name": "__cpp_lib_constexpr_string_view",
256    "values": { "c++20": 201811 },
257    "headers": ["string_view"],
258  }, {
259    "name": "__cpp_lib_constexpr_tuple",
260    "values": { "c++20": 201811 },
261    "headers": ["tuple"],
262  }, {
263    "name": "__cpp_lib_constexpr_typeinfo",
264    "values": { "c++2b": 202106 },
265    "headers": ["typeinfo"],
266    "unimplemented": True,
267  }, {
268    "name": "__cpp_lib_constexpr_utility",
269    "values": { "c++20": 201811 },
270    "headers": ["utility"],
271  }, {
272    "name": "__cpp_lib_constexpr_vector",
273    "values": { "c++20": 201907 },
274    "headers": ["vector"],
275    "unimplemented": True,
276  }, {
277    "name": "__cpp_lib_coroutine",
278    "values": { "c++20": 201902 },
279    "headers": ["coroutine"],
280  }, {
281    "name": "__cpp_lib_destroying_delete",
282    "values": { "c++20": 201806 },
283    "headers": ["new"],
284    "test_suite_guard": "TEST_STD_VER > 17 && defined(__cpp_impl_destroying_delete) && __cpp_impl_destroying_delete >= 201806L",
285    "libcxx_guard": "_LIBCPP_STD_VER > 17 && defined(__cpp_impl_destroying_delete) && __cpp_impl_destroying_delete >= 201806L",
286  }, {
287    "name": "__cpp_lib_enable_shared_from_this",
288    "values": { "c++17": 201603 },
289    "headers": ["memory"],
290  }, {
291    "name": "__cpp_lib_endian",
292    "values": { "c++20": 201907 },
293    "headers": ["bit"],
294  }, {
295    "name": "__cpp_lib_erase_if",
296    "values": { "c++20": 202002 },
297    "headers": ["deque", "forward_list", "list", "map", "set", "string", "unordered_map", "unordered_set", "vector"],
298  }, {
299    "name": "__cpp_lib_exchange_function",
300    "values": { "c++14": 201304 },
301    "headers": ["utility"],
302  }, {
303    "name": "__cpp_lib_execution",
304    "values": { "c++17": 201603, "c++20": 201902 },
305    "headers": ["execution"],
306    "unimplemented": True,
307  }, {
308    "name": "__cpp_lib_filesystem",
309    "values": { "c++17": 201703 },
310    "headers": ["filesystem"],
311    "test_suite_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_filesystem)",
312    "libcxx_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_filesystem)"
313  }, {
314    "name": "__cpp_lib_format",
315    "values": { "c++20": 202106 },
316    "headers": ["format"],
317    "test_suite_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_format)",
318    "libcxx_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_format)",
319    "unimplemented": True,
320  }, {
321    "name": "__cpp_lib_gcd_lcm",
322    "values": { "c++17": 201606 },
323    "headers": ["numeric"],
324  }, {
325    "name": "__cpp_lib_generic_associative_lookup",
326    "values": { "c++14": 201304 },
327    "headers": ["map", "set"],
328  }, {
329    "name": "__cpp_lib_generic_unordered_lookup",
330    "values": { "c++20": 201811 },
331    "headers": ["unordered_map", "unordered_set"],
332  }, {
333    "name": "__cpp_lib_hardware_interference_size",
334    "values": { "c++17": 201703 },
335    "headers": ["new"],
336    "unimplemented": True,
337  }, {
338    "name": "__cpp_lib_has_unique_object_representations",
339    "values": { "c++17": 201606 },
340    "headers": ["type_traits"],
341  }, {
342    "name": "__cpp_lib_hypot",
343    "values": { "c++17": 201603 },
344    "headers": ["cmath"],
345  }, {
346    "name": "__cpp_lib_incomplete_container_elements",
347    "values": { "c++17": 201505 },
348    "headers": ["forward_list", "list", "vector"],
349  }, {
350    "name": "__cpp_lib_int_pow2",
351    "values": { "c++20": 202002 },
352    "headers": ["bit"],
353  }, {
354    "name": "__cpp_lib_integer_comparison_functions",
355    "values": { "c++20": 202002 },
356    "headers": ["utility"],
357  }, {
358    "name": "__cpp_lib_integer_sequence",
359    "values": { "c++14": 201304 },
360    "headers": ["utility"],
361  }, {
362    "name": "__cpp_lib_integral_constant_callable",
363    "values": { "c++14": 201304 },
364    "headers": ["type_traits"],
365  }, {
366    "name": "__cpp_lib_interpolate",
367    "values": { "c++20": 201902 },
368    "headers": ["cmath", "numeric"],
369  }, {
370    "name": "__cpp_lib_invoke",
371    "values": { "c++17": 201411 },
372    "headers": ["functional"],
373  }, {
374    "name": "__cpp_lib_invoke_r",
375    "values": { "c++2b": 202106 },
376    "headers": ["functional"],
377    "unimplemented": True,
378  }, {
379    "name": "__cpp_lib_is_aggregate",
380    "values": { "c++17": 201703 },
381    "headers": ["type_traits"],
382  }, {
383    "name": "__cpp_lib_is_constant_evaluated",
384    "values": { "c++20": 201811 },
385    "headers": ["type_traits"],
386  }, {
387    "name": "__cpp_lib_is_final",
388    "values": { "c++14": 201402 },
389    "headers": ["type_traits"],
390  }, {
391    "name": "__cpp_lib_is_invocable",
392    "values": { "c++17": 201703 },
393    "headers": ["type_traits"],
394  }, {
395    "name": "__cpp_lib_is_layout_compatible",
396    "values": { "c++20": 201907 },
397    "headers": ["type_traits"],
398    "unimplemented": True,
399  }, {
400    "name": "__cpp_lib_is_nothrow_convertible",
401    "values": { "c++20": 201806 },
402    "headers": ["type_traits"],
403  }, {
404    "name": "__cpp_lib_is_null_pointer",
405    "values": { "c++14": 201309 },
406    "headers": ["type_traits"],
407  }, {
408    "name": "__cpp_lib_is_pointer_interconvertible",
409    "values": { "c++20": 201907 },
410    "headers": ["type_traits"],
411    "unimplemented": True,
412  }, {
413    "name": "__cpp_lib_is_scoped_enum",
414    "values": { "c++2b": 202011 },
415    "headers": ["type_traits"],
416  }, {
417    "name": "__cpp_lib_is_swappable",
418    "values": { "c++17": 201603 },
419    "headers": ["type_traits"],
420  }, {
421    "name": "__cpp_lib_jthread",
422    "values": { "c++20": 201911 },
423    "headers": ["stop_token", "thread"],
424    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS)",
425    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS)",
426    "unimplemented": True,
427  }, {
428    "name": "__cpp_lib_latch",
429    "values": { "c++20": 201907 },
430    "headers": ["latch"],
431    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch)",
432    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch)",
433  }, {
434    "name": "__cpp_lib_launder",
435    "values": { "c++17": 201606 },
436    "headers": ["new"],
437  }, {
438    "name": "__cpp_lib_list_remove_return_type",
439    "values": { "c++20": 201806 },
440    "headers": ["forward_list", "list"],
441  }, {
442    "name": "__cpp_lib_logical_traits",
443    "values": { "c++17": 201510 },
444    "headers": ["type_traits"],
445  }, {
446    "name": "__cpp_lib_make_from_tuple",
447    "values": { "c++17": 201606 },
448    "headers": ["tuple"],
449  }, {
450    "name": "__cpp_lib_make_reverse_iterator",
451    "values": { "c++14": 201402 },
452    "headers": ["iterator"],
453  }, {
454    "name": "__cpp_lib_make_unique",
455    "values": { "c++14": 201304 },
456    "headers": ["memory"],
457  }, {
458    "name": "__cpp_lib_map_try_emplace",
459    "values": { "c++17": 201411 },
460    "headers": ["map"],
461  }, {
462    "name": "__cpp_lib_math_constants",
463    "values": { "c++20": 201907 },
464    "headers": ["numbers"],
465  }, {
466    "name": "__cpp_lib_math_special_functions",
467    "values": { "c++17": 201603 },
468    "headers": ["cmath"],
469    "unimplemented": True,
470  }, {
471    "name": "__cpp_lib_memory_resource",
472    "values": { "c++17": 201603 },
473    "headers": ["memory_resource"],
474    "unimplemented": True,
475  }, {
476    "name": "__cpp_lib_monadic_optional",
477    "values": { "c++2b": 202110 },
478    "headers": ["optional"],
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 },
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    "unimplemented": True,
528  }, {
529    "name": "__cpp_lib_ranges_chunk",
530    "values": { "c++2b": 202202 },
531    "headers": ["ranges"],
532    "unimplemented": True,
533  }, {
534    "name": "__cpp_lib_ranges_chunk_by",
535    "values": { "c++2b": 202202 },
536    "headers": ["ranges"],
537    "unimplemented": True,
538  }, {
539    "name": "__cpp_lib_ranges_iota",
540    "values": { "c++2b": 202202 },
541    "headers": ["numeric"],
542    "unimplemented": True,
543  }, {
544    "name": "__cpp_lib_ranges_join_with",
545    "values": { "c++2b": 202202 },
546    "headers": ["ranges"],
547    "unimplemented": True,
548  }, {
549    "name": "__cpp_lib_ranges_slide",
550    "values": { "c++2b": 202202 },
551    "headers": ["ranges"],
552    "unimplemented": True,
553  }, {
554    "name": "__cpp_lib_ranges_starts_ends_with",
555    "values": { "c++2b": 202106 },
556    "headers": ["algorithm"],
557    "unimplemented": True,
558  }, {
559    "name": "__cpp_lib_ranges_to_container",
560    "values": { "c++2b": 202202 },
561    "headers": ["deque", "forward_list", "list", "map", "priority_queue", "queue", "set", "stack", "string", "unordered_map", "unordered_set", "vector"],
562    "unimplemented": True,
563  }, {
564    "name": "__cpp_lib_ranges_zip",
565    "values": { "c++2b": 202110 },
566    "headers": ["ranges", "tuple", "utility"],
567    "unimplemented": True,
568  }, {
569    "name": "__cpp_lib_raw_memory_algorithms",
570    "values": { "c++17": 201606 },
571    "headers": ["memory"],
572  }, {
573    "name": "__cpp_lib_reference_from_temporary",
574    "values": { "c++2b": 202202 },
575    "headers": ["type_traits"],
576    "unimplemented": True,
577  }, {
578    "name": "__cpp_lib_remove_cvref",
579    "values": { "c++20": 201711 },
580    "headers": ["type_traits"],
581  }, {
582    "name": "__cpp_lib_result_of_sfinae",
583    "values": { "c++14": 201210 },
584    "headers": ["functional", "type_traits"],
585  }, {
586    "name": "__cpp_lib_robust_nonmodifying_seq_ops",
587    "values": { "c++14": 201304 },
588    "headers": ["algorithm"],
589  }, {
590    "name": "__cpp_lib_sample",
591    "values": { "c++17": 201603 },
592    "headers": ["algorithm"],
593  }, {
594    "name": "__cpp_lib_scoped_lock",
595    "values": { "c++17": 201703 },
596    "headers": ["mutex"],
597  }, {
598    "name": "__cpp_lib_semaphore",
599    "values": { "c++20": 201907 },
600    "headers": ["semaphore"],
601    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore)",
602    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore)",
603  }, {
604    "name": "__cpp_lib_shared_mutex",
605    "values": { "c++17": 201505 },
606    "headers": ["shared_mutex"],
607    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex)",
608    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex)",
609  }, {
610    "name": "__cpp_lib_shared_ptr_arrays",
611    "values": { "c++17": 201611, "c++20": 201707 },
612    "headers": ["memory"],
613  }, {
614    "name": "__cpp_lib_shared_ptr_weak_type",
615    "values": { "c++17": 201606 },
616    "headers": ["memory"],
617  }, {
618    "name": "__cpp_lib_shared_timed_mutex",
619    "values": { "c++14": 201402 },
620    "headers": ["shared_mutex"],
621    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex)",
622    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex)",
623  }, {
624    "name": "__cpp_lib_shift",
625    "values": { "c++20": 201806 },
626    "headers": ["algorithm"],
627  }, {
628    "name": "__cpp_lib_smart_ptr_for_overwrite",
629    "values": { "c++20": 202002 },
630    "headers": ["memory"],
631    "unimplemented": True,
632  }, {
633    "name": "__cpp_lib_source_location",
634    "values": { "c++20": 201907 },
635    "headers": ["source_location"],
636    "unimplemented": True,
637  }, {
638    "name": "__cpp_lib_span",
639    "values": { "c++20": 202002 },
640    "headers": ["span"],
641  }, {
642    "name": "__cpp_lib_spanstream",
643    "values": { "c++2b": 202106 },
644    "headers": ["spanstream"],
645    "unimplemented": True,
646  }, {
647    "name": "__cpp_lib_ssize",
648    "values": { "c++20": 201902 },
649    "headers": ["iterator"],
650  }, {
651    "name": "__cpp_lib_stacktrace",
652    "values": { "c++2b": 202011 },
653    "headers": ["stacktrace"],
654    "unimplemented": True,
655  }, {
656    "name": "__cpp_lib_starts_ends_with",
657    "values": { "c++20": 201711 },
658    "headers": ["string", "string_view"],
659  }, {
660    "name": "__cpp_lib_stdatomic_h",
661    "values": { "c++2b": 202011 },
662    "headers": ["stdatomic.h"],
663    "unimplemented": True,
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: libcpp-has-no-threads"],
771  "filesystem": ["UNSUPPORTED: libcpp-has-no-filesystem-library"],
772  "format": ["UNSUPPORTED: libcpp-has-no-incomplete-format"],
773  "iomanip": ["UNSUPPORTED: libcpp-has-no-localization"],
774  "ios": ["UNSUPPORTED: libcpp-has-no-localization"],
775  "iostream": ["UNSUPPORTED: libcpp-has-no-localization"],
776  "istream": ["UNSUPPORTED: libcpp-has-no-localization"],
777  "latch": ["UNSUPPORTED: libcpp-has-no-threads"],
778  "locale": ["UNSUPPORTED: libcpp-has-no-localization"],
779  "mutex": ["UNSUPPORTED: libcpp-has-no-threads"],
780  "ostream": ["UNSUPPORTED: libcpp-has-no-localization"],
781  "ranges": ["UNSUPPORTED: libcpp-has-no-incomplete-ranges"],
782  "regex": ["UNSUPPORTED: libcpp-has-no-localization"],
783  "semaphore": ["UNSUPPORTED: libcpp-has-no-threads"],
784  "shared_mutex": ["UNSUPPORTED: libcpp-has-no-threads"],
785  "thread": ["UNSUPPORTED: libcpp-has-no-threads"]
786}
787
788def get_std_dialects():
789  std_dialects = ['c++14', 'c++17', 'c++20', 'c++2b']
790  return list(std_dialects)
791
792def get_first_std(d):
793    for s in get_std_dialects():
794        if s in d.keys():
795            return s
796    return None
797
798def get_last_std(d):
799  rev_dialects = get_std_dialects()
800  rev_dialects.reverse()
801  for s in rev_dialects:
802    if s in d.keys():
803      return s
804  return None
805
806def get_std_before(d, std):
807  std_dialects = get_std_dialects()
808  candidates = std_dialects[0:std_dialects.index(std)]
809  candidates.reverse()
810  for cand in candidates:
811    if cand in d.keys():
812      return cand
813  return None
814
815def get_value_before(d, std):
816  new_std = get_std_before(d, std)
817  if new_std is None:
818    return None
819  return d[new_std]
820
821def get_for_std(d, std):
822  # This catches the C++11 case for which there should be no defined feature
823  # test macros.
824  std_dialects = get_std_dialects()
825  if std not in std_dialects:
826    return None
827  # Find the value for the newest C++ dialect between C++14 and std
828  std_list = list(std_dialects[0:std_dialects.index(std)+1])
829  std_list.reverse()
830  for s in std_list:
831    if s in d.keys():
832      return d[s]
833  return None
834
835def get_std_number(std):
836    return std.replace('c++', '')
837
838"""
839  Functions to produce the <version> header
840"""
841
842def produce_macros_definition_for_std(std):
843  result = ""
844  indent = 55
845  for tc in feature_test_macros:
846    if std not in tc["values"]:
847      continue
848    inner_indent = 1
849    if 'test_suite_guard' in tc.keys():
850      result += "# if %s\n" % tc["libcxx_guard"]
851      inner_indent += 2
852    if get_value_before(tc["values"], std) is not None:
853      assert 'test_suite_guard' not in tc.keys()
854      result += "# undef  %s\n" % tc["name"]
855    line = "#%sdefine %s" % ((" " * inner_indent), tc["name"])
856    line += " " * (indent - len(line))
857    line += " %sL" % tc["values"][std]
858    if 'unimplemented' in tc.keys():
859      line = "// " + line
860    result += line
861    result += "\n"
862    if 'test_suite_guard' in tc.keys():
863      result += "# endif\n"
864  return result.strip()
865
866def produce_macros_definitions():
867  macro_definition_template = """#if _LIBCPP_STD_VER > {previous_std_number}
868{macro_definition}
869#endif"""
870
871  macros_definitions = []
872  previous_std_number = '11'
873  for std in get_std_dialects():
874    macros_definitions.append(
875      macro_definition_template.format(previous_std_number=previous_std_number,
876                                       macro_definition=produce_macros_definition_for_std(std)))
877    previous_std_number = get_std_number(std)
878
879  return '\n\n'.join(macros_definitions)
880
881def chunks(l, n):
882  """Yield successive n-sized chunks from l."""
883  for i in range(0, len(l), n):
884    yield l[i:i + n]
885
886def produce_version_synopsis():
887  indent = 56
888  header_indent = 56 + len("20XXYYL ")
889  result = ""
890  def indent_to(s, val):
891    if len(s) >= val:
892      return s
893    s += " " * (val - len(s))
894    return s
895  line = indent_to("Macro name", indent) + "Value"
896  line = indent_to(line, header_indent) + "Headers"
897  result += line + "\n"
898  for tc in feature_test_macros:
899    prev_defined_std = get_last_std(tc["values"])
900    line = "{name: <{indent}}{value}L ".format(name=tc['name'], indent=indent,
901                                               value=tc["values"][prev_defined_std])
902    headers = list(tc["headers"])
903    headers.remove("version")
904    for chunk in chunks(headers, 3):
905      line = indent_to(line, header_indent)
906      chunk = ['<%s>' % header for header in chunk]
907      line += ' '.join(chunk)
908      result += line
909      result += "\n"
910      line = ""
911    while True:
912      prev_defined_std = get_std_before(tc["values"], prev_defined_std)
913      if prev_defined_std is None:
914        break
915      result += "%s%sL // %s\n" % (indent_to("", indent), tc["values"][prev_defined_std],
916                                prev_defined_std.replace("c++", "C++"))
917  return result
918
919
920def produce_version_header():
921  template="""// -*- C++ -*-
922//===----------------------------------------------------------------------===//
923//
924// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
925// See https://llvm.org/LICENSE.txt for license information.
926// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
927//
928//===----------------------------------------------------------------------===//
929
930#ifndef _LIBCPP_VERSIONH
931#define _LIBCPP_VERSIONH
932
933/*
934  version synopsis
935
936{synopsis}
937
938*/
939
940#include <__assert> // all public C++ headers provide the assertion handler
941#include <__config>
942
943#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
944#  pragma GCC system_header
945#endif
946
947// clang-format off
948
949{cxx_macros}
950
951// clang-format on
952
953#endif // _LIBCPP_VERSIONH
954"""
955
956  version_str = template.format(
957      synopsis=produce_version_synopsis().strip(),
958      cxx_macros=produce_macros_definitions())
959  version_header_path = os.path.join(include_path, 'version')
960  with open(version_header_path, 'w', newline='\n') as f:
961    f.write(version_str)
962
963
964"""
965    Functions to produce test files
966"""
967
968test_types = {
969  "undefined": """
970# ifdef {name}
971#   error "{name} should not be defined before {std_first}"
972# endif
973""",
974
975  "test_suite_guard": """
976# if {test_suite_guard}
977#   ifndef {name}
978#     error "{name} should be defined in {std}"
979#   endif
980#   if {name} != {value}
981#     error "{name} should have the value {value} in {std}"
982#   endif
983# else
984#   ifdef {name}
985#     error "{name} should not be defined when {test_suite_guard} is not defined!"
986#   endif
987# endif
988""",
989
990  "unimplemented": """
991# if !defined(_LIBCPP_VERSION)
992#   ifndef {name}
993#     error "{name} should be defined in {std}"
994#   endif
995#   if {name} != {value}
996#     error "{name} should have the value {value} in {std}"
997#   endif
998# else // _LIBCPP_VERSION
999#   ifdef {name}
1000#     error "{name} should not be defined because it is unimplemented in libc++!"
1001#   endif
1002# endif
1003""",
1004
1005  "defined": """
1006# ifndef {name}
1007#   error "{name} should be defined in {std}"
1008# endif
1009# if {name} != {value}
1010#   error "{name} should have the value {value} in {std}"
1011# endif
1012"""
1013}
1014
1015def generate_std_test(test_list, std):
1016  result = ""
1017  for tc in test_list:
1018    val = get_for_std(tc["values"], std)
1019    if val is not None:
1020      val = "%sL" % val
1021    if val is None:
1022      result += test_types["undefined"].format(name=tc["name"], std_first=get_first_std(tc["values"]))
1023    elif 'unimplemented' in tc.keys():
1024      result += test_types["unimplemented"].format(name=tc["name"], value=val, std=std)
1025    elif "test_suite_guard" in tc.keys():
1026      result += test_types["test_suite_guard"].format(name=tc["name"], value=val, std=std, test_suite_guard=tc["test_suite_guard"])
1027    else:
1028      result +=  test_types["defined"].format(name=tc["name"], value=val, std=std)
1029  return result.strip()
1030
1031def generate_std_tests(test_list):
1032  std_tests_template = """#if TEST_STD_VER < {first_std_number}
1033
1034{pre_std_test}
1035
1036{other_std_tests}
1037
1038#elif TEST_STD_VER > {penultimate_std_number}
1039
1040{last_std_test}
1041
1042#endif // TEST_STD_VER > {penultimate_std_number}"""
1043
1044  std_dialects = get_std_dialects()
1045  assert not get_std_number(std_dialects[-1]).isnumeric()
1046
1047  other_std_tests = []
1048  for std in std_dialects[:-1]:
1049    other_std_tests.append('#elif TEST_STD_VER == ' + get_std_number(std))
1050    other_std_tests.append(generate_std_test(test_list, std))
1051
1052  std_tests = std_tests_template.format(first_std_number=get_std_number(std_dialects[0]),
1053                                        pre_std_test=generate_std_test(test_list, 'c++11'),
1054                                        other_std_tests='\n\n'.join(other_std_tests),
1055                                        penultimate_std_number=get_std_number(std_dialects[-2]),
1056                                        last_std_test=generate_std_test(test_list, std_dialects[-1]))
1057
1058  return std_tests
1059
1060def generate_synopsis(test_list):
1061    max_name_len = max([len(tc["name"]) for tc in test_list])
1062    indent = max_name_len + 8
1063    def mk_line(prefix, suffix):
1064        return "{prefix: <{max_len}}{suffix}\n".format(prefix=prefix, suffix=suffix,
1065        max_len=indent)
1066    result = ""
1067    result += mk_line("/*  Constant", "Value")
1068    for tc in test_list:
1069        prefix = "    %s" % tc["name"]
1070        for std in [s for s in get_std_dialects() if s in tc["values"].keys()]:
1071            result += mk_line(prefix, "%sL [%s]" % (tc["values"][std], std.replace("c++", "C++")))
1072            prefix = ""
1073    result += "*/"
1074    return result
1075
1076def produce_tests():
1077  headers = set([h for tc in feature_test_macros for h in tc["headers"]])
1078  for h in headers:
1079    test_list = [tc for tc in feature_test_macros if h in tc["headers"]]
1080    if not has_header(h):
1081      for tc in test_list:
1082        assert 'unimplemented' in tc.keys()
1083      continue
1084    markup = '\n'.join('// ' + tag for tag in lit_markup.get(h, []))
1085    test_body = \
1086"""//===----------------------------------------------------------------------===//
1087//
1088// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
1089// See https://llvm.org/LICENSE.txt for license information.
1090// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
1091//
1092//===----------------------------------------------------------------------===//
1093//
1094// WARNING: This test was generated by {script_name}
1095// and should not be edited manually.
1096//
1097// clang-format off
1098{markup}
1099// <{header}>
1100
1101// Test the feature test macros defined by <{header}>
1102
1103{synopsis}
1104
1105#include <{header}>
1106#include "test_macros.h"
1107
1108{cxx_tests}
1109
1110int main(int, char**) {{ return 0; }}
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.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