Bug 1874684 - Part 17: Fix uninitialised variable warnings from clang-tidy. r=allstarschh
[gecko.git] / build / clang-plugin / ThreadAllows.py
blobf3e1ee894c8ea83962e9e416c58a348722c65c89
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 # You can obtain one at http://mozilla.org/MPL/2.0/.
4 import json
5 import os
6 import posixpath
7 from os import PathLike
9 # `typing.Literal` not available until Python 3.8;
10 # `typing_extensions` not generally available here
11 from typing import Iterable, Set
13 FIRST_LINE = "// This file was generated by {}. DO NOT EDIT.".format(
14 # `posixpath` for forward slashes, for presentation purposes
15 posixpath.relpath(__file__, os.getenv("TOPSRCDIR", "/"))
19 def generate_allowed_items(
20 which: str, # should be: Literal["files", "names"],
21 paths: Iterable[PathLike],
22 ) -> str:
23 def remove_trailing_comment(s: str) -> str:
24 return s[0 : s.find("#")]
26 def read_items_from_path(path: PathLike) -> Set[str]:
27 out = set()
28 with open(path) as file:
29 for line in file.readlines():
30 line = remove_trailing_comment(line).strip()
31 if not line:
32 continue # comment or empty line; discard
33 out.add(line)
34 return out
36 allowed = set().union(*(read_items_from_path(path) for path in paths))
37 # BUG: `json.dumps` may not correctly handle use of the quote character in
38 # thread names
39 allowed_list_s = ",\n ".join(json.dumps(elem) for elem in sorted(allowed))
41 return f"""\
42 static const char *allow_thread_{which}[] = {{
43 {allowed_list_s}
44 }};"""
47 def generate_allows(
48 *, allowed_names: Iterable[PathLike], allowed_files: Iterable[PathLike]
49 ) -> str:
50 """
51 This function reads in the specified sets of files -- ordinarily,
52 ["ThreadAllows.txt"] and ["ThreadFileAllows.txt"] -- and generates the text
53 of a header file containing two arrays with their contents, for inclusion by
54 the thread-name checker.
56 The checker will reject the creation of any thread via NS_NewNamedThread
57 unless either:
58 - the thread's name is a literal string which is found in the set of
59 allowed thread names; or
60 - the thread's creation occurs within a file which is found in the set of
61 unchecked files.
63 The latter condition exists mostly for the definition of NS_NewNamedThread,
64 but there also exist a few cases where the thread name is dynamically
65 computed (and so can't be checked).
66 """
67 output_string = (
68 FIRST_LINE
69 + "\n\n"
70 + generate_allowed_items("files", allowed_files)
71 + "\n\n"
72 + generate_allowed_items("names", allowed_names)
73 + "\n"
75 return output_string
78 # Entry point used by build/clang-plugin/moz.build (q.v.).
79 def generate_file(output, allowed_names, allowed_files):
80 output.write(
81 generate_allows(allowed_names=[allowed_names], allowed_files=[allowed_files])