Debian Codegraph @

mesonbuild/scripts/depscan.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2020 The Meson development team
3 # Copyright © 2023-2024 Intel Corporation
4
5 from __future__ import annotations
6
7 import collections
8 import json
9 import os
10 import pathlib
11 import pickle
12 import re
13 import typing as T
14
15 if T.TYPE_CHECKING:
16 from typing_extensions import Literal, TypedDict, NotRequired
17 from ..backend.ninjabackend import TargetDependencyScannerInfo
18
19 Require = TypedDict(
20 'Require',
21 {
22 'logical-name': str,
23 'compiled-module-path': NotRequired[str],
24 'source-path': NotRequired[str],
25 'unique-on-source-path': NotRequired[bool],
26 'lookup-method': NotRequired[Literal['by-name', 'include-angle', 'include-quote']]
27 },
28 )
29
30 Provide = TypedDict(
31 'Provide',
32 {
33 'logical-name': str,
34 'compiled-module-path': NotRequired[str],
35 'source-path': NotRequired[str],
36 'unique-on-source-path': NotRequired[bool],
37 'is-interface': NotRequired[bool],
38 },
39 )
40
41 Rule = TypedDict(
42 'Rule',
43 {
44 'primary-output': NotRequired[str],
45 'outputs': NotRequired[T.List[str]],
46 'provides': NotRequired[T.List[Provide]],
47 'requires': NotRequired[T.List[Require]],
48 }
49 )
50
51 class Description(TypedDict):
52
53 version: int
54 revision: int
55 rules: T.List[Rule]
56
57
58 CPP_IMPORT_RE = re.compile(r'\w*import ([a-zA-Z0-9]+);')
59 CPP_EXPORT_RE = re.compile(r'\w*export module ([a-zA-Z0-9]+);')
60
61 FORTRAN_INCLUDE_PAT = r"^\s*include\s*['\"](\w+\.\w+)['\"]"
62 FORTRAN_MODULE_PAT = r"^\s*\bmodule\b\s+(\w+)\s*(?:!+.*)*$"
63 FORTRAN_SUBMOD_PAT = r"^\s*\bsubmodule\b\s*\((\w+:?\w+)\)\s*(\w+)"
64 FORTRAN_USE_PAT = r"^\s*use,?\s*(?:non_intrinsic)?\s*(?:::)?\s*(\w+)"
65
66 FORTRAN_MODULE_RE = re.compile(FORTRAN_MODULE_PAT, re.IGNORECASE)
67 FORTRAN_SUBMOD_RE = re.compile(FORTRAN_SUBMOD_PAT, re.IGNORECASE)
68 FORTRAN_USE_RE = re.compile(FORTRAN_USE_PAT, re.IGNORECASE)
69
70 class DependencyScanner:
71 def __init__(self, pickle_file: str, outfile: str):
72 with open(pickle_file, 'rb') as pf:
73 self.target_data: TargetDependencyScannerInfo = pickle.load(pf)
74 self.outfile = outfile
75 self.sources = self.target_data.sources
76 self.provided_by: T.Dict[str, str] = {}
77 self.exports: T.Dict[str, str] = {}
78 self.imports: collections.defaultdict[str, T.List[str]] = collections.defaultdict(list)
79 self.sources_with_exports: T.List[str] = []
80
81 def scan_file(self, fname: str, lang: Literal['cpp', 'fortran']) -> None:
82 if lang == 'fortran':
83 self.scan_fortran_file(fname)
84 else:
85 self.scan_cpp_file(fname)
86
87 def scan_fortran_file(self, fname: str) -> None:
88 fpath = pathlib.Path(fname)
89 modules_in_this_file = set()
90 for line in fpath.read_text(encoding='utf-8-sig', errors='ignore').split('\n'):
91 import_match = FORTRAN_USE_RE.match(line)
92 export_match = FORTRAN_MODULE_RE.match(line)
93 submodule_export_match = FORTRAN_SUBMOD_RE.match(line)
94 if import_match:
95 needed = import_match.group(1).lower()
96 # In Fortran you have an using declaration also for the module
97 # you define in the same file. Prevent circular dependencies.
98 if needed not in modules_in_this_file:
99 self.imports[fname].append(needed)
100 if export_match:
101 exported_module = export_match.group(1).lower()
102 assert exported_module not in modules_in_this_file
103 modules_in_this_file.add(exported_module)
104 if exported_module in self.provided_by:
105 raise RuntimeError(f'Multiple files provide module {exported_module}.')
106 self.sources_with_exports.append(fname)
107 self.provided_by[exported_module] = fname
108 self.exports[fname] = exported_module
109 if submodule_export_match:
110 # Store submodule "Foo" "Bar" as "foo:bar".
111 # A submodule declaration can be both an import and an export declaration:
112 #
113 # submodule (a1:a2) a3
114 # - requires [email protected]
115 # - produces [email protected]
116 parent_module_name_full = submodule_export_match.group(1).lower()
117 parent_module_name = parent_module_name_full.split(':')[0]
118 submodule_name = submodule_export_match.group(2).lower()
119 concat_name = f'{parent_module_name}:{submodule_name}'
120 self.sources_with_exports.append(fname)
121 self.provided_by[concat_name] = fname
122 self.exports[fname] = concat_name
123 # Fortran requires that the immediate parent module must be built
124 # before the current one. Thus:
125 #
126 # submodule (parent) parent <- requires parent.mod (really parent.smod, but they are created at the same time)
127 # submodule (a1:a2) a3 <- requires [email protected]
128 #
129 # a3 does not depend on the a1 parent module directly, only transitively.
130 self.imports[fname].append(parent_module_name_full)
131
132 def scan_cpp_file(self, fname: str) -> None:
133 fpath = pathlib.Path(fname)
134 for line in fpath.read_text(encoding='utf-8-sig', errors='ignore').split('\n'):
135 import_match = CPP_IMPORT_RE.match(line)
136 export_match = CPP_EXPORT_RE.match(line)
137 if import_match:
138 needed = import_match.group(1)
139 self.imports[fname].append(needed)
140 if export_match:
141 exported_module = export_match.group(1)
142 if exported_module in self.provided_by:
143 raise RuntimeError(f'Multiple files provide module {exported_module}.')
144 self.sources_with_exports.append(fname)
145 self.provided_by[exported_module] = fname
146 self.exports[fname] = exported_module
147
148 def module_name_for(self, src: str, lang: Literal['cpp', 'fortran']) -> str:
149 if lang == 'fortran':
150 exported = self.exports[src]
151 # Module foo:bar goes to a file name [email protected]
152 # Module Foo goes to a file name foo.mod
153 namebase = exported.replace(':', '@')
154 if ':' in exported:
155 extension = 'smod'
156 else:
157 extension = 'mod'
158 return os.path.join(self.target_data.private_dir, f'{namebase}.{extension}')
159 return '{}.ifc'.format(self.exports[src])
160
161 def scan(self) -> int:
162 for s, lang in self.sources:
163 self.scan_file(s, lang)
164 description: Description = {
165 'version': 1,
166 'revision': 0,
167 'rules': [],
168 }
169 for src, lang in self.sources:
170 rule: Rule = {
171 'primary-output': self.target_data.source2object[src],
172 'requires': [],
173 'provides': [],
174 }
175 if src in self.sources_with_exports:
176 rule['outputs'] = [self.module_name_for(src, lang)]
177 if src in self.imports:
178 for modname in self.imports[src]:
179 provider_src = self.provided_by.get(modname)
180 if provider_src == src:
181 continue
182 rule['requires'].append({
183 'logical-name': modname,
184 })
185 if provider_src:
186 rule['requires'][-1].update({
187 'source-path': provider_src,
188 'compiled-module-path': self.module_name_for(provider_src, lang),
189 })
190 if src in self.exports:
191 modname = self.exports[src]
192 rule['provides'].append({
193 'logical-name': modname,
194 'source-path': src,
195 'compiled-module-path': self.module_name_for(src, lang),
196 })
197 description['rules'].append(rule)
198
199 with open(self.outfile, 'w', encoding='utf-8') as f:
200 json.dump(description, f)
201
202 return 0
203
204 def run(args: T.List[str]) -> int:
205 assert len(args) == 2, 'got wrong number of arguments!'
206 outfile, pickle_file = args
207 scanner = DependencyScanner(pickle_file, outfile)
208 return scanner.scan()