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