Debian Codegraph @

mesonbuild/ast/introspection.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2018 The Meson development team
3 # Copyright © 2024-2025 Intel Corporation
4
5 # This class contains the basic functionality needed to run any interpreter
6 # or an interpreter-based tool
7
8 from __future__ import annotations
9 import os
10 import typing as T
11
12 from .. import compilers, environment, mesonlib
13 from ..build import Executable, Jar, SharedLibrary, SharedModule, StaticLibrary, BuildProject
14 from ..compilers import detect_compiler_for
15 from ..interpreterbase import InvalidArguments, UnknownValue, Feature
16 from ..interpreter import type_checking
17 from ..mesonlib import MachineChoice, SubProject
18 from ..options import OptionKey
19 from ..mparser import BaseNode, ArrayNode, ElementaryNode, IdNode, FunctionNode, StringNode
20 from .interpreter import AstInterpreter, IntrospectionBuildTarget, IntrospectionDependency
21
22 if T.TYPE_CHECKING:
23 from ..build import BuildTarget, BuildTargetKeywordArguments
24 from ..compilers.compilers import Language
25 from ..interpreterbase import TYPE_var
26 from .visitor import AstVisitor
27
28
29 _TARGET_KWARGS: T.Mapping[str, set[str]] = {
30 'executable': {s.name for s in type_checking.EXECUTABLE_KWS},
31 'jar': {s.name for s in type_checking.JAR_KWS},
32 'library': {s.name for s in type_checking.LIBRARY_KWS},
33 'shared library': {s.name for s in type_checking.SHARED_LIB_KWS},
34 'shared module': {s.name for s in type_checking.SHARED_MOD_KWS},
35 'static library': {s.name for s in type_checking.STATIC_LIB_KWS},
36 'both libraries': {s.name for s in type_checking.LIBRARY_KWS},
37 }
38
39 # TODO: it would be nice to not have to duplicate this
40 BUILD_TARGET_FUNCTIONS = [
41 'executable', 'jar', 'library', 'shared_library', 'shared_module',
42 'static_library', 'both_libraries'
43 ]
44
45 class IntrospectionHelper:
46 # mimic an argparse namespace
47 def __init__(self, cross_file: T.Optional[str]):
48 self.cross_file = [cross_file] if cross_file is not None else []
49 self.native_file: T.List[str] = []
50 self.cmd_line_options: T.Dict[OptionKey, str] = {}
51 self.builtin_keys: T.Set[OptionKey] = set()
52 self.d_keys: T.Set[OptionKey] = set()
53 self.projectoptions: T.List[str] = []
54
55 def __eq__(self, other: object) -> bool:
56 return NotImplemented
57
58 class IntrospectionInterpreter(AstInterpreter):
59 # If you run `meson setup ...` the `Interpreter`-class walks over the AST.
60 # If you run `meson rewrite ...` and `meson introspect meson.build ...`,
61 # the `AstInterpreter`-class walks over the AST.
62 # Works without a build directory.
63 # Most of the code is stolen from interpreter.Interpreter .
64 def __init__(self,
65 source_root: str,
66 subdir: str,
67 backend: str,
68 visitors: T.Optional[T.List[AstVisitor]] = None,
69 cross_file: T.Optional[str] = None,
70 subproject: SubProject = mesonlib.ROOT_SUBPROJECT,
71 subproject_dir: str = 'subprojects',
72 env: T.Optional[environment.Environment] = None):
73 options = IntrospectionHelper(cross_file)
74 env_ = env or environment.Environment(source_root, None, options)
75 super().__init__(source_root, subdir, subproject, subproject_dir, env_, visitors=visitors)
76
77 self.cross_file = cross_file
78 self.backend = backend
79 self.build_project = BuildProject(subproject, '', subproject, MachineChoice.HOST, MachineChoice.HOST)
80 self.project_data: T.Dict[str, T.Any] = {}
81 self.targets: T.List[IntrospectionBuildTarget] = []
82 self.dependencies: T.List[IntrospectionDependency] = []
83 self.project_node: FunctionNode = None
84
85 self.funcs.update({
86 'add_languages': self.func_add_languages,
87 'dependency': self.func_dependency,
88 'executable': self.func_executable,
89 'jar': self.func_jar,
90 'library': self.func_library,
91 'project': self.func_project,
92 'shared_library': self.func_shared_lib,
93 'shared_module': self.func_shared_module,
94 'static_library': self.func_static_lib,
95 'both_libraries': self.func_both_lib,
96 })
97
98 def func_project(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> None:
99 if self.project_node:
100 raise InvalidArguments('Second call to project()')
101 assert isinstance(node, FunctionNode)
102 self.project_node = node
103 if len(args) < 1:
104 raise InvalidArguments('Not enough arguments to project(). Needs at least the project name.')
105
106 def _str_list(node: T.Any) -> T.Optional[T.List[str]]:
107 if isinstance(node, ArrayNode):
108 r = []
109 for v in node.args.arguments:
110 if not isinstance(v, StringNode):
111 return None
112 r.append(v.value)
113 return r
114 if isinstance(node, StringNode):
115 return [node.value]
116 return None
117
118 proj_name = args[0]
119 proj_vers = kwargs.get('version', 'undefined')
120 if isinstance(proj_vers, ElementaryNode):
121 proj_vers = proj_vers.value
122 if not isinstance(proj_vers, str):
123 proj_vers = 'undefined'
124 proj_langs = self.flatten_args(args[1:])
125 # Match the value returned by ``meson.project_license()`` when
126 # no ``license`` argument is specified in the ``project()`` call.
127 proj_license = _str_list(kwargs.get('license', None)) or ['unknown']
128 proj_license_files = _str_list(kwargs.get('license_files', None)) or []
129 self.project_data = {'descriptive_name': proj_name, 'version': proj_vers, 'license': proj_license, 'license_files': proj_license_files}
130
131 self._load_option_file()
132
133 if not self.is_subproject() and 'subproject_dir' in kwargs:
134 spdirname = kwargs['subproject_dir']
135 if isinstance(spdirname, StringNode):
136 assert isinstance(spdirname.value, str)
137 self.subproject_dir = spdirname.value
138 if not self.is_subproject():
139 self.project_data['subprojects'] = []
140 subprojects_dir = os.path.join(self.source_root, self.subproject_dir)
141 if os.path.isdir(subprojects_dir):
142 for i in os.listdir(subprojects_dir):
143 if os.path.isdir(os.path.join(subprojects_dir, i)):
144 self.do_subproject(SubProject(i))
145
146 self.environment.init_backend_options(self.backend)
147
148 self._add_languages(proj_langs, True, MachineChoice.HOST)
149 self._add_languages(proj_langs, True, MachineChoice.BUILD)
150
151 def do_subproject(self, dirname: SubProject) -> None:
152 subdir = os.path.join(self.environment.source_dir, self.subproject_dir, dirname)
153 try:
154 subi = IntrospectionInterpreter(self.source_root, subdir, self.backend, cross_file=self.cross_file, subproject=dirname, subproject_dir=self.subproject_dir, env=self.environment, visitors=self.visitors)
155 subi.analyze()
156 subi.project_data['name'] = dirname
157 self.project_data['subprojects'] += [subi.project_data]
158 except (mesonlib.MesonException, RuntimeError):
159 pass
160
161 def func_add_languages(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> UnknownValue:
162 kwargs = self.flatten_kwargs(kwargs)
163 required = kwargs.get('required', True)
164 assert isinstance(required, (bool, Feature, UnknownValue)), 'for mypy'
165 if isinstance(required, Feature):
166 required = required.is_enabled()
167 if 'native' in kwargs:
168 native = kwargs.get('native', False)
169 self._add_languages(args, required, MachineChoice.BUILD if native else MachineChoice.HOST)
170 else:
171 for for_machine in [MachineChoice.BUILD, MachineChoice.HOST]:
172 self._add_languages(args, required, for_machine)
173 return UnknownValue()
174
175 def _add_languages(self, raw_langs: T.List[TYPE_var], required: T.Union[bool, UnknownValue], for_machine: MachineChoice) -> None:
176 langs: T.List[Language] = []
177 for l in self.flatten_args(raw_langs):
178 # we need to call .lower() here because `project('foo', 'CpP')` is valid.
179 if isinstance(l, str):
180 langs.append(T.cast('Language', l.lower()))
181 elif isinstance(l, StringNode):
182 langs.append(T.cast('Language', l.value.lower()))
183
184 for lang in sorted(langs, key=compilers.sort_clink):
185 if lang not in self.coredata.compilers[for_machine]:
186 try:
187 comp = detect_compiler_for(self.environment, lang, for_machine, True, self.subproject)
188 except mesonlib.MesonException:
189 # All code paths are evaluated regardless of conditionals,
190 # so always ignore compiler detection failures.
191 continue
192 if comp:
193 self.coredata.process_compiler_options(lang, comp, self.subproject)
194
195 def func_dependency(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Optional[IntrospectionDependency]:
196 assert isinstance(node, FunctionNode)
197 args = self.flatten_args(args)
198 kwargs = self.flatten_kwargs(kwargs)
199 if not args:
200 return None
201 name = args[0]
202 assert isinstance(name, (str, UnknownValue))
203 has_fallback = 'fallback' in kwargs
204 required = kwargs.get('required', True)
205 version = kwargs.get('version', [])
206 if not isinstance(version, list):
207 version = [version]
208 if any(isinstance(el, UnknownValue) for el in version):
209 version = UnknownValue()
210 else:
211 assert all(isinstance(el, str) for el in version)
212 version = T.cast(T.List[str], version)
213 assert isinstance(required, (bool, UnknownValue))
214 newdep = IntrospectionDependency(
215 name=name,
216 required=required,
217 version=version,
218 has_fallback=has_fallback,
219 conditional=node.condition_level > 0,
220 node=node)
221 self.dependencies += [newdep]
222 return newdep
223
224 def build_target(self, node: BaseNode, args: T.List[TYPE_var], kwargs_raw: T.Dict[str, TYPE_var], targetclass: T.Type[BuildTarget]) -> T.Union[IntrospectionBuildTarget, UnknownValue]:
225 assert isinstance(node, FunctionNode)
226 args = self.flatten_args(args)
227 if not args or not isinstance(args[0], str):
228 return UnknownValue()
229 name = args[0]
230 srcqueue: T.List[BaseNode] = [node]
231 extra_queue = []
232
233 # Process the sources BEFORE flattening the kwargs, to preserve the original nodes
234 if 'sources' in kwargs_raw:
235 srcqueue += mesonlib.listify(kwargs_raw['sources'])
236
237 if 'extra_files' in kwargs_raw:
238 extra_queue += mesonlib.listify(kwargs_raw['extra_files'])
239
240 kwargs = self.flatten_kwargs(kwargs_raw, True)
241
242 oldlen = len(node.args.arguments)
243 source_nodes = node.args.arguments[1:]
244 for k, v in node.args.kwargs.items():
245 assert isinstance(k, IdNode)
246 if k.value == 'sources':
247 source_nodes.append(v)
248 assert oldlen == len(node.args.arguments)
249
250 extraf_nodes = None
251 for k, v in node.args.kwargs.items():
252 assert isinstance(k, IdNode)
253 if k.value == 'extra_files':
254 assert extraf_nodes is None
255 extraf_nodes = v
256
257 for_machine = MachineChoice.BUILD if kwargs.get('native', False) else MachineChoice.HOST
258
259 # Make sure nothing can crash when creating the build class
260 _kwargs_reduced = {k: v for k, v in kwargs.items() if k in _TARGET_KWARGS[targetclass.typename] and k in {'install', 'build_by_default', 'build_always', 'name_prefix'}}
261 _kwargs_reduced = {k: v.value if isinstance(v, ElementaryNode) else v for k, v in _kwargs_reduced.items()}
262 _kwargs_reduced = {k: v for k, v in _kwargs_reduced.items() if not isinstance(v, (BaseNode, UnknownValue))}
263 _kwargs_reduced['native'] = for_machine
264 kwargs_reduced = T.cast('BuildTargetKeywordArguments', _kwargs_reduced)
265 objects: T.List[T.Any] = []
266 empty_sources: T.List[T.Any] = []
267 # Passing the unresolved sources list causes errors
268 kwargs_reduced['_allow_no_sources'] = True
269 target = targetclass(name, self.subdir, for_machine, empty_sources, None, objects,
270 self.environment, self.coredata.compilers[for_machine],
271 self.build_project, kwargs_reduced)
272 target.process_compilers_late()
273
274 build_by_default: T.Union[UnknownValue, bool] = target.build_by_default
275 if 'build_by_default' in kwargs and isinstance(kwargs['build_by_default'], UnknownValue):
276 build_by_default = kwargs['build_by_default']
277
278 install: T.Union[UnknownValue, bool] = target.should_install()
279 if 'install' in kwargs and isinstance(kwargs['install'], UnknownValue):
280 install = kwargs['install']
281
282 new_target = IntrospectionBuildTarget(
283 name=target.get_basename(),
284 machine=target.for_machine.get_lower_case_name(),
285 id=target.get_id(),
286 typename=target.get_typename(),
287 defined_in=os.path.normpath(os.path.join(self.source_root, self.subdir, environment.build_filename)),
288 subdir=self.subdir,
289 build_by_default=build_by_default,
290 installed=install,
291 outputs=target.get_outputs(),
292 source_nodes=source_nodes,
293 extra_files=extraf_nodes,
294 kwargs=kwargs,
295 node=node)
296
297 self.targets += [new_target]
298 return new_target
299
300 def build_library(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]:
301 default_library = self.coredata.optstore.get_value_for(OptionKey('default_library', subproject=self.subproject))
302 if default_library == 'shared':
303 return self.build_target(node, args, kwargs, SharedLibrary)
304 elif default_library == 'static':
305 return self.build_target(node, args, kwargs, StaticLibrary)
306 elif default_library == 'both':
307 return self.build_target(node, args, kwargs, SharedLibrary)
308 return None
309
310 def func_executable(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]:
311 return self.build_target(node, args, kwargs, Executable)
312
313 def func_static_lib(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]:
314 return self.build_target(node, args, kwargs, StaticLibrary)
315
316 def func_shared_lib(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]:
317 return self.build_target(node, args, kwargs, SharedLibrary)
318
319 def func_both_lib(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]:
320 return self.build_target(node, args, kwargs, SharedLibrary)
321
322 def func_shared_module(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]:
323 return self.build_target(node, args, kwargs, SharedModule)
324
325 def func_library(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]:
326 return self.build_library(node, args, kwargs)
327
328 def func_jar(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]:
329 return self.build_target(node, args, kwargs, Jar)
330
331 def func_build_target(self, node: BaseNode, args: T.List[TYPE_var], kwargs: T.Dict[str, TYPE_var]) -> T.Union[IntrospectionBuildTarget, UnknownValue]:
332 if 'target_type' not in kwargs:
333 return None
334 target_type = kwargs.pop('target_type')
335 if isinstance(target_type, ElementaryNode):
336 target_type = target_type.value
337 if target_type == 'executable':
338 return self.build_target(node, args, kwargs, Executable)
339 elif target_type == 'shared_library':
340 return self.build_target(node, args, kwargs, SharedLibrary)
341 elif target_type == 'static_library':
342 return self.build_target(node, args, kwargs, StaticLibrary)
343 elif target_type == 'both_libraries':
344 return self.build_target(node, args, kwargs, SharedLibrary)
345 elif target_type == 'library':
346 return self.build_library(node, args, kwargs)
347 elif target_type == 'jar':
348 return self.build_target(node, args, kwargs, Jar)
349 return None
350
351 def is_subproject(self) -> bool:
352 return self.subproject != ''
353
354 def analyze(self) -> None:
355 self.load_root_meson_file()
356 self.sanity_check_ast()
357 self.parse_project()
358 self.run()
359
360 def extract_subproject_dir(self) -> T.Optional[str]:
361 '''Fast path to extract subproject_dir kwarg.
362 This is faster than self.parse_project() which also initialize options
363 and also calls parse_project() on every subproject.
364 '''
365 if not self.ast.lines:
366 return None
367 project = self.ast.lines[0]
368 # first line is always project()
369 if not isinstance(project, FunctionNode):
370 return None
371 for kw, val in project.args.kwargs.items():
372 assert isinstance(kw, IdNode), 'for mypy'
373 if kw.value == 'subproject_dir':
374 # mypy does not understand "and isinstance"
375 if isinstance(val, StringNode):
376 return val.value
377 return None
378
379 def flatten_kwargs(self, kwargs: T.Dict[str, TYPE_var], include_unknown_args: bool = False) -> T.Dict[str, TYPE_var]:
380 flattened_kwargs = {}
381 for key, val in kwargs.items():
382 if isinstance(val, BaseNode):
383 resolved = self.node_to_runtime_value(val)
384 if resolved is not None:
385 flattened_kwargs[key] = resolved
386 elif isinstance(val, (str, bool, int, float)) or include_unknown_args:
387 flattened_kwargs[key] = val
388 return flattened_kwargs