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": 201811 },
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": { "c++20": 202106 },
313    "headers": ["format"],
314    "test_suite_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_format)",
315    "libcxx_guard": "!defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_format)",
316    "unimplemented": True,
317  }, {
318    "name": "__cpp_lib_gcd_lcm",
319    "values": { "c++17": 201606 },
320    "headers": ["numeric"],
321  }, {
322    "name": "__cpp_lib_generic_associative_lookup",
323    "values": { "c++14": 201304 },
324    "headers": ["map", "set"],
325  }, {
326    "name": "__cpp_lib_generic_unordered_lookup",
327    "values": { "c++20": 201811 },
328    "headers": ["unordered_map", "unordered_set"],
329  }, {
330    "name": "__cpp_lib_hardware_interference_size",
331    "values": { "c++17": 201703 },
332    "headers": ["new"],
333    "unimplemented": True,
334  }, {
335    "name": "__cpp_lib_has_unique_object_representations",
336    "values": { "c++17": 201606 },
337    "headers": ["type_traits"],
338  }, {
339    "name": "__cpp_lib_hypot",
340    "values": { "c++17": 201603 },
341    "headers": ["cmath"],
342  }, {
343    "name": "__cpp_lib_incomplete_container_elements",
344    "values": { "c++17": 201505 },
345    "headers": ["forward_list", "list", "vector"],
346  }, {
347    "name": "__cpp_lib_int_pow2",
348    "values": { "c++20": 202002 },
349    "headers": ["bit"],
350  }, {
351    "name": "__cpp_lib_integer_comparison_functions",
352    "values": { "c++20": 202002 },
353    "headers": ["utility"],
354  }, {
355    "name": "__cpp_lib_integer_sequence",
356    "values": { "c++14": 201304 },
357    "headers": ["utility"],
358  }, {
359    "name": "__cpp_lib_integral_constant_callable",
360    "values": { "c++14": 201304 },
361    "headers": ["type_traits"],
362  }, {
363    "name": "__cpp_lib_interpolate",
364    "values": { "c++20": 201902 },
365    "headers": ["cmath", "numeric"],
366  }, {
367    "name": "__cpp_lib_invoke",
368    "values": { "c++17": 201411 },
369    "headers": ["functional"],
370  }, {
371    "name": "__cpp_lib_invoke_r",
372    "values": { "c++2b": 202106 },
373    "headers": ["functional"],
374    "unimplemented": True,
375  }, {
376    "name": "__cpp_lib_is_aggregate",
377    "values": { "c++17": 201703 },
378    "headers": ["type_traits"],
379  }, {
380    "name": "__cpp_lib_is_constant_evaluated",
381    "values": { "c++20": 201811 },
382    "headers": ["type_traits"],
383  }, {
384    "name": "__cpp_lib_is_final",
385    "values": { "c++14": 201402 },
386    "headers": ["type_traits"],
387  }, {
388    "name": "__cpp_lib_is_invocable",
389    "values": { "c++17": 201703 },
390    "headers": ["type_traits"],
391  }, {
392    "name": "__cpp_lib_is_layout_compatible",
393    "values": { "c++20": 201907 },
394    "headers": ["type_traits"],
395    "unimplemented": True,
396  }, {
397    "name": "__cpp_lib_is_nothrow_convertible",
398    "values": { "c++20": 201806 },
399    "headers": ["type_traits"],
400  }, {
401    "name": "__cpp_lib_is_null_pointer",
402    "values": { "c++14": 201309 },
403    "headers": ["type_traits"],
404  }, {
405    "name": "__cpp_lib_is_pointer_interconvertible",
406    "values": { "c++20": 201907 },
407    "headers": ["type_traits"],
408    "unimplemented": True,
409  }, {
410    "name": "__cpp_lib_is_scoped_enum",
411    "values": { "c++2b": 202011 },
412    "headers": ["type_traits"],
413  }, {
414    "name": "__cpp_lib_is_swappable",
415    "values": { "c++17": 201603 },
416    "headers": ["type_traits"],
417  }, {
418    "name": "__cpp_lib_jthread",
419    "values": { "c++20": 201911 },
420    "headers": ["stop_token", "thread"],
421    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS)",
422    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS)",
423    "unimplemented": True,
424  }, {
425    "name": "__cpp_lib_latch",
426    "values": { "c++20": 201907 },
427    "headers": ["latch"],
428    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch)",
429    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch)",
430  }, {
431    "name": "__cpp_lib_launder",
432    "values": { "c++17": 201606 },
433    "headers": ["new"],
434  }, {
435    "name": "__cpp_lib_list_remove_return_type",
436    "values": { "c++20": 201806 },
437    "headers": ["forward_list", "list"],
438  }, {
439    "name": "__cpp_lib_logical_traits",
440    "values": { "c++17": 201510 },
441    "headers": ["type_traits"],
442  }, {
443    "name": "__cpp_lib_make_from_tuple",
444    "values": { "c++17": 201606 },
445    "headers": ["tuple"],
446  }, {
447    "name": "__cpp_lib_make_reverse_iterator",
448    "values": { "c++14": 201402 },
449    "headers": ["iterator"],
450  }, {
451    "name": "__cpp_lib_make_unique",
452    "values": { "c++14": 201304 },
453    "headers": ["memory"],
454  }, {
455    "name": "__cpp_lib_map_try_emplace",
456    "values": { "c++17": 201411 },
457    "headers": ["map"],
458  }, {
459    "name": "__cpp_lib_math_constants",
460    "values": { "c++20": 201907 },
461    "headers": ["numbers"],
462  }, {
463    "name": "__cpp_lib_math_special_functions",
464    "values": { "c++17": 201603 },
465    "headers": ["cmath"],
466    "unimplemented": True,
467  }, {
468    "name": "__cpp_lib_memory_resource",
469    "values": { "c++17": 201603 },
470    "headers": ["memory_resource"],
471    "unimplemented": True,
472  }, {
473    "name": "__cpp_lib_move_only_function",
474    "values": { "c++2b": 202110 },
475    "headers": ["functional"],
476    "unimplemented": True,
477  }, {
478    "name": "__cpp_lib_node_extract",
479    "values": { "c++17": 201606 },
480    "headers": ["map", "set", "unordered_map", "unordered_set"],
481  }, {
482    "name": "__cpp_lib_nonmember_container_access",
483    "values": { "c++17": 201411 },
484    "headers": ["array", "deque", "forward_list", "iterator", "list", "map", "regex", "set", "string", "unordered_map", "unordered_set", "vector"],
485  }, {
486    "name": "__cpp_lib_not_fn",
487    "values": { "c++17": 201603 },
488    "headers": ["functional"],
489  }, {
490    "name": "__cpp_lib_null_iterators",
491    "values": { "c++14": 201304 },
492    "headers": ["iterator"],
493  }, {
494    "name": "__cpp_lib_optional",
495    "values": { "c++17": 201606, "c++2b": 202110 },
496    "headers": ["optional"],
497  }, {
498    "name": "__cpp_lib_out_ptr",
499    "values": { "c++2b": 202106 },
500    "headers": ["memory"],
501    "unimplemented": True,
502  }, {
503    "name": "__cpp_lib_parallel_algorithm",
504    "values": { "c++17": 201603 },
505    "headers": ["algorithm", "numeric"],
506    "unimplemented": True,
507  }, {
508    "name": "__cpp_lib_polymorphic_allocator",
509    "values": { "c++20": 201902 },
510    "headers": ["memory_resource"],
511    "unimplemented": True,
512  }, {
513    "name": "__cpp_lib_quoted_string_io",
514    "values": { "c++14": 201304 },
515    "headers": ["iomanip"],
516  }, {
517    "name": "__cpp_lib_ranges",
518    "values": { "c++20": 201811 },
519    "headers": ["algorithm", "functional", "iterator", "memory", "ranges"],
520    "unimplemented": True,
521  }, {
522    "name": "__cpp_lib_ranges_chunk",
523    "values": { "c++2b": 202202 },
524    "headers": ["ranges"],
525    "unimplemented": True,
526  }, {
527    "name": "__cpp_lib_ranges_chunk_by",
528    "values": { "c++2b": 202202 },
529    "headers": ["ranges"],
530    "unimplemented": True,
531  }, {
532    "name": "__cpp_lib_ranges_iota",
533    "values": { "c++2b": 202202 },
534    "headers": ["numeric"],
535    "unimplemented": True,
536  }, {
537    "name": "__cpp_lib_ranges_join_with",
538    "values": { "c++2b": 202202 },
539    "headers": ["ranges"],
540    "unimplemented": True,
541  }, {
542    "name": "__cpp_lib_ranges_slide",
543    "values": { "c++2b": 202202 },
544    "headers": ["ranges"],
545    "unimplemented": True,
546  }, {
547    "name": "__cpp_lib_ranges_starts_ends_with",
548    "values": { "c++2b": 202106 },
549    "headers": ["algorithm"],
550    "unimplemented": True,
551  }, {
552    "name": "__cpp_lib_ranges_to_container",
553    "values": { "c++2b": 202202 },
554    "headers": ["deque", "forward_list", "list", "map", "priority_queue", "queue", "set", "stack", "string", "unordered_map", "unordered_set", "vector"],
555    "unimplemented": True,
556  }, {
557    "name": "__cpp_lib_ranges_zip",
558    "values": { "c++2b": 202110 },
559    "headers": ["ranges", "tuple", "utility"],
560    "unimplemented": True,
561  }, {
562    "name": "__cpp_lib_raw_memory_algorithms",
563    "values": { "c++17": 201606 },
564    "headers": ["memory"],
565  }, {
566    "name": "__cpp_lib_reference_from_temporary",
567    "values": { "c++2b": 202202 },
568    "headers": ["type_traits"],
569    "unimplemented": True,
570  }, {
571    "name": "__cpp_lib_remove_cvref",
572    "values": { "c++20": 201711 },
573    "headers": ["type_traits"],
574  }, {
575    "name": "__cpp_lib_result_of_sfinae",
576    "values": { "c++14": 201210 },
577    "headers": ["functional", "type_traits"],
578  }, {
579    "name": "__cpp_lib_robust_nonmodifying_seq_ops",
580    "values": { "c++14": 201304 },
581    "headers": ["algorithm"],
582  }, {
583    "name": "__cpp_lib_sample",
584    "values": { "c++17": 201603 },
585    "headers": ["algorithm"],
586  }, {
587    "name": "__cpp_lib_scoped_lock",
588    "values": { "c++17": 201703 },
589    "headers": ["mutex"],
590  }, {
591    "name": "__cpp_lib_semaphore",
592    "values": { "c++20": 201907 },
593    "headers": ["semaphore"],
594    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore)",
595    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore)",
596  }, {
597    "name": "__cpp_lib_shared_mutex",
598    "values": { "c++17": 201505 },
599    "headers": ["shared_mutex"],
600    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex)",
601    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex)",
602  }, {
603    "name": "__cpp_lib_shared_ptr_arrays",
604    "values": { "c++17": 201611, "c++20": 201707 },
605    "headers": ["memory"],
606  }, {
607    "name": "__cpp_lib_shared_ptr_weak_type",
608    "values": { "c++17": 201606 },
609    "headers": ["memory"],
610  }, {
611    "name": "__cpp_lib_shared_timed_mutex",
612    "values": { "c++14": 201402 },
613    "headers": ["shared_mutex"],
614    "test_suite_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex)",
615    "libcxx_guard": "!defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex)",
616  }, {
617    "name": "__cpp_lib_shift",
618    "values": { "c++20": 201806 },
619    "headers": ["algorithm"],
620  }, {
621    "name": "__cpp_lib_smart_ptr_for_overwrite",
622    "values": { "c++20": 202002 },
623    "headers": ["memory"],
624    "unimplemented": True,
625  }, {
626    "name": "__cpp_lib_source_location",
627    "values": { "c++20": 201907 },
628    "headers": ["source_location"],
629    "unimplemented": True,
630  }, {
631    "name": "__cpp_lib_span",
632    "values": { "c++20": 202002 },
633    "headers": ["span"],
634  }, {
635    "name": "__cpp_lib_spanstream",
636    "values": { "c++2b": 202106 },
637    "headers": ["spanstream"],
638    "unimplemented": True,
639  }, {
640    "name": "__cpp_lib_ssize",
641    "values": { "c++20": 201902 },
642    "headers": ["iterator"],
643  }, {
644    "name": "__cpp_lib_stacktrace",
645    "values": { "c++2b": 202011 },
646    "headers": ["stacktrace"],
647    "unimplemented": True,
648  }, {
649    "name": "__cpp_lib_starts_ends_with",
650    "values": { "c++20": 201711 },
651    "headers": ["string", "string_view"],
652  }, {
653    "name": "__cpp_lib_stdatomic_h",
654    "values": { "c++2b": 202011 },
655    "headers": ["stdatomic.h"],
656  }, {
657    "name": "__cpp_lib_string_contains",
658    "values": { "c++2b": 202011 },
659    "headers": ["string", "string_view"],
660  }, {
661    "name": "__cpp_lib_string_resize_and_overwrite",
662    "values": { "c++2b": 202110 },
663    "headers": ["string"],
664  }, {
665    "name": "__cpp_lib_string_udls",
666    "values": { "c++14": 201304 },
667    "headers": ["string"],
668  }, {
669    "name": "__cpp_lib_string_view",
670    "values": { "c++17": 201606, "c++20": 201803 },
671    "headers": ["string", "string_view"],
672  }, {
673    "name": "__cpp_lib_syncbuf",
674    "values": { "c++20": 201803 },
675    "headers": ["syncstream"],
676    "unimplemented": True,
677  }, {
678    "name": "__cpp_lib_three_way_comparison",
679    "values": { "c++20": 201907 },
680    "headers": ["compare"],
681    "unimplemented": True,
682  }, {
683    "name": "__cpp_lib_to_address",
684    "values": { "c++20": 201711 },
685    "headers": ["memory"],
686  }, {
687    "name": "__cpp_lib_to_array",
688    "values": { "c++20": 201907 },
689    "headers": ["array"],
690  }, {
691    "name": "__cpp_lib_to_chars",
692    "values": { "c++17": 201611 },
693    "headers": ["charconv"],
694    "unimplemented": True,
695  }, {
696    "name": "__cpp_lib_to_underlying",
697    "values": { "c++2b": 202102 },
698    "headers": ["utility"],
699  }, {
700    "name": "__cpp_lib_transformation_trait_aliases",
701    "values": { "c++14": 201304 },
702    "headers": ["type_traits"],
703  }, {
704    "name": "__cpp_lib_transparent_operators",
705    "values": { "c++14": 201210, "c++17": 201510 },
706    "headers": ["functional", "memory"],
707  }, {
708    "name": "__cpp_lib_tuple_element_t",
709    "values": { "c++14": 201402 },
710    "headers": ["tuple"],
711  }, {
712    "name": "__cpp_lib_tuples_by_type",
713    "values": { "c++14": 201304 },
714    "headers": ["tuple", "utility"],
715  }, {
716    "name": "__cpp_lib_type_identity",
717    "values": { "c++20": 201806 },
718    "headers": ["type_traits"],
719  }, {
720    "name": "__cpp_lib_type_trait_variable_templates",
721    "values": { "c++17": 201510 },
722    "headers": ["type_traits"],
723  }, {
724    "name": "__cpp_lib_uncaught_exceptions",
725    "values": { "c++17": 201411 },
726    "headers": ["exception"],
727  }, {
728    "name": "__cpp_lib_unordered_map_try_emplace",
729    "values": { "c++17": 201411 },
730    "headers": ["unordered_map"],
731  }, {
732    "name": "__cpp_lib_unreachable",
733    "values": { "c++2b": 202202 },
734    "headers": ["utility"],
735  }, {
736    "name": "__cpp_lib_unwrap_ref",
737    "values": { "c++20": 201811 },
738    "headers": ["functional"],
739  }, {
740    "name": "__cpp_lib_variant",
741    "values": { "c++17": 202102 },
742    "headers": ["variant"],
743  }, {
744    "name": "__cpp_lib_void_t",
745    "values": { "c++17": 201411 },
746    "headers": ["type_traits"],
747  }
748]]
749
750assert feature_test_macros == sorted(feature_test_macros, key=lambda tc: tc["name"])
751assert all(tc["headers"] == sorted(tc["headers"]) for tc in feature_test_macros)
752assert all(("libcxx_guard" in tc) == ("test_suite_guard" in tc) for tc in feature_test_macros)
753assert all(all(key in ["name", "values", "headers", "libcxx_guard", "test_suite_guard", "unimplemented"] for key in tc.keys()) for tc in feature_test_macros)
754
755# Map from each header to the Lit annotations that should be used for
756# tests that include that header.
757#
758# For example, when threads are not supported, any test that includes
759# <thread> should be marked as UNSUPPORTED, because including <thread>
760# is a hard error in that case.
761lit_markup = {
762  "barrier": ["UNSUPPORTED: no-threads"],
763  "filesystem": ["UNSUPPORTED: no-filesystem"],
764  "format": ["UNSUPPORTED: libcpp-has-no-incomplete-format"],
765  "iomanip": ["UNSUPPORTED: no-localization"],
766  "ios": ["UNSUPPORTED: no-localization"],
767  "iostream": ["UNSUPPORTED: no-localization"],
768  "istream": ["UNSUPPORTED: no-localization"],
769  "latch": ["UNSUPPORTED: no-threads"],
770  "locale": ["UNSUPPORTED: no-localization"],
771  "mutex": ["UNSUPPORTED: no-threads"],
772  "ostream": ["UNSUPPORTED: no-localization"],
773  "ranges": ["UNSUPPORTED: libcpp-has-no-incomplete-ranges"],
774  "regex": ["UNSUPPORTED: no-localization"],
775  "semaphore": ["UNSUPPORTED: no-threads"],
776  "shared_mutex": ["UNSUPPORTED: no-threads"],
777  "stdatomic.h": ["UNSUPPORTED: no-threads"],
778  "thread": ["UNSUPPORTED: no-threads"],
779}
780
781def get_std_dialects():
782  std_dialects = ['c++14', 'c++17', 'c++20', 'c++2b']
783  return list(std_dialects)
784
785def get_first_std(d):
786    for s in get_std_dialects():
787        if s in d.keys():
788            return s
789    return None
790
791def get_last_std(d):
792  rev_dialects = get_std_dialects()
793  rev_dialects.reverse()
794  for s in rev_dialects:
795    if s in d.keys():
796      return s
797  return None
798
799def get_std_before(d, std):
800  std_dialects = get_std_dialects()
801  candidates = std_dialects[0:std_dialects.index(std)]
802  candidates.reverse()
803  for cand in candidates:
804    if cand in d.keys():
805      return cand
806  return None
807
808def get_value_before(d, std):
809  new_std = get_std_before(d, std)
810  if new_std is None:
811    return None
812  return d[new_std]
813
814def get_for_std(d, std):
815  # This catches the C++11 case for which there should be no defined feature
816  # test macros.
817  std_dialects = get_std_dialects()
818  if std not in std_dialects:
819    return None
820  # Find the value for the newest C++ dialect between C++14 and std
821  std_list = list(std_dialects[0:std_dialects.index(std)+1])
822  std_list.reverse()
823  for s in std_list:
824    if s in d.keys():
825      return d[s]
826  return None
827
828def get_std_number(std):
829    return std.replace('c++', '')
830
831"""
832  Functions to produce the <version> header
833"""
834
835def produce_macros_definition_for_std(std):
836  result = ""
837  indent = 55
838  for tc in feature_test_macros:
839    if std not in tc["values"]:
840      continue
841    inner_indent = 1
842    if 'test_suite_guard' in tc.keys():
843      result += "# if %s\n" % tc["libcxx_guard"]
844      inner_indent += 2
845    if get_value_before(tc["values"], std) is not None:
846      assert 'test_suite_guard' not in tc.keys()
847      result += "# undef  %s\n" % tc["name"]
848    line = "#%sdefine %s" % ((" " * inner_indent), tc["name"])
849    line += " " * (indent - len(line))
850    line += " %sL" % tc["values"][std]
851    if 'unimplemented' in tc.keys():
852      line = "// " + line
853    result += line
854    result += "\n"
855    if 'test_suite_guard' in tc.keys():
856      result += "# endif\n"
857  return result.strip()
858
859def produce_macros_definitions():
860  macro_definition_template = """#if _LIBCPP_STD_VER > {previous_std_number}
861{macro_definition}
862#endif"""
863
864  macros_definitions = []
865  previous_std_number = '11'
866  for std in get_std_dialects():
867    macros_definitions.append(
868      macro_definition_template.format(previous_std_number=previous_std_number,
869                                       macro_definition=produce_macros_definition_for_std(std)))
870    previous_std_number = get_std_number(std)
871
872  return '\n\n'.join(macros_definitions)
873
874def chunks(l, n):
875  """Yield successive n-sized chunks from l."""
876  for i in range(0, len(l), n):
877    yield l[i:i + n]
878
879def produce_version_synopsis():
880  indent = 56
881  header_indent = 56 + len("20XXYYL ")
882  result = ""
883  def indent_to(s, val):
884    if len(s) >= val:
885      return s
886    s += " " * (val - len(s))
887    return s
888  line = indent_to("Macro name", indent) + "Value"
889  line = indent_to(line, header_indent) + "Headers"
890  result += line + "\n"
891  for tc in feature_test_macros:
892    prev_defined_std = get_last_std(tc["values"])
893    line = "{name: <{indent}}{value}L ".format(name=tc['name'], indent=indent,
894                                               value=tc["values"][prev_defined_std])
895    headers = list(tc["headers"])
896    headers.remove("version")
897    for chunk in chunks(headers, 3):
898      line = indent_to(line, header_indent)
899      chunk = ['<%s>' % header for header in chunk]
900      line += ' '.join(chunk)
901      result += line
902      result += "\n"
903      line = ""
904    while True:
905      prev_defined_std = get_std_before(tc["values"], prev_defined_std)
906      if prev_defined_std is None:
907        break
908      result += "%s%sL // %s\n" % (indent_to("", indent), tc["values"][prev_defined_std],
909                                prev_defined_std.replace("c++", "C++"))
910  return result
911
912
913def produce_version_header():
914  template="""// -*- C++ -*-
915//===----------------------------------------------------------------------===//
916//
917// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
918// See https://llvm.org/LICENSE.txt for license information.
919// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
920//
921//===----------------------------------------------------------------------===//
922
923#ifndef _LIBCPP_VERSIONH
924#define _LIBCPP_VERSIONH
925
926/*
927  version synopsis
928
929{synopsis}
930
931*/
932
933#include <__assert> // all public C++ headers provide the assertion handler
934#include <__config>
935
936#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
937#  pragma GCC system_header
938#endif
939
940// clang-format off
941
942{cxx_macros}
943
944// clang-format on
945
946#endif // _LIBCPP_VERSIONH
947"""
948
949  version_str = template.format(
950      synopsis=produce_version_synopsis().strip(),
951      cxx_macros=produce_macros_definitions())
952  version_header_path = os.path.join(include_path, 'version')
953  with open(version_header_path, 'w', newline='\n') as f:
954    f.write(version_str)
955
956
957"""
958    Functions to produce test files
959"""
960
961test_types = {
962  "undefined": """
963# ifdef {name}
964#   error "{name} should not be defined before {std_first}"
965# endif
966""",
967
968  "test_suite_guard": """
969# if {test_suite_guard}
970#   ifndef {name}
971#     error "{name} should be defined in {std}"
972#   endif
973#   if {name} != {value}
974#     error "{name} should have the value {value} in {std}"
975#   endif
976# else
977#   ifdef {name}
978#     error "{name} should not be defined when {test_suite_guard} is not defined!"
979#   endif
980# endif
981""",
982
983  "unimplemented": """
984# if !defined(_LIBCPP_VERSION)
985#   ifndef {name}
986#     error "{name} should be defined in {std}"
987#   endif
988#   if {name} != {value}
989#     error "{name} should have the value {value} in {std}"
990#   endif
991# else // _LIBCPP_VERSION
992#   ifdef {name}
993#     error "{name} should not be defined because it is unimplemented in libc++!"
994#   endif
995# endif
996""",
997
998  "defined": """
999# ifndef {name}
1000#   error "{name} should be defined in {std}"
1001# endif
1002# if {name} != {value}
1003#   error "{name} should have the value {value} in {std}"
1004# endif
1005"""
1006}
1007
1008def generate_std_test(test_list, std):
1009  result = ""
1010  for tc in test_list:
1011    val = get_for_std(tc["values"], std)
1012    if val is not None:
1013      val = "%sL" % val
1014    if val is None:
1015      result += test_types["undefined"].format(name=tc["name"], std_first=get_first_std(tc["values"]))
1016    elif 'unimplemented' in tc.keys():
1017      result += test_types["unimplemented"].format(name=tc["name"], value=val, std=std)
1018    elif "test_suite_guard" in tc.keys():
1019      result += test_types["test_suite_guard"].format(name=tc["name"], value=val, std=std, test_suite_guard=tc["test_suite_guard"])
1020    else:
1021      result +=  test_types["defined"].format(name=tc["name"], value=val, std=std)
1022  return result.strip()
1023
1024def generate_std_tests(test_list):
1025  std_tests_template = """#if TEST_STD_VER < {first_std_number}
1026
1027{pre_std_test}
1028
1029{other_std_tests}
1030
1031#elif TEST_STD_VER > {penultimate_std_number}
1032
1033{last_std_test}
1034
1035#endif // TEST_STD_VER > {penultimate_std_number}"""
1036
1037  std_dialects = get_std_dialects()
1038  assert not get_std_number(std_dialects[-1]).isnumeric()
1039
1040  other_std_tests = []
1041  for std in std_dialects[:-1]:
1042    other_std_tests.append('#elif TEST_STD_VER == ' + get_std_number(std))
1043    other_std_tests.append(generate_std_test(test_list, std))
1044
1045  std_tests = std_tests_template.format(first_std_number=get_std_number(std_dialects[0]),
1046                                        pre_std_test=generate_std_test(test_list, 'c++11'),
1047                                        other_std_tests='\n\n'.join(other_std_tests),
1048                                        penultimate_std_number=get_std_number(std_dialects[-2]),
1049                                        last_std_test=generate_std_test(test_list, std_dialects[-1]))
1050
1051  return std_tests
1052
1053def generate_synopsis(test_list):
1054    max_name_len = max([len(tc["name"]) for tc in test_list])
1055    indent = max_name_len + 8
1056    def mk_line(prefix, suffix):
1057        return "{prefix: <{max_len}}{suffix}\n".format(prefix=prefix, suffix=suffix,
1058        max_len=indent)
1059    result = ""
1060    result += mk_line("/*  Constant", "Value")
1061    for tc in test_list:
1062        prefix = "    %s" % tc["name"]
1063        for std in [s for s in get_std_dialects() if s in tc["values"].keys()]:
1064            result += mk_line(prefix, "%sL [%s]" % (tc["values"][std], std.replace("c++", "C++")))
1065            prefix = ""
1066    result += "*/"
1067    return result
1068
1069def produce_tests():
1070  headers = set([h for tc in feature_test_macros for h in tc["headers"]])
1071  for h in headers:
1072    test_list = [tc for tc in feature_test_macros if h in tc["headers"]]
1073    if not has_header(h):
1074      for tc in test_list:
1075        assert 'unimplemented' in tc.keys()
1076      continue
1077    markup = '\n'.join('// ' + tag for tag in lit_markup.get(h, []))
1078    test_body = \
1079"""//===----------------------------------------------------------------------===//
1080//
1081// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
1082// See https://llvm.org/LICENSE.txt for license information.
1083// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
1084//
1085//===----------------------------------------------------------------------===//
1086//
1087// WARNING: This test was generated by {script_name}
1088// and should not be edited manually.
1089//
1090// clang-format off
1091{markup}
1092// <{header}>
1093
1094// Test the feature test macros defined by <{header}>
1095
1096{synopsis}
1097
1098#include <{header}>
1099#include "test_macros.h"
1100
1101{cxx_tests}
1102
1103""".format(script_name=script_name,
1104           header=h,
1105           markup=('\n{}\n'.format(markup) if markup else ''),
1106           synopsis=generate_synopsis(test_list),
1107           cxx_tests=generate_std_tests(test_list))
1108    test_name = "{header}.version.compile.pass.cpp".format(header=h)
1109    out_path = os.path.join(macro_test_path, test_name)
1110    with open(out_path, 'w', newline='\n') as f:
1111      f.write(test_body)
1112
1113"""
1114    Produce documentation for the feature test macros
1115"""
1116
1117def make_widths(grid):
1118  widths = []
1119  for i in range(0, len(grid[0])):
1120    cell_width = 2 + max(reduce(lambda x,y: x+y, [[len(row[i])] for row in grid], []))
1121    widths += [cell_width]
1122  return widths
1123
1124def create_table(grid, indent):
1125  indent_str = ' '*indent
1126  col_widths = make_widths(grid)
1127  result = [indent_str + add_divider(col_widths, 2)]
1128  header_flag = 2
1129  for row_i in range(0, len(grid)):
1130    row = grid[row_i]
1131    line = indent_str + ' '.join([pad_cell(row[i], col_widths[i]) for i in range(0, len(row))])
1132    result.append(line.rstrip())
1133    is_cxx_header = row[0].startswith('**')
1134    if row_i == len(grid) - 1:
1135      header_flag = 2
1136    separator = indent_str + add_divider(col_widths, 1 if is_cxx_header else header_flag)
1137    result.append(separator.rstrip())
1138    header_flag = 0
1139  return '\n'.join(result)
1140
1141def add_divider(widths, header_flag):
1142  if header_flag == 2:
1143    return ' '.join(['='*w for w in widths])
1144  if header_flag == 1:
1145    return '-'.join(['-'*w for w in widths])
1146  else:
1147    return ' '.join(['-'*w for w in widths])
1148
1149def pad_cell(s, length, left_align=True):
1150  padding = ((length - len(s)) * ' ')
1151  return s + padding
1152
1153
1154def get_status_table():
1155  table = [["Macro Name", "Value"]]
1156  for std in get_std_dialects():
1157    table += [["**" + std.replace("c++", "C++ ") + "**", ""]]
1158    for tc in feature_test_macros:
1159      if std not in tc["values"].keys():
1160        continue
1161      value = "``%sL``" % tc["values"][std]
1162      if 'unimplemented' in tc.keys():
1163        value = '*unimplemented*'
1164      table += [["``%s``" % tc["name"], value]]
1165  return table
1166
1167def produce_docs():
1168  doc_str = """.. _FeatureTestMacroTable:
1169
1170==========================
1171Feature Test Macro Support
1172==========================
1173
1174.. contents::
1175   :local:
1176
1177Overview
1178========
1179
1180This file documents the feature test macros currently supported by libc++.
1181
1182.. _feature-status:
1183
1184Status
1185======
1186
1187.. table:: Current Status
1188    :name: feature-status-table
1189    :widths: auto
1190
1191{status_tables}
1192
1193""".format(status_tables=create_table(get_status_table(), 4))
1194
1195  table_doc_path = os.path.join(docs_path, 'FeatureTestMacroTable.rst')
1196  with open(table_doc_path, 'w', newline='\n') as f:
1197    f.write(doc_str)
1198
1199def main():
1200  produce_version_header()
1201  produce_tests()
1202  produce_docs()
1203
1204
1205if __name__ == '__main__':
1206  main()
1207