1#!/usr/bin/env python
2
3import contextlib
4import glob
5import io
6import os
7import pathlib
8import re
9
10header_restrictions = {
11    "barrier": "!defined(_LIBCPP_HAS_NO_THREADS)",
12    "future": "!defined(_LIBCPP_HAS_NO_THREADS)",
13    "latch": "!defined(_LIBCPP_HAS_NO_THREADS)",
14    "mutex": "!defined(_LIBCPP_HAS_NO_THREADS)",
15    "semaphore": "!defined(_LIBCPP_HAS_NO_THREADS)",
16    "shared_mutex": "!defined(_LIBCPP_HAS_NO_THREADS)",
17    "stdatomic.h": "__cplusplus > 202002L && !defined(_LIBCPP_HAS_NO_THREADS)",
18    "thread": "!defined(_LIBCPP_HAS_NO_THREADS)",
19
20    "filesystem": "!defined(_LIBCPP_HAS_NO_FILESYSTEM_LIBRARY)",
21
22    "clocale": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
23    "codecvt": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
24    "fstream": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
25    "iomanip": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
26    "ios": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
27    "iostream": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
28    "istream": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
29    "locale.h": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
30    "locale": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
31    "ostream": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
32    "regex": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
33    "sstream": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
34    "streambuf": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
35    "strstream": "!defined(_LIBCPP_HAS_NO_LOCALIZATION)",
36
37    "wctype.h": "!defined(_LIBCPP_HAS_NO_WIDE_CHARACTERS)",
38    "cwctype": "!defined(_LIBCPP_HAS_NO_WIDE_CHARACTERS)",
39    "cwchar": "!defined(_LIBCPP_HAS_NO_WIDE_CHARACTERS)",
40    "wchar.h": "!defined(_LIBCPP_HAS_NO_WIDE_CHARACTERS)",
41
42    "experimental/coroutine": "!defined(_LIBCPP_HAS_NO_EXPERIMENTAL_COROUTINES)",
43
44    "experimental/regex": "!defined(_LIBCPP_HAS_NO_LOCALIZATION) && __cplusplus >= 201103L",
45    "experimental/deque": "__cplusplus >= 201103L",
46    "experimental/map": "__cplusplus >= 201103L",
47    "experimental/memory_resource": "__cplusplus >= 201103L",
48    "experimental/forward_list": "__cplusplus >= 201103L",
49    "experimental/list": "__cplusplus >= 201103L",
50    "experimental/set": "__cplusplus >= 201103L",
51    "experimental/string": "__cplusplus >= 201103L",
52    "experimental/unordered_map": "__cplusplus >= 201103L",
53    "experimental/unordered_set": "__cplusplus >= 201103L",
54    "experimental/vector": "__cplusplus >= 201103L",
55}
56
57private_headers_still_public_in_modules = [
58    '__assert', '__bsd_locale_defaults.h', '__bsd_locale_fallbacks.h', '__config',
59    '__config_site.in', '__debug', '__hash_table',
60    '__threading_support', '__tree', '__undef_macros'
61]
62
63def find_script(file):
64    """Finds the script used to generate a file inside the file itself. The script is delimited by
65       BEGIN-SCRIPT and END-SCRIPT markers.
66    """
67    with open(file, 'r') as f:
68        content = f.read()
69
70    match = re.search(r'^BEGIN-SCRIPT$(.+)^END-SCRIPT$', content, flags=re.MULTILINE | re.DOTALL)
71    if not match:
72        raise RuntimeError("Was unable to find a script delimited with BEGIN-SCRIPT/END-SCRIPT markers in {}".format(test_file))
73    return match.group(1)
74
75def execute_script(script, variables):
76    """Executes the provided Mako template with the given variables available during the
77       evaluation of the script, and returns the result.
78    """
79    code = compile(script, 'fake-filename', 'exec')
80    output = io.StringIO()
81    with contextlib.redirect_stdout(output):
82        exec(code, variables)
83        output = output.getvalue()
84    return output
85
86def generate_new_file(file, new_content):
87    """Generates the new content of the file by inserting the new content in-between
88       two '// GENERATED-MARKER' markers located in the file.
89    """
90    with open(file, 'r') as f:
91        old_content = f.read()
92
93    try:
94        before, begin_marker, _, end_marker, after = re.split(r'(// GENERATED-MARKER\n)', old_content, flags=re.MULTILINE | re.DOTALL)
95    except ValueError:
96        raise RuntimeError("Failed to split {} based on markers, please make sure the file has exactly two '// GENERATED-MARKER' occurrences".format(file))
97
98    return before + begin_marker + new_content + end_marker + after
99
100def produce(test_file, variables):
101    script = find_script(test_file)
102    result = execute_script(script, variables)
103    new_content = generate_new_file(test_file, result)
104    with open(test_file, 'w', newline='\n') as f:
105        f.write(new_content)
106
107def is_header(file):
108    """Returns whether the given file is a header (i.e. not a directory or the modulemap file)."""
109    return not file.is_dir() and not file.name == 'module.modulemap'
110
111def main():
112    monorepo_root = pathlib.Path(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
113    include = pathlib.Path(os.path.join(monorepo_root, 'libcxx', 'include'))
114    test = pathlib.Path(os.path.join(monorepo_root, 'libcxx', 'test'))
115    assert(monorepo_root.exists())
116
117    toplevel_headers     = sorted(str(p.relative_to(include)) for p in include.glob('[a-z]*') if is_header(p))
118    experimental_headers = sorted(str(p.relative_to(include)) for p in include.glob('experimental/[a-z]*') if is_header(p))
119    extended_headers     = sorted(str(p.relative_to(include)) for p in include.glob('ext/[a-z]*') if is_header(p))
120    public_headers       = toplevel_headers + experimental_headers + extended_headers
121    private_headers      = sorted(str(p.relative_to(include)) for p in include.rglob('*') if is_header(p) and str(p.relative_to(include)).startswith('__'))
122    variables = {
123        'toplevel_headers': toplevel_headers,
124        'experimental_headers': experimental_headers,
125        'extended_headers': extended_headers,
126        'public_headers': public_headers,
127        'private_headers': private_headers,
128        'header_restrictions': header_restrictions,
129        'private_headers_still_public_in_modules': private_headers_still_public_in_modules
130    }
131
132    produce(test.joinpath('libcxx/assertions/headers_declare_assertion_handler.sh.cpp'), variables)
133    produce(test.joinpath('libcxx/clang_tidy.sh.cpp'), variables)
134    produce(test.joinpath('libcxx/double_include.sh.cpp'), variables)
135    produce(test.joinpath('libcxx/min_max_macros.compile.pass.cpp'), variables)
136    produce(test.joinpath('libcxx/nasty_macros.compile.pass.cpp'), variables)
137    produce(test.joinpath('libcxx/no_assert_include.compile.pass.cpp'), variables)
138    produce(test.joinpath('libcxx/private_headers.verify.cpp'), variables)
139
140
141if __name__ == '__main__':
142    main()
143