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