Debian Codegraph @

mesonbuild/modules/sourceset.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2019 The Meson development team
3
4 from __future__ import annotations
5 import typing as T
6
7 from . import ExtensionModule, ModuleObject, MutableModuleObject, ModuleInfo
8 from .. import build
9 from .. import dependencies
10 from .. import mesonlib
11 from ..interpreterbase import (
12 noPosargs, noKwargs,
13 InterpreterException, InvalidArguments, InvalidCode, FeatureNew,
14 )
15 from ..interpreterbase.decorators import ContainerTypeInfo, KwargInfo, typed_kwargs, typed_pos_args
16 from ..mesonlib import OrderedSet
17
18 if T.TYPE_CHECKING:
19 from typing_extensions import TypedDict
20
21 from . import ModuleState
22 from ..interpreter import Interpreter
23 from ..interpreterbase import TYPE_var, TYPE_kwargs
24
25 class AddKwargs(TypedDict):
26
27 when: T.List[T.Union[str, dependencies.Dependency]]
28 if_true: T.List[T.Union[str, build.TargetSources, dependencies.Dependency]]
29 if_false: T.List[T.Union[str, build.TargetSources, dependencies.Dependency]]
30
31 class AddAllKw(TypedDict):
32
33 when: T.List[T.Union[str, dependencies.Dependency]]
34 if_true: T.List[SourceSetImpl]
35
36 class ApplyKw(TypedDict):
37
38 strict: bool
39
40
41 _WHEN_KW: KwargInfo[T.List[T.Union[str, dependencies.Dependency]]] = KwargInfo(
42 'when',
43 ContainerTypeInfo(list, (str, dependencies.Dependency)),
44 listify=True,
45 default=[],
46 )
47
48
49 class SourceSetRule(T.NamedTuple):
50 keys: T.List[str]
51 """Configuration keys that enable this rule if true"""
52
53 deps: T.List[dependencies.Dependency]
54 """Dependencies that enable this rule if true"""
55
56 sources: T.List[str | build.TargetSources]
57 """Source files added when this rule's conditions are true"""
58
59 extra_deps: T.List[dependencies.Dependency]
60 """Dependencies added when this rule's conditions are true, but
61 that do not make the condition false if they're absent."""
62
63 sourcesets: T.List[SourceSetImpl]
64 """Other sourcesets added when this rule's conditions are true"""
65
66 if_false: T.List[str | build.TargetSources]
67 """Source files added when this rule's conditions are false"""
68
69 if_false_deps: T.List[dependencies.Dependency]
70 """Dependencies added when this rule's conditions are false, but
71 that do not make the condition true if they're absent"""
72
73
74 class SourceFiles(T.NamedTuple):
75 sources: OrderedSet[str | build.TargetSources]
76 deps: OrderedSet[dependencies.Dependency]
77
78
79 class SourceSet:
80 """Base class to avoid circular references.
81
82 Because of error messages, this class is called SourceSet, and the actual
83 implementation is an Impl.
84 """
85
86
87 class SourceSetImpl(SourceSet, MutableModuleObject):
88 def __init__(self, interpreter: Interpreter):
89 super().__init__()
90 self.rules: T.List[SourceSetRule] = []
91 self.frozen = False
92 self.methods.update({
93 'add': self.add_method,
94 'add_all': self.add_all_method,
95 'all_sources': self.all_sources_method,
96 'all_dependencies': self.all_dependencies_method,
97 'apply': self.apply_method,
98 })
99
100 def check_source_files(self, args: T.Sequence[T.Union[str, build.TargetSources, dependencies.Dependency]],
101 ) -> T.Tuple[T.List[T.Union[str, build.TargetSources]], T.List[dependencies.Dependency]]:
102 sources: T.List[T.Union[str, build.TargetSources]] = []
103 deps: T.List[dependencies.Dependency] = []
104 for x in args:
105 if isinstance(x, dependencies.Dependency):
106 deps.append(x)
107 else:
108 sources.append(x)
109 to_check: T.List[str] = []
110
111 # Get the actual output names to check
112 for s in sources:
113 if isinstance(s, str):
114 to_check.append(s)
115 elif isinstance(s, mesonlib.File):
116 to_check.append(s.fname)
117 else:
118 to_check.extend(s.get_outputs())
119 mesonlib.check_direntry_issues(to_check)
120 return sources, deps
121
122 def check_conditions(self, args: T.Sequence[T.Union[str, dependencies.Dependency]]
123 ) -> T.Tuple[T.List[str], T.List[dependencies.Dependency]]:
124 keys: T.List[str] = []
125 deps: T.List[dependencies.Dependency] = []
126 for x in args:
127 if isinstance(x, str):
128 keys.append(x)
129 else:
130 deps.append(x)
131 return keys, deps
132
133 @typed_pos_args('sourceset.add', varargs=(str, mesonlib.File, build.GeneratedList, build.CustomTarget, build.CustomTargetIndex, dependencies.Dependency))
134 @typed_kwargs(
135 'sourceset.add',
136 _WHEN_KW,
137 KwargInfo(
138 'if_true',
139 ContainerTypeInfo(list, (str, mesonlib.File, build.GeneratedList, build.CustomTarget, build.CustomTargetIndex, dependencies.Dependency)),
140 listify=True,
141 default=[],
142 ),
143 KwargInfo(
144 'if_false',
145 ContainerTypeInfo(list, (str, mesonlib.File, build.GeneratedList, build.CustomTarget, build.CustomTargetIndex, dependencies.Dependency)),
146 listify=True,
147 default=[],
148 ),
149 )
150 def add_method(self, state: ModuleState,
151 args: T.Tuple[T.List[T.Union[str, build.TargetSources, dependencies.Dependency]]],
152 kwargs: AddKwargs) -> None:
153 if self.frozen:
154 raise InvalidCode('Tried to use \'add\' after querying the source set')
155 when = kwargs['when']
156 if_true = kwargs['if_true']
157 if_false = kwargs['if_false']
158 if not any([when, if_true, if_false]):
159 if_true = args[0]
160 elif args[0]:
161 raise InterpreterException('add called with both positional and keyword arguments')
162 keys, dependencies = self.check_conditions(when)
163 sources, extra_deps = self.check_source_files(if_true)
164 if_false_sources, if_false_deps = self.check_source_files(if_false)
165 if len(if_false_deps) > 0:
166 FeatureNew.single_use('sourceset.add Dependency in if_false', '1.11.0',
167 state.subproject, location=state.current_node)
168 self.rules.append(SourceSetRule(keys, dependencies, sources, extra_deps, [], if_false_sources, if_false_deps))
169
170 @typed_pos_args('sourceset.add_all', varargs=SourceSet)
171 @typed_kwargs(
172 'sourceset.add_all',
173 _WHEN_KW,
174 KwargInfo(
175 'if_true',
176 ContainerTypeInfo(list, SourceSet),
177 listify=True,
178 default=[],
179 )
180 )
181 def add_all_method(self, state: ModuleState, args: T.Tuple[T.List[SourceSetImpl]],
182 kwargs: AddAllKw) -> None:
183 if self.frozen:
184 raise InvalidCode('Tried to use \'add_all\' after querying the source set')
185 when = kwargs['when']
186 if_true = kwargs['if_true']
187 if not when and not if_true:
188 if_true = args[0]
189 elif args[0]:
190 raise InterpreterException('add_all called with both positional and keyword arguments')
191 keys, dependencies = self.check_conditions(when)
192 for s in if_true:
193 s.frozen = True
194 self.rules.append(SourceSetRule(keys, dependencies, [], [], if_true, [], []))
195
196 def collect(self, enabled_fn: T.Callable[[str], bool],
197 all_sources: bool,
198 into: T.Optional['SourceFiles'] = None) -> SourceFiles:
199 if not into:
200 into = SourceFiles(OrderedSet(), OrderedSet())
201 for entry in self.rules:
202 if all(x.found() for x in entry.deps) and \
203 all(enabled_fn(key) for key in entry.keys):
204 into.sources.update(entry.sources)
205 into.deps.update(entry.deps)
206 into.deps.update(entry.extra_deps)
207 for ss in entry.sourcesets:
208 ss.collect(enabled_fn, all_sources, into)
209 if not all_sources:
210 continue
211 into.sources.update(entry.if_false)
212 into.deps.update(entry.if_false_deps)
213 return into
214
215 @noKwargs
216 @noPosargs
217 def all_sources_method(self, state: ModuleState, args: T.List[TYPE_var], kwargs: TYPE_kwargs
218 ) -> T.List[str | build.TargetSources]:
219 self.frozen = True
220 files = self.collect(lambda x: True, True)
221 return list(files.sources)
222
223 @noKwargs
224 @noPosargs
225 @FeatureNew('source_set.all_dependencies() method', '0.52.0')
226 def all_dependencies_method(self, state: ModuleState, args: T.List[TYPE_var], kwargs: TYPE_kwargs
227 ) -> T.List[dependencies.Dependency]:
228 self.frozen = True
229 files = self.collect(lambda x: True, True)
230 return list(files.deps)
231
232 @typed_pos_args('sourceset.apply', (build.ConfigurationData, dict))
233 @typed_kwargs('sourceset.apply', KwargInfo('strict', bool, default=True))
234 def apply_method(self, state: ModuleState, args: T.Tuple[T.Union[build.ConfigurationData, T.Dict[str, TYPE_var]]], kwargs: ApplyKw) -> SourceFilesObject:
235 config_data = args[0]
236 self.frozen = True
237 strict = kwargs['strict']
238 if isinstance(config_data, dict):
239 def _get_from_config_data(key: str) -> bool:
240 assert isinstance(config_data, dict), 'for mypy'
241 if strict and key not in config_data:
242 raise InterpreterException(f'Entry {key} not in configuration dictionary.')
243 return bool(config_data.get(key, False))
244 else:
245 config_cache: T.Dict[str, bool] = {}
246
247 def _get_from_config_data(key: str) -> bool:
248 assert isinstance(config_data, build.ConfigurationData), 'for mypy'
249 if key not in config_cache:
250 if key in config_data:
251 config_cache[key] = bool(config_data.get(key)[0])
252 elif strict:
253 raise InvalidArguments(f'sourceset.apply: key "{key}" not in passed configuration, and strict set.')
254 else:
255 config_cache[key] = False
256 return config_cache[key]
257
258 files = self.collect(_get_from_config_data, False)
259 res = SourceFilesObject(files)
260 return res
261
262 class SourceFilesObject(ModuleObject):
263 def __init__(self, files: SourceFiles):
264 super().__init__()
265 self.files = files
266 self.methods.update({
267 'sources': self.sources_method,
268 'dependencies': self.dependencies_method,
269 })
270
271 @noPosargs
272 @noKwargs
273 def sources_method(self, state: ModuleState, args: T.List[TYPE_var], kwargs: TYPE_kwargs
274 ) -> T.List[str | build.TargetSources]:
275 return list(self.files.sources)
276
277 @noPosargs
278 @noKwargs
279 def dependencies_method(self, state: ModuleState, args: T.List[TYPE_var], kwargs: TYPE_kwargs
280 ) -> T.List[dependencies.Dependency]:
281 return list(self.files.deps)
282
283 class SourceSetModule(ExtensionModule):
284
285 INFO = ModuleInfo('sourceset', '0.51.0')
286
287 def __init__(self, interpreter: Interpreter):
288 super().__init__(interpreter)
289 self.methods.update({
290 'source_set': self.source_set,
291 })
292
293 @noKwargs
294 @noPosargs
295 def source_set(self, state: ModuleState, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> SourceSetImpl:
296 return SourceSetImpl(self.interpreter)
297
298 def initialize(interp: Interpreter) -> SourceSetModule:
299 return SourceSetModule(interp)