Debian Codegraph @

mesonbuild/cmake/interpreter.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2019 The Meson development team
3
4 # This class contains the basic functionality needed to run any interpreter
5 # or an interpreter-based tool.
6 from __future__ import annotations
7
8 from functools import lru_cache
9 from os import environ
10 from pathlib import Path
11 import itertools
12 import re
13 import typing as T
14
15 from .common import CMakeException, CMakeTarget, language_map, cmake_get_generator_args, check_cmake_args
16 from .fileapi import CMakeFileAPI
17 from .executor import CMakeExecutor
18 from .toolchain import CMakeToolchain, CMakeExecScope
19 from .traceparser import CMakeTraceParser
20 from .tracetargets import resolve_cmake_trace_targets
21 from .. import mlog, mesonlib
22 from .. import options
23 from ..mesonlib import MachineChoice, OrderedSet, path_is_in_root, relative_to_if_possible
24 from ..options import OptionKey
25 from ..mesondata import DataFile
26 from ..compilers.compilers import assembler_suffixes, lang_suffixes, header_suffixes, obj_suffixes, lib_suffixes, is_header
27 from ..programs import ExternalProgram
28 from ..coredata import FORBIDDEN_TARGET_NAMES
29 from ..mparser import (
30 Token,
31 BaseNode,
32 CodeBlockNode,
33 FunctionNode,
34 ArrayNode,
35 ArgumentNode,
36 AssignmentNode,
37 BooleanNode,
38 StringNode,
39 IdNode,
40 IndexNode,
41 MethodNode,
42 NumberNode,
43 SymbolNode,
44 )
45
46
47 if T.TYPE_CHECKING:
48 from ..compilers.compilers import Language
49 from .common import CMakeConfiguration, TargetOptions
50 from .traceparser import CMakeGeneratorTarget
51 from .._typing import ImmutableListProtocol
52 from ..backend.backends import Backend
53 from ..environment import Environment
54
55 TYPE_mixed = T.Union[str, int, bool, Path, BaseNode]
56 TYPE_mixed_list = T.Union[TYPE_mixed, T.Sequence[TYPE_mixed]]
57 TYPE_mixed_kwargs = T.Dict[str, TYPE_mixed_list]
58
59 # Disable all warnings automatically enabled with --trace and friends
60 # See https://cmake.org/cmake/help/latest/variable/CMAKE_POLICY_WARNING_CMPNNNN.html
61 DISABLE_POLICY_WARNINGS: T.Collection[str] = [
62 'CMP0025',
63 'CMP0047',
64 'CMP0056',
65 'CMP0060',
66 'CMP0065',
67 'CMP0066',
68 'CMP0067',
69 'CMP0082',
70 'CMP0089',
71 'CMP0102',
72 ]
73
74 # CMake is a bit more averse to debugging, but in spirit the build types match
75 BUILDTYPE_MAP: T.Mapping[str, str] = {
76 'debug': 'Debug',
77 'debugoptimized': 'RelWithDebInfo', # CMake sets NDEBUG
78 'release': 'Release',
79 'minsize': 'MinSizeRel', # CMake leaves out debug information immediately
80 }
81
82 TARGET_TYPE_MAP: T.Mapping[str, str] = {
83 'STATIC_LIBRARY': 'static_library',
84 'MODULE_LIBRARY': 'shared_module',
85 'SHARED_LIBRARY': 'shared_library',
86 'EXECUTABLE': 'executable',
87 'OBJECT_LIBRARY': 'static_library',
88 'INTERFACE_LIBRARY': 'header_only'
89 }
90
91 SKIP_TARGETS: T.Collection[str] = ['UTILITY']
92
93 BLACKLIST_COMPILER_FLAGS: T.Collection[str] = [
94 '-Wall', '-Wextra', '-Weverything', '-Werror', '-Wpedantic', '-pedantic', '-w',
95 '/W1', '/W2', '/W3', '/W4', '/Wall', '/WX', '/w',
96 '/O1', '/O2', '/Ob', '/Od', '/Og', '/Oi', '/Os', '/Ot', '/Ox', '/Oy', '/Ob0',
97 '/RTC1', '/RTCc', '/RTCs', '/RTCu',
98 '/Z7', '/Zi', '/ZI',
99 ]
100
101 BLACKLIST_LINK_FLAGS: T.Collection[str] = [
102 '/machine:x64', '/machine:x86', '/machine:arm', '/machine:ebc',
103 '/debug', '/debug:fastlink', '/debug:full', '/debug:none',
104 '/incremental',
105 ]
106
107 BLACKLIST_CLANG_CL_LINK_FLAGS: T.Collection[str] = [
108 '/GR', '/EHsc', '/MDd', '/Zi', '/RTC1',
109 ]
110
111 BLACKLIST_LINK_LIBS: T.Collection[str] = [
112 'kernel32.lib',
113 'user32.lib',
114 'gdi32.lib',
115 'winspool.lib',
116 'shell32.lib',
117 'ole32.lib',
118 'oleaut32.lib',
119 'uuid.lib',
120 'comdlg32.lib',
121 'advapi32.lib'
122 ]
123
124 TRANSFER_DEPENDENCIES_FROM: T.Collection[str] = ['header_only']
125
126 _cmake_name_regex = re.compile(r'[^_a-zA-Z0-9]')
127 def _sanitize_cmake_name(name: str) -> str:
128 name = _cmake_name_regex.sub('_', name)
129 if name in FORBIDDEN_TARGET_NAMES or name.startswith('meson') or name[0].isdigit():
130 name = 'cm_' + name
131 return name
132
133 class OutputTargetMap:
134 rm_so_version = re.compile(r'(\.[0-9]+)+$')
135
136 def __init__(self, build_dir: Path):
137 self.tgt_map: T.Dict[str, T.Union['ConverterTarget', 'ConverterCustomTarget']] = {}
138 self.build_dir = build_dir
139
140 def add(self, tgt: T.Union['ConverterTarget', 'ConverterCustomTarget']) -> None:
141 keys: T.List[T.Optional[str]] = [self._target_key(tgt.cmake_name)]
142 if isinstance(tgt, ConverterTarget):
143 keys += [tgt.full_name]
144 keys += [self._rel_artifact_key(x) for x in tgt.artifacts]
145 keys += [self._base_artifact_key(x) for x in tgt.artifacts]
146 if isinstance(tgt, ConverterCustomTarget):
147 keys += [self._rel_generated_file_key(x) for x in tgt.original_outputs]
148 keys += [self._base_generated_file_key(x) for x in tgt.original_outputs]
149 for k in keys:
150 if k is not None:
151 self.tgt_map[k] = tgt
152
153 def _return_first_valid_key(self, keys: T.List[T.Optional[str]]) -> T.Optional[T.Union['ConverterTarget', 'ConverterCustomTarget']]:
154 for i in keys:
155 if i and i in self.tgt_map:
156 return self.tgt_map[i]
157 return None
158
159 def target(self, name: str) -> T.Optional[T.Union['ConverterTarget', 'ConverterCustomTarget']]:
160 return self._return_first_valid_key([self._target_key(name)])
161
162 def executable(self, name: str) -> T.Optional['ConverterTarget']:
163 tgt = self.target(name)
164 if tgt is None or not isinstance(tgt, ConverterTarget):
165 return None
166 if tgt.meson_func() != 'executable':
167 return None
168 return tgt
169
170 def artifact(self, name: str) -> T.Optional[T.Union['ConverterTarget', 'ConverterCustomTarget']]:
171 keys: T.List[T.Optional[str]] = []
172 candidates = [name, OutputTargetMap.rm_so_version.sub('', name)]
173 for i in lib_suffixes:
174 if not name.endswith('.' + i):
175 continue
176 new_name = name[:-len(i) - 1]
177 new_name = OutputTargetMap.rm_so_version.sub('', new_name)
178 candidates += [f'{new_name}.{i}']
179 for i in candidates:
180 keys += [self._rel_artifact_key(Path(i)), Path(i).name, self._base_artifact_key(Path(i))]
181 return self._return_first_valid_key(keys)
182
183 def generated(self, name: Path) -> T.Optional['ConverterCustomTarget']:
184 res = self._return_first_valid_key([self._rel_generated_file_key(name), self._base_generated_file_key(name)])
185 assert res is None or isinstance(res, ConverterCustomTarget)
186 return res
187
188 # Utility functions to generate local keys
189 def _rel_path(self, fname: Path) -> T.Optional[Path]:
190 try:
191 return fname.resolve().relative_to(self.build_dir)
192 except ValueError:
193 pass
194 return None
195
196 def _target_key(self, tgt_name: str) -> str:
197 return f'__tgt_{tgt_name}__'
198
199 def _rel_generated_file_key(self, fname: Path) -> T.Optional[str]:
200 path = self._rel_path(fname)
201 return f'__relgen_{path.as_posix()}__' if path else None
202
203 def _base_generated_file_key(self, fname: Path) -> str:
204 return f'__gen_{fname.name}__'
205
206 def _rel_artifact_key(self, fname: Path) -> T.Optional[str]:
207 path = self._rel_path(fname)
208 return f'__relart_{path.as_posix()}__' if path else None
209
210 def _base_artifact_key(self, fname: Path) -> str:
211 return f'__art_{fname.name}__'
212
213 class ConverterTarget:
214 def __init__(self, target: CMakeTarget, env: 'Environment', for_machine: MachineChoice) -> None:
215 self.env = env
216 self.for_machine = for_machine
217 self.artifacts = target.artifacts
218 self.src_dir = target.src_dir
219 self.build_dir = target.build_dir
220 self.name = target.name
221 self.cmake_name = target.name
222 self.full_name = target.full_name
223 self.type = target.type
224 self.install = target.install
225 self.install_dir: T.Optional[Path] = None
226 self.link_libraries = target.link_libraries
227 self.link_targets: T.List[str] = []
228 self.link_flags = target.link_flags + target.link_lang_flags
229 self.public_link_flags: T.List[str] = []
230 self.depends_raw: T.List[str] = []
231 self.depends: T.List[T.Union[ConverterTarget, ConverterCustomTarget]] = []
232
233 if target.install_paths:
234 self.install_dir = target.install_paths[0]
235
236 self.languages: T.Set[Language] = set()
237 self.sources: T.List[Path] = []
238 self.generated: T.List[Path] = []
239 self.generated_ctgt: T.List[CustomTargetReference] = []
240 self.includes: T.List[Path] = []
241 self.sys_includes: T.List[Path] = []
242 self.link_with: T.List[T.Union[ConverterTarget, ConverterCustomTarget]] = []
243 self.object_libs: T.List[ConverterTarget] = []
244 self.compile_opts: T.Dict[Language, T.List[str]] = {}
245 self.public_compile_opts: T.List[str] = []
246 self.pie = False
247 self.version: T.Optional[str] = None
248 self.soversion: T.Optional[str] = None
249
250 # Project default override options (c_std, cpp_std, etc.)
251 self.override_options: T.List[str] = []
252
253 # Convert the target name to a valid meson target name
254 self.name = _sanitize_cmake_name(self.name)
255
256 self.generated_raw: T.List[Path] = []
257
258 for i in target.files:
259 languages: T.Set[Language] = set()
260 src_suffixes: T.Set[str] = set()
261
262 # Insert suffixes
263 for j in i.sources:
264 if not j.suffix:
265 continue
266 src_suffixes.add(j.suffix[1:])
267
268 # Determine the meson language(s)
269 # Extract the default language from the explicit CMake field
270 lang_cmake_to_meson: T.Mapping[str, Language] = {val.lower(): key for key, val in language_map.items()}
271 languages.add(lang_cmake_to_meson.get(i.language.lower(), 'c'))
272
273 # Determine missing languages from the source suffixes
274 for sfx in src_suffixes:
275 for key, val in lang_suffixes.items():
276 if sfx in val:
277 languages.add(key)
278 break
279
280 # Register the new languages and initialize the compile opts array
281 for lang in languages:
282 self.languages.add(lang)
283 if lang not in self.compile_opts:
284 self.compile_opts[lang] = []
285
286 # Add arguments, but avoid duplicates
287 args = i.flags
288 args += [f'-D{x}' for x in i.defines]
289 for lang in languages:
290 self.compile_opts[lang] += [x for x in args if x not in self.compile_opts[lang]]
291
292 # Handle include directories
293 self.includes += [x.path for x in i.includes if x.path not in self.includes and not x.isSystem]
294 self.sys_includes += [x.path for x in i.includes if x.path not in self.sys_includes and x.isSystem]
295
296 # Add sources to the right array
297 if i.is_generated:
298 self.generated_raw += i.sources
299 else:
300 self.sources += i.sources
301
302 self.clib_compiler = None
303 compilers = self.env.coredata.compilers[self.for_machine]
304
305 # https://github.com/python/mypy/issues/18826
306 # However, we need to support versions of mypy that cannot deduce the
307 # tuple either.
308 for lang in T.cast('T.Tuple[Language, ...]', ('objcpp', 'cpp', 'objc', 'fortran', 'c')):
309 if lang in self.languages:
310 try:
311 self.clib_compiler = compilers[lang]
312 break
313 except KeyError:
314 pass
315
316 def __repr__(self) -> str:
317 return f'<{self.__class__.__name__}: {self.name}>'
318
319 std_regex = re.compile(r'([-]{1,2}std=|/std:v?|[-]{1,2}std:)(.*)')
320
321 def postprocess(self, output_target_map: OutputTargetMap, root_src_dir: Path, subdir: Path, install_prefix: Path, trace: CMakeTraceParser) -> None:
322 # Detect setting the C and C++ standard and do additional compiler args manipulation
323
324 # https://github.com/python/mypy/issues/18826
325 # However, we need to support versions of mypy that cannot deduce the
326 # tuple either.
327 for i in T.cast('T.Tuple[Language, ...]', ('c', 'cpp')):
328 if i not in self.compile_opts:
329 continue
330
331 temp: T.List[str] = []
332 for j in self.compile_opts[i]:
333 m = ConverterTarget.std_regex.match(j)
334 ctgt = output_target_map.generated(Path(j))
335 if m:
336 std = m.group(2)
337 supported = self._all_lang_stds(i)
338 if std not in supported:
339 mlog.warning(
340 'Unknown {0}_std "{1}" -> Ignoring. Try setting the project-'
341 'level {0}_std if build errors occur. Known '
342 '{0}_stds are: {2}'.format(i, std, ' '.join(supported)),
343 once=True
344 )
345 continue
346 self.override_options += [f'{i}_std={std}']
347 elif j in {'-fPIC', '-fpic', '-fPIE', '-fpie'}:
348 self.pie = True
349 elif isinstance(ctgt, ConverterCustomTarget):
350 # Sometimes projects pass generated source files as compiler
351 # flags. Add these as generated sources to ensure that the
352 # corresponding custom target is run.2
353 self.generated_raw += [Path(j)]
354 temp += [j]
355 elif j in BLACKLIST_COMPILER_FLAGS:
356 pass
357 else:
358 temp += [j]
359
360 self.compile_opts[i] = temp
361
362 # Make sure to force enable -fPIC for OBJECT libraries
363 if self.type.upper() == 'OBJECT_LIBRARY':
364 self.pie = True
365
366 # Use the CMake trace, if required
367 tgt = trace.targets.get(self.cmake_name)
368 if tgt:
369 self.depends_raw = trace.targets[self.cmake_name].depends
370 self.version = trace.targets[self.cmake_name].properties.get('VERSION', [None])[0]
371 self.soversion = trace.targets[self.cmake_name].properties.get('SOVERSION', [None])[0]
372
373 rtgt = resolve_cmake_trace_targets(self.cmake_name, trace, self.env, clib_compiler=self.clib_compiler)
374 self.includes += [Path(x) for x in rtgt.include_directories]
375 self.link_flags += rtgt.link_flags
376 self.public_link_flags += rtgt.public_link_flags
377 self.public_compile_opts += rtgt.public_compile_opts
378 self.link_libraries += rtgt.libraries
379 self.depends_raw += rtgt.target_dependencies
380 self.link_targets += rtgt.target_dependencies
381
382 elif self.type.upper() not in ['EXECUTABLE', 'OBJECT_LIBRARY']:
383 mlog.warning('CMake: Target', mlog.bold(self.cmake_name), 'not found in CMake trace. This can lead to build errors')
384
385 temp = []
386 for cmd in self.link_libraries:
387 # Let meson handle this arcane magic
388 if ',-rpath,' in cmd:
389 continue
390 if not Path(cmd).is_absolute():
391 link_with = output_target_map.artifact(cmd)
392 if link_with:
393 self.link_with += [link_with]
394 continue
395
396 temp += [cmd]
397 self.link_libraries = temp
398
399 # Filter out files that are not supported by the language
400 supported = list(assembler_suffixes) + list(header_suffixes) + list(obj_suffixes)
401 for i in self.languages:
402 supported += list(lang_suffixes[i])
403 supported = [f'.{x}' for x in supported]
404 self.sources = [x for x in self.sources if any(x.name.endswith(y) for y in supported)]
405 # Don't filter unsupported files from generated_raw because they
406 # can be GENERATED dependencies for other targets.
407 # See: https://github.com/mesonbuild/meson/issues/11607
408 # However, the dummy CMake rule files for Visual Studio still
409 # need to be filtered out. They don't exist (because the project was
410 # not generated at this time) but the fileapi will still
411 # report them on Windows.
412 # See: https://stackoverflow.com/a/41816323
413 self.generated_raw = [x for x in self.generated_raw if not x.name.endswith('.rule')]
414
415 # Make paths relative
416 def rel_path(x: Path, is_header: bool, is_generated: bool) -> T.Optional[Path]:
417 if not x.is_absolute():
418 x = self.src_dir / x
419 x = x.resolve()
420 assert x.is_absolute()
421 if not x.exists() and not any(x.name.endswith(y) for y in obj_suffixes) and not is_generated:
422 if path_is_in_root(x, Path(self.env.get_build_dir()), resolve=True):
423 x.mkdir(parents=True, exist_ok=True)
424 return x.relative_to(Path(self.env.get_build_dir()) / subdir)
425 else:
426 mlog.warning('CMake: path', mlog.bold(x.as_posix()), 'does not exist.')
427 mlog.warning(' --> Ignoring. This can lead to build errors.')
428 return None
429 if x in trace.explicit_headers:
430 return None
431 if (
432 path_is_in_root(x, Path(self.env.get_source_dir()))
433 and not (
434 path_is_in_root(x, root_src_dir) or
435 path_is_in_root(x, Path(self.env.get_build_dir()))
436 )
437 ):
438 mlog.warning('CMake: path', mlog.bold(x.as_posix()), 'is inside the root project but', mlog.bold('not'), 'inside the subproject.')
439 mlog.warning(' --> Ignoring. This can lead to build errors.')
440 return None
441 if path_is_in_root(x, Path(self.env.get_build_dir()) / subdir) and is_header:
442 return x.relative_to(Path(self.env.get_build_dir()) / subdir)
443 if path_is_in_root(x, Path(self.env.get_build_dir())) and is_header:
444 return Path(*([".."] * len(subdir.parts))) / x.relative_to(Path(self.env.get_build_dir()))
445 if path_is_in_root(x, root_src_dir):
446 return x.relative_to(root_src_dir)
447 return x
448
449 def non_optional(inputs: T.Iterable[T.Optional[Path]]) -> T.List[Path]:
450 return [p for p in inputs if p is not None]
451
452 self.generated_raw = non_optional(rel_path(x, False, True) for x in self.generated_raw)
453 self.includes = non_optional(itertools.chain((rel_path(x, True, False) for x in OrderedSet(self.includes))))
454 self.sys_includes = non_optional(rel_path(x, True, False) for x in OrderedSet(self.sys_includes))
455 self.sources = non_optional(rel_path(x, False, False) for x in self.sources)
456
457 # Resolve custom targets
458 for gen_file in self.generated_raw:
459 ctgt = output_target_map.generated(gen_file)
460 if ctgt:
461 ref = ctgt.get_ref(gen_file)
462 assert ref.valid()
463 self.generated_ctgt += [ref]
464 else:
465 self.generated += [gen_file]
466
467 # Make sure '.' is always in the include directories
468 if Path('.') not in self.includes:
469 self.includes += [Path('.')]
470
471 # make install dir relative to the install prefix
472 if self.install_dir and self.install_dir.is_absolute():
473 if path_is_in_root(self.install_dir, install_prefix):
474 self.install_dir = self.install_dir.relative_to(install_prefix)
475
476 # Remove blacklisted options and libs
477 def check_flag(flag: str) -> bool:
478 if flag.lower() in BLACKLIST_LINK_FLAGS or flag in BLACKLIST_COMPILER_FLAGS or flag in BLACKLIST_CLANG_CL_LINK_FLAGS:
479 return False
480 if flag.startswith('/D'):
481 return False
482 return True
483
484 self.link_libraries = [x for x in self.link_libraries if x.lower() not in BLACKLIST_LINK_LIBS]
485 self.link_flags = [x for x in self.link_flags if check_flag(x)]
486
487 # Handle OSX frameworks
488 def handle_frameworks(flags: T.List[str]) -> T.List[str]:
489 res: T.List[str] = []
490 for i in flags:
491 p = Path(i)
492 if not p.exists() or not p.name.endswith('.framework'):
493 res += [i]
494 continue
495 res += ['-framework', p.stem]
496 return res
497
498 self.link_libraries = handle_frameworks(self.link_libraries)
499 self.link_flags = handle_frameworks(self.link_flags)
500
501 # Handle explicit CMake add_dependency() calls
502 for arg in self.depends_raw:
503 dep_tgt = output_target_map.target(arg)
504 if dep_tgt:
505 self.depends.append(dep_tgt)
506
507 def process_object_libs(self, obj_target_list: T.List['ConverterTarget'], linker_workaround: bool) -> None:
508 # Try to detect the object library(s) from the generated input sources
509 temp = [x for x in self.generated if any(x.name.endswith('.' + y) for y in obj_suffixes)]
510 stem = [x.stem for x in temp]
511 exts = self._all_source_suffixes()
512 # Temp now stores the source filenames of the object files
513 for i in obj_target_list:
514 source_files = [x.name for x in i.sources + i.generated]
515 for j in stem:
516 # On some platforms (specifically looking at you Windows with vs20xy backend) CMake does
517 # not produce object files with the format `foo.cpp.obj`, instead it skips the language
518 # suffix and just produces object files like `foo.obj`. Thus we have to do our best to
519 # undo this step and guess the correct language suffix of the object file. This is done
520 # by trying all language suffixes meson knows and checking if one of them fits.
521 candidates = [j]
522 if not any(j.endswith('.' + x) for x in exts):
523 mlog.warning('Object files do not contain source file extensions, thus falling back to guessing them.', once=True)
524 candidates += [f'{j}.{x}' for x in exts]
525 if any(x in source_files for x in candidates):
526 if linker_workaround:
527 self._append_objlib_sources(i)
528 else:
529 self.includes += i.includes
530 self.includes = list(OrderedSet(self.includes))
531 self.object_libs += [i]
532 break
533
534 # Filter out object files from the sources
535 self.generated = [x for x in self.generated if not any(x.name.endswith('.' + y) for y in obj_suffixes)]
536
537 def _append_objlib_sources(self, tgt: 'ConverterTarget') -> None:
538 self.includes += tgt.includes
539 self.sources += tgt.sources
540 self.generated += tgt.generated
541 self.generated_ctgt += tgt.generated_ctgt
542 self.includes = list(OrderedSet(self.includes))
543 self.sources = list(OrderedSet(self.sources))
544 self.generated = list(OrderedSet(self.generated))
545 self.generated_ctgt = list(OrderedSet(self.generated_ctgt))
546
547 # Inherit compiler arguments since they may be required for building
548 for lang, opts in tgt.compile_opts.items():
549 if lang not in self.compile_opts:
550 self.compile_opts[lang] = []
551 self.compile_opts[lang] += [x for x in opts if x not in self.compile_opts[lang]]
552
553 @lru_cache(maxsize=None)
554 def _all_source_suffixes(self) -> 'ImmutableListProtocol[str]':
555 suffixes: T.List[str] = []
556 for exts in lang_suffixes.values():
557 suffixes.extend(exts)
558 return suffixes
559
560 @lru_cache(maxsize=None)
561 def _all_lang_stds(self, lang: str) -> 'ImmutableListProtocol[str]':
562 try:
563 opt = self.env.coredata.optstore.get_value_object(OptionKey(f'{lang}_std', machine=MachineChoice.BUILD))
564 assert isinstance(opt, (options.UserStdOption, options.UserComboOption)), 'for mypy'
565 return opt.choices or []
566 except KeyError:
567 return []
568
569 def process_inter_target_dependencies(self) -> None:
570 # Move the dependencies from all TRANSFER_DEPENDENCIES_FROM to the target
571 to_process = list(self.depends)
572 processed = []
573 new_deps = []
574 for i in to_process:
575 processed += [i]
576 if isinstance(i, ConverterTarget) and i.meson_func() in TRANSFER_DEPENDENCIES_FROM:
577 to_process += [x for x in i.depends if x not in processed]
578 else:
579 new_deps += [i]
580 self.depends = list(OrderedSet(new_deps))
581
582 def cleanup_dependencies(self) -> None:
583 # Clear the dependencies from targets that where moved from
584 if self.meson_func() in TRANSFER_DEPENDENCIES_FROM:
585 self.depends = []
586
587 def meson_func(self) -> str:
588 return TARGET_TYPE_MAP.get(self.type.upper())
589
590 def log(self) -> None:
591 mlog.log('Target', mlog.bold(self.name), f'({self.cmake_name})')
592 mlog.log(' -- artifacts: ', mlog.bold(str(self.artifacts)))
593 mlog.log(' -- full_name: ', mlog.bold(self.full_name))
594 mlog.log(' -- type: ', mlog.bold(self.type))
595 mlog.log(' -- install: ', mlog.bold('true' if self.install else 'false'))
596 mlog.log(' -- install_dir: ', mlog.bold(self.install_dir.as_posix() if self.install_dir else ''))
597 mlog.log(' -- link_libraries: ', mlog.bold(str(self.link_libraries)))
598 mlog.log(' -- link_with: ', mlog.bold(str(self.link_with)))
599 mlog.log(' -- object_libs: ', mlog.bold(str(self.object_libs)))
600 mlog.log(' -- link_flags: ', mlog.bold(str(self.link_flags)))
601 mlog.log(' -- languages: ', mlog.bold(str(self.languages)))
602 mlog.log(' -- includes: ', mlog.bold(str(self.includes)))
603 mlog.log(' -- sys_includes: ', mlog.bold(str(self.sys_includes)))
604 mlog.log(' -- sources: ', mlog.bold(str(self.sources)))
605 mlog.log(' -- generated: ', mlog.bold(str(self.generated)))
606 mlog.log(' -- generated_ctgt: ', mlog.bold(str(self.generated_ctgt)))
607 mlog.log(' -- pie: ', mlog.bold('true' if self.pie else 'false'))
608 mlog.log(' -- override_opts: ', mlog.bold(str(self.override_options)))
609 mlog.log(' -- depends: ', mlog.bold(str(self.depends)))
610 mlog.log(' -- options:')
611 for key, val in self.compile_opts.items():
612 mlog.log(' -', key, '=', mlog.bold(str(val)))
613
614 class CustomTargetReference:
615 def __init__(self, ctgt: 'ConverterCustomTarget', index: int) -> None:
616 self.ctgt = ctgt
617 self.index = index
618
619 def __repr__(self) -> str:
620 if self.valid():
621 return '<{}: {} [{}]>'.format(self.__class__.__name__, self.ctgt.name, self.ctgt.outputs[self.index])
622 else:
623 return f'<{self.__class__.__name__}: INVALID REFERENCE>'
624
625 def valid(self) -> bool:
626 return self.ctgt is not None and self.index >= 0
627
628 def filename(self) -> str:
629 return self.ctgt.outputs[self.index]
630
631 class ConverterCustomTarget:
632 tgt_counter = 0
633 out_counter = 0
634
635 def __init__(self, target: CMakeGeneratorTarget, env: 'Environment', for_machine: MachineChoice) -> None:
636 assert target.current_bin_dir is not None
637 assert target.current_src_dir is not None
638 self.name = target.name
639 if not self.name:
640 self.name = f'custom_tgt_{ConverterCustomTarget.tgt_counter}'
641 ConverterCustomTarget.tgt_counter += 1
642 self.cmake_name = str(self.name)
643 self.original_outputs = list(target.outputs)
644 self.outputs = [x.name for x in self.original_outputs]
645 self.conflict_map: T.Dict[str, str] = {}
646 self.command: T.List[T.List[T.Union[str, ConverterTarget]]] = []
647 self.working_dir = target.working_dir
648 self.depends_raw = target.depends
649 self.inputs: T.List[T.Union[str, CustomTargetReference]] = []
650 self.depends: T.List[T.Union[ConverterTarget, ConverterCustomTarget]] = []
651 self.current_bin_dir = target.current_bin_dir
652 self.current_src_dir = target.current_src_dir
653 self.env = env
654 self.for_machine = for_machine
655 self._raw_target = target
656
657 # Convert the target name to a valid meson target name
658 self.name = _sanitize_cmake_name(self.name)
659
660 def __repr__(self) -> str:
661 return f'<{self.__class__.__name__}: {self.name} {self.outputs}>'
662
663 def postprocess(self, output_target_map: OutputTargetMap, root_src_dir: Path, all_outputs: T.List[str], trace: CMakeTraceParser) -> None:
664 # Default the working directory to ${CMAKE_CURRENT_BINARY_DIR}
665 if self.working_dir is None:
666 self.working_dir = self.current_bin_dir
667
668 # relative paths in the working directory are always relative
669 # to ${CMAKE_CURRENT_BINARY_DIR}
670 if not self.working_dir.is_absolute():
671 self.working_dir = self.current_bin_dir / self.working_dir
672
673 # Modify the original outputs if they are relative. Again,
674 # relative paths are relative to ${CMAKE_CURRENT_BINARY_DIR}
675 def ensure_absolute(x: Path) -> Path:
676 if x.is_absolute():
677 return x
678 else:
679 return self.current_bin_dir / x
680 self.original_outputs = [ensure_absolute(x) for x in self.original_outputs]
681
682 # Ensure that there is no duplicate output in the project so
683 # that meson can handle cases where the same filename is
684 # generated in multiple directories
685 temp_outputs: T.List[str] = []
686 for i in self.outputs:
687 if i in all_outputs:
688 old = str(i)
689 i = f'c{ConverterCustomTarget.out_counter}_{i}'
690 ConverterCustomTarget.out_counter += 1
691 self.conflict_map[old] = i
692 all_outputs += [i]
693 temp_outputs += [i]
694 self.outputs = temp_outputs
695
696 # Check if the command is a build target
697 commands: T.List[T.List[T.Union[str, ConverterTarget]]] = []
698 for curr_cmd in self._raw_target.command:
699 assert isinstance(curr_cmd, list)
700 assert curr_cmd[0] != '', "An empty string is not a valid executable"
701 cmd: T.List[T.Union[str, ConverterTarget]] = []
702
703 for j in curr_cmd:
704 if not j:
705 continue
706 target = output_target_map.executable(j)
707 if target:
708 # When cross compiling, binaries have to be executed with an exe_wrapper (for instance wine for mingw-w64)
709 if self.env.exe_wrapper is not None and self.env.properties[self.for_machine].get_cmake_use_exe_wrapper():
710 assert isinstance(self.env.exe_wrapper, ExternalProgram)
711 cmd += self.env.exe_wrapper.get_command()
712 cmd += [target]
713 continue
714 elif j in trace.targets:
715 trace_tgt = trace.targets[j]
716 if trace_tgt.type == 'EXECUTABLE' and 'IMPORTED_LOCATION' in trace_tgt.properties:
717 cmd += trace_tgt.properties['IMPORTED_LOCATION']
718 continue
719 mlog.debug(f'CMake: Found invalid CMake target "{j}" --> ignoring \n{trace_tgt}')
720
721 # Fallthrough on error
722 cmd += [j]
723
724 commands += [cmd]
725 self.command = commands
726
727 # If the custom target does not declare any output, create a dummy
728 # one that can be used as dependency.
729 if not self.outputs:
730 self.outputs = [self.name + '.h']
731
732 # Check dependencies and input files
733 for i in self.depends_raw:
734 if not i:
735 continue
736 raw = Path(i)
737 art = output_target_map.artifact(i)
738 tgt = output_target_map.target(i)
739 gen = output_target_map.generated(raw)
740
741 rel_to_root = None
742 try:
743 rel_to_root = raw.relative_to(root_src_dir)
744 except ValueError:
745 rel_to_root = None
746
747 # First check for existing files. Only then check for existing
748 # targets, etc. This reduces the chance of misdetecting input files
749 # as outputs from other targets.
750 # See https://github.com/mesonbuild/meson/issues/6632
751 if not raw.is_absolute() and (self.current_src_dir / raw).is_file():
752 self.inputs += [(self.current_src_dir / raw).relative_to(root_src_dir).as_posix()]
753 elif raw.is_absolute() and raw.exists() and rel_to_root is not None:
754 self.inputs += [rel_to_root.as_posix()]
755 elif art:
756 self.depends += [art]
757 elif tgt:
758 self.depends += [tgt]
759 elif gen:
760 ctgt_ref = gen.get_ref(raw)
761 self.inputs += [ctgt_ref]
762
763 def process_inter_target_dependencies(self) -> None:
764 # Move the dependencies from all TRANSFER_DEPENDENCIES_FROM to the target
765 to_process = list(self.depends)
766 processed = []
767 new_deps = []
768 for i in to_process:
769 processed += [i]
770 if isinstance(i, ConverterTarget) and i.meson_func() in TRANSFER_DEPENDENCIES_FROM:
771 to_process += [x for x in i.depends if x not in processed]
772 else:
773 new_deps += [i]
774 self.depends = list(OrderedSet(new_deps))
775
776 def get_ref(self, fname: Path) -> CustomTargetReference:
777 name = fname.name
778 if name in self.conflict_map:
779 name = self.conflict_map[name]
780 try:
781 idx = self.outputs.index(name)
782 except ValueError:
783 raise mesonlib.MesonBugException(f'Attempted to get an output for {fname}, but none exists')
784
785 return CustomTargetReference(self, idx)
786
787 def log(self) -> None:
788 mlog.log('Custom Target', mlog.bold(self.name), f'({self.cmake_name})')
789 mlog.log(' -- command: ', mlog.bold(str(self.command)))
790 mlog.log(' -- outputs: ', mlog.bold(str(self.outputs)))
791 mlog.log(' -- conflict_map: ', mlog.bold(str(self.conflict_map)))
792 mlog.log(' -- working_dir: ', mlog.bold(str(self.working_dir)))
793 mlog.log(' -- depends_raw: ', mlog.bold(str(self.depends_raw)))
794 mlog.log(' -- inputs: ', mlog.bold(str(self.inputs)))
795 mlog.log(' -- depends: ', mlog.bold(str(self.depends)))
796
797 class CMakeInterpreter:
798 def __init__(self, subdir: Path, env: 'Environment', backend: 'Backend', for_machine: MachineChoice):
799 self.subdir = subdir
800 self.src_dir = Path(env.get_source_dir(), subdir)
801 self.build_dir_rel = subdir / '__CMake_build'
802 self.build_dir = Path(env.get_build_dir()) / self.build_dir_rel
803 self.install_prefix = Path(T.cast('str', env.coredata.optstore.get_value_for(OptionKey('prefix'))))
804 self.env = env
805 self.for_machine = for_machine
806 self.backend_name = backend.name
807 self.linkers: T.Set[str] = set()
808 self.fileapi = CMakeFileAPI(self.build_dir)
809
810 # Raw CMake results
811 self.bs_files: T.List[Path] = []
812 self.codemodel_configs: T.Optional[T.List[CMakeConfiguration]] = None
813 self.cmake_stderr: T.Optional[str] = None
814
815 # Analysed data
816 self.project_name = ''
817 self.project_version = ''
818 self.languages: T.List[str] = []
819 self.targets: T.List[ConverterTarget] = []
820 self.custom_targets: T.List[ConverterCustomTarget] = []
821 self.trace: CMakeTraceParser
822 self.output_target_map = OutputTargetMap(self.build_dir)
823
824 # Generated meson data
825 self.generated_targets: T.Dict[str, T.Dict[str, T.Optional[str]]] = {}
826 self.internal_name_map: T.Dict[str, str] = {}
827
828 # Do some special handling for object libraries for certain configurations
829 self._object_lib_workaround = False
830 if self.backend_name.startswith('vs'):
831 for comp in self.env.coredata.compilers[self.for_machine].values():
832 if comp.get_linker_id() == 'link':
833 self._object_lib_workaround = True
834 break
835
836 def configure(self, extra_cmake_options: T.List[str]) -> CMakeExecutor:
837 # Find CMake
838 cmake_exe = CMakeExecutor(self.env, '>=3.14', self.for_machine)
839 if not cmake_exe.found():
840 raise CMakeException('Unable to find CMake')
841 self.trace = CMakeTraceParser(cmake_exe.version(), self.build_dir, self.env, permissive=True)
842
843 preload_file = DataFile('cmake/data/preload.cmake').write_to_private(self.env)
844 toolchain = CMakeToolchain(cmake_exe, self.env, self.for_machine, CMakeExecScope.SUBPROJECT, self.build_dir, preload_file)
845 toolchain_file = toolchain.write()
846
847 # TODO: drop this check once the deprecated `cmake_args` kwarg is removed
848 extra_cmake_options = check_cmake_args(extra_cmake_options)
849
850 cmake_args = []
851 cmake_args += cmake_get_generator_args(self.env)
852 cmake_args += [f'-DCMAKE_INSTALL_PREFIX={self.install_prefix}']
853 libdir = self.env.coredata.optstore.get_value_for(OptionKey('libdir'))
854 cmake_args += [f'-DCMAKE_INSTALL_LIBDIR={libdir}']
855 cmake_args += extra_cmake_options
856 if not any(arg.startswith('-DCMAKE_BUILD_TYPE=') for arg in cmake_args):
857 # Our build type is favored over any CMAKE_BUILD_TYPE environment variable
858 buildtype = T.cast('str', self.env.coredata.optstore.get_value_for(OptionKey('buildtype')))
859 if buildtype in BUILDTYPE_MAP:
860 cmake_args += [f'-DCMAKE_BUILD_TYPE={BUILDTYPE_MAP[buildtype]}']
861 trace_args = self.trace.trace_args()
862 cmcmp_args = [f'-DCMAKE_POLICY_WARNING_{x}=OFF' for x in DISABLE_POLICY_WARNINGS]
863
864 if mesonlib.version_compare(cmake_exe.version(), '>= 3.25'):
865 # Enable MSVC debug information variable
866 cmcmp_args += ['-DCMAKE_POLICY_CMP0141=NEW']
867
868 self.fileapi.setup_request()
869
870 # Run CMake
871 mlog.log()
872 with mlog.nested():
873 mlog.log('Configuring the build directory with', mlog.bold('CMake'), 'version', mlog.cyan(cmake_exe.version()))
874 mlog.log(mlog.bold('Running CMake with:'), ' '.join(cmake_args))
875 mlog.log(mlog.bold(' - build directory: '), self.build_dir.as_posix())
876 mlog.log(mlog.bold(' - source directory: '), self.src_dir.as_posix())
877 mlog.log(mlog.bold(' - toolchain file: '), toolchain_file.as_posix())
878 mlog.log(mlog.bold(' - preload file: '), preload_file.as_posix())
879 mlog.log(mlog.bold(' - trace args: '), ' '.join(trace_args))
880 mlog.log(mlog.bold(' - disabled policy warnings:'), '[{}]'.format(', '.join(DISABLE_POLICY_WARNINGS)))
881 mlog.log()
882 self.build_dir.mkdir(parents=True, exist_ok=True)
883 os_env = environ.copy()
884 os_env['LC_ALL'] = 'C'
885 final_args = cmake_args + trace_args + cmcmp_args + toolchain.get_cmake_args() + [self.src_dir.as_posix()]
886
887 cmake_exe.set_exec_mode(print_cmout=True, always_capture_stderr=self.trace.requires_stderr())
888 rc, _, self.cmake_stderr = cmake_exe.call(final_args, self.build_dir, env=os_env, disable_cache=True)
889
890 mlog.log()
891 h = mlog.green('SUCCEEDED') if rc == 0 else mlog.red('FAILED')
892 mlog.log('CMake configuration:', h)
893 if rc != 0:
894 # get the last CMake error - We only need the message function for this:
895 self.trace.functions = {'message': self.trace.functions['message']}
896 self.trace.parse(self.cmake_stderr)
897 error = f': {self.trace.errors[-1]}' if self.trace.errors else ''
898 raise CMakeException(f'Failed to configure the CMake subproject{error}')
899
900 return cmake_exe
901
902 def initialise(self, extra_cmake_options: T.List[str]) -> None:
903 # Configure the CMake project to generate the file API data
904 self.configure(extra_cmake_options)
905
906 # Parse the result
907 self.fileapi.load_reply()
908
909 # Load the buildsystem file list
910 cmake_files = self.fileapi.get_cmake_sources()
911 self.bs_files = [x.file for x in cmake_files if not x.is_cmake and not x.is_temp]
912 self.bs_files = [relative_to_if_possible(x, Path(self.env.get_source_dir())) for x in self.bs_files]
913 self.bs_files = [x for x in self.bs_files if not path_is_in_root(x, Path(self.env.get_build_dir()), resolve=True)]
914 self.bs_files = list(OrderedSet(self.bs_files))
915
916 # Load the codemodel configurations
917 self.codemodel_configs = self.fileapi.get_cmake_configurations()
918
919 self.project_version = self.fileapi.get_project_version()
920
921 def analyse(self) -> None:
922 if self.codemodel_configs is None:
923 raise CMakeException('CMakeInterpreter was not initialized')
924
925 # Clear analyser data
926 self.project_name = ''
927 self.languages = []
928 self.targets = []
929 self.custom_targets = []
930
931 # Parse the trace
932 self.trace.parse(self.cmake_stderr)
933
934 # Find all targets
935 added_target_names: T.List[str] = []
936 for i_0 in self.codemodel_configs:
937 for j_0 in i_0.projects:
938 if not self.project_name:
939 self.project_name = j_0.name
940 for k_0 in j_0.targets:
941 # Avoid duplicate targets from different configurations and known
942 # dummy CMake internal target types
943 if k_0.type not in SKIP_TARGETS and k_0.name not in added_target_names:
944 added_target_names += [k_0.name]
945 self.targets += [ConverterTarget(k_0, self.env, self.for_machine)]
946
947 # Add interface targets from trace, if not already present.
948 # This step is required because interface targets were removed from
949 # the CMake file API output.
950 api_target_name_list = [x.name for x in self.targets]
951 for i_1 in self.trace.targets.values():
952 if i_1.type != 'INTERFACE' or i_1.name in api_target_name_list or i_1.imported:
953 continue
954 dummy = CMakeTarget({
955 'name': i_1.name,
956 'type': 'INTERFACE_LIBRARY',
957 'sourceDirectory': self.src_dir,
958 'buildDirectory': self.build_dir,
959 })
960 self.targets += [ConverterTarget(dummy, self.env, self.for_machine)]
961
962 for i_2 in self.trace.custom_targets:
963 self.custom_targets += [ConverterCustomTarget(i_2, self.env, self.for_machine)]
964
965 # generate the output_target_map
966 for i_3 in [*self.targets, *self.custom_targets]:
967 assert isinstance(i_3, (ConverterTarget, ConverterCustomTarget))
968 self.output_target_map.add(i_3)
969
970 # First pass: Basic target cleanup
971 object_libs = []
972 custom_target_outputs: T.List[str] = []
973 for ctgt in self.custom_targets:
974 ctgt.postprocess(self.output_target_map, self.src_dir, custom_target_outputs, self.trace)
975 for tgt in self.targets:
976 tgt.postprocess(self.output_target_map, self.src_dir, self.subdir, self.install_prefix, self.trace)
977 if tgt.type == 'OBJECT_LIBRARY':
978 object_libs += [tgt]
979 self.languages += [x for x in tgt.languages if x not in self.languages]
980
981 # Second pass: Populate link_with project internal targets
982 for tgt in self.targets:
983 for i in tgt.link_targets:
984 # Handle target-based link libraries
985 link_with = self.output_target_map.target(i)
986 if not link_with or isinstance(link_with, ConverterCustomTarget):
987 # Generated file etc.
988 continue
989 tgt.link_with.append(link_with)
990
991 # Third pass: Detect object library dependencies
992 for tgt in self.targets:
993 tgt.process_object_libs(object_libs, self._object_lib_workaround)
994
995 # Fourth pass: Reassign dependencies to avoid some loops
996 for tgt in self.targets:
997 tgt.process_inter_target_dependencies()
998 for ctgt in self.custom_targets:
999 ctgt.process_inter_target_dependencies()
1000
1001 # Fifth pass: Remove reassigned dependencies
1002 for tgt in self.targets:
1003 tgt.cleanup_dependencies()
1004
1005 mlog.log('CMake project', mlog.bold(self.project_name), mlog.bold(self.project_version), 'has', mlog.bold(str(len(self.targets) + len(self.custom_targets))), 'build targets.')
1006
1007 def pretend_to_be_meson(self, options: TargetOptions) -> CodeBlockNode:
1008 if not self.project_name:
1009 raise CMakeException('CMakeInterpreter was not analysed')
1010
1011 def token(tid: str = 'string', val: TYPE_mixed = '') -> Token:
1012 return Token(tid, self.subdir.as_posix(), 0, 0, 0, None, val)
1013
1014 def symbol(val: str) -> SymbolNode:
1015 return SymbolNode(token('', val))
1016
1017 def string(value: str) -> StringNode:
1018 return StringNode(token(val=value), escape=False)
1019
1020 def id_node(value: str) -> IdNode:
1021 return IdNode(token(val=value))
1022
1023 def number(value: int) -> NumberNode:
1024 return NumberNode(token(val=str(value)))
1025
1026 def nodeify(value: TYPE_mixed_list) -> BaseNode:
1027 if isinstance(value, str):
1028 return string(value)
1029 if isinstance(value, Path):
1030 return string(value.as_posix())
1031 elif isinstance(value, bool):
1032 return BooleanNode(token(val=value))
1033 elif isinstance(value, int):
1034 return number(value)
1035 elif isinstance(value, list):
1036 return array(value)
1037 elif isinstance(value, BaseNode):
1038 return value
1039 raise RuntimeError('invalid type of value: {} ({})'.format(type(value).__name__, str(value)))
1040
1041 def indexed(node: BaseNode, index: int) -> IndexNode:
1042 return IndexNode(node, symbol('['), nodeify(index), symbol(']'))
1043
1044 def array(elements: TYPE_mixed_list) -> ArrayNode:
1045 args = ArgumentNode(token())
1046 if not isinstance(elements, list):
1047 elements = [args]
1048 args.arguments += [nodeify(x) for x in elements if x is not None]
1049 return ArrayNode(symbol('['), args, symbol(']'))
1050
1051 def function(name: str, args: T.Optional[TYPE_mixed_list] = None, kwargs: T.Optional[TYPE_mixed_kwargs] = None) -> FunctionNode:
1052 args = [] if args is None else args
1053 kwargs = {} if kwargs is None else kwargs
1054 args_n = ArgumentNode(token())
1055 if not isinstance(args, list):
1056 assert isinstance(args, (str, int, bool, Path, BaseNode))
1057 args = [args]
1058 args_n.arguments = [nodeify(x) for x in args if x is not None]
1059 args_n.kwargs = {id_node(k): nodeify(v) for k, v in kwargs.items() if v is not None}
1060 func_n = FunctionNode(id_node(name), symbol('('), args_n, symbol(')'))
1061 return func_n
1062
1063 def method(obj: BaseNode, name: str, args: T.Optional[TYPE_mixed_list] = None, kwargs: T.Optional[TYPE_mixed_kwargs] = None) -> MethodNode:
1064 args = [] if args is None else args
1065 kwargs = {} if kwargs is None else kwargs
1066 args_n = ArgumentNode(token())
1067 if not isinstance(args, list):
1068 assert isinstance(args, (str, int, bool, Path, BaseNode))
1069 args = [args]
1070 args_n.arguments = [nodeify(x) for x in args if x is not None]
1071 args_n.kwargs = {id_node(k): nodeify(v) for k, v in kwargs.items() if v is not None}
1072 return MethodNode(obj, symbol('.'), id_node(name), symbol('('), args_n, symbol(')'))
1073
1074 def assign(var_name: str, value: BaseNode) -> AssignmentNode:
1075 return AssignmentNode(id_node(var_name), symbol('='), value)
1076
1077 # Generate the root code block and the project function call
1078 root_cb = CodeBlockNode(token())
1079 root_cb.lines += [function('project', [self.project_name] + self.languages, {'version': self.project_version} if self.project_version else None)]
1080
1081 # Add the run script for custom commands
1082
1083 # Add the targets
1084 processing: T.List[str] = []
1085 processed: T.Dict[str, T.Dict[str, T.Optional[str]]] = {}
1086 name_map: T.Dict[str, str] = {}
1087
1088 def extract_tgt(tgt: T.Union[ConverterTarget, ConverterCustomTarget, CustomTargetReference]) -> IdNode:
1089 tgt_name = None
1090 if isinstance(tgt, (ConverterTarget, ConverterCustomTarget)):
1091 tgt_name = tgt.name
1092 elif isinstance(tgt, CustomTargetReference):
1093 tgt_name = tgt.ctgt.name
1094 assert tgt_name is not None and tgt_name in processed
1095 res_var = processed[tgt_name]['tgt']
1096 return id_node(res_var) if res_var else None
1097
1098 def detect_cycle(tgt: T.Union[ConverterTarget, ConverterCustomTarget]) -> None:
1099 if tgt.name in processing:
1100 processing.append(tgt.name)
1101 stack = ' -> '.join(processing)
1102 raise CMakeException(f'Cycle in CMake inputs/dependencies detected: {stack}')
1103 processing.append(tgt.name)
1104
1105 def resolve_ctgt_ref(ref: CustomTargetReference) -> T.Union[IdNode, IndexNode]:
1106 tgt_var = extract_tgt(ref)
1107 if len(ref.ctgt.outputs) == 1:
1108 return tgt_var
1109 else:
1110 return indexed(tgt_var, ref.index)
1111
1112 def process_target(tgt: ConverterTarget) -> None:
1113 detect_cycle(tgt)
1114
1115 # First handle inter target dependencies
1116 link_with: T.List[IdNode] = []
1117 objec_libs: T.List[IdNode] = []
1118 sources: T.List[Path] = []
1119 generated: T.List[T.Union[IdNode, IndexNode]] = []
1120 generated_filenames: T.List[str] = []
1121 custom_targets: T.List[ConverterCustomTarget] = []
1122 dependencies: T.List[IdNode] = []
1123 for i in tgt.link_with:
1124 assert isinstance(i, ConverterTarget)
1125 if i.name not in processed:
1126 process_target(i)
1127 link_with += [extract_tgt(i)]
1128 for i in tgt.object_libs:
1129 assert isinstance(i, ConverterTarget)
1130 if i.name not in processed:
1131 process_target(i)
1132 objec_libs += [extract_tgt(i)]
1133 for i in tgt.depends:
1134 if not isinstance(i, ConverterCustomTarget):
1135 continue
1136 if i.name not in processed:
1137 process_custom_target(i)
1138 dependencies += [extract_tgt(i)]
1139
1140 # Generate the source list and handle generated sources
1141 sources += tgt.sources
1142 sources += tgt.generated
1143
1144 for ctgt_ref in tgt.generated_ctgt:
1145 ctgt = ctgt_ref.ctgt
1146 if ctgt.name not in processed:
1147 process_custom_target(ctgt)
1148 generated += [resolve_ctgt_ref(ctgt_ref)]
1149 generated_filenames += [ctgt_ref.filename()]
1150 if ctgt not in custom_targets:
1151 custom_targets += [ctgt]
1152
1153 # Add all header files from all used custom targets. This
1154 # ensures that all custom targets are built before any
1155 # sources of the current target are compiled and thus all
1156 # header files are present. This step is necessary because
1157 # CMake always ensures that a custom target is executed
1158 # before another target if at least one output is used.
1159 for ctgt in custom_targets:
1160 for j in ctgt.outputs:
1161 if not is_header(j) or j in generated_filenames:
1162 continue
1163
1164 generated += [resolve_ctgt_ref(ctgt.get_ref(Path(j)))]
1165 generated_filenames += [j]
1166
1167 # Determine the meson function to use for the build target
1168 tgt_func = tgt.meson_func()
1169 if not tgt_func:
1170 raise CMakeException(f'Unknown target type "{tgt.type}"')
1171
1172 # Determine the variable names
1173 inc_var = f'{tgt.name}_inc'
1174 dir_var = f'{tgt.name}_dir'
1175 sys_var = f'{tgt.name}_sys'
1176 src_var = f'{tgt.name}_src'
1177 dep_var = f'{tgt.name}_dep'
1178 tgt_var = tgt.name
1179
1180 install_tgt = options.get_install(tgt.cmake_name, tgt.install)
1181
1182 # Generate target kwargs
1183 tgt_kwargs: TYPE_mixed_kwargs = {
1184 'build_by_default': install_tgt,
1185 'link_args': options.get_link_args(tgt.cmake_name, tgt.link_flags + tgt.link_libraries),
1186 'link_with': link_with,
1187 'include_directories': id_node(inc_var),
1188 'install': install_tgt,
1189 'override_options': options.get_override_options(tgt.cmake_name, tgt.override_options),
1190 'objects': [method(x, 'extract_all_objects') for x in objec_libs],
1191 }
1192
1193 # Only set version if we know it and this is not a static lib
1194 if tgt_func != 'static_library':
1195 if tgt.version:
1196 tgt_kwargs['version'] = tgt.version
1197 if tgt.soversion:
1198 tgt_kwargs['soversion'] = tgt.soversion
1199
1200 # Only set if installed and only override if it is set
1201 if install_tgt and tgt.install_dir:
1202 tgt_kwargs['install_dir'] = tgt.install_dir
1203
1204 # Handle compiler args
1205 for key, val in tgt.compile_opts.items():
1206 tgt_kwargs[f'{key}_args'] = options.get_compile_args(tgt.cmake_name, key, val)
1207
1208 # Handle -fPCI, etc
1209 if tgt_func == 'executable':
1210 tgt_kwargs['pie'] = tgt.pie
1211 elif tgt_func == 'static_library':
1212 tgt_kwargs['pic'] = tgt.pie
1213
1214 # declare_dependency kwargs
1215 dep_kwargs: TYPE_mixed_kwargs = {
1216 'link_with': id_node(tgt_var),
1217 'compile_args': tgt.public_compile_opts,
1218 'include_directories': id_node(inc_var),
1219 }
1220
1221 # Static libraries need all link options and transient dependencies, but other
1222 # libraries should only use the link flags from INTERFACE_LINK_OPTIONS.
1223 if tgt_func == 'static_library':
1224 dep_kwargs['link_args'] = tgt.link_flags + tgt.link_libraries
1225 else:
1226 dep_kwargs['link_args'] = tgt.public_link_flags
1227
1228 if dependencies:
1229 generated += dependencies
1230
1231 # Generate the function nodes
1232 dir_node = assign(dir_var, function('include_directories', tgt.includes))
1233 sys_node = assign(sys_var, function('include_directories', tgt.sys_includes, {'is_system': True}))
1234 inc_node = assign(inc_var, array([id_node(dir_var), id_node(sys_var)]))
1235 node_list = [dir_node, sys_node, inc_node]
1236 if tgt_func == 'header_only':
1237 del dep_kwargs['link_with']
1238 dep_node = assign(dep_var, function('declare_dependency', kwargs=dep_kwargs))
1239 node_list += [dep_node]
1240 src_var = None
1241 tgt_var = None
1242 else:
1243 src_node = assign(src_var, function('files', sources))
1244 tgt_node = assign(tgt_var, function(tgt_func, [tgt_var, id_node(src_var), *generated], tgt_kwargs))
1245 node_list += [src_node, tgt_node]
1246 if tgt_func in {'static_library', 'shared_library'}:
1247 dep_node = assign(dep_var, function('declare_dependency', kwargs=dep_kwargs))
1248 node_list += [dep_node]
1249 elif tgt_func == 'shared_module':
1250 del dep_kwargs['link_with']
1251 dep_node = assign(dep_var, function('declare_dependency', kwargs=dep_kwargs))
1252 node_list += [dep_node]
1253 else:
1254 dep_var = None
1255
1256 # Add the nodes to the ast
1257 root_cb.lines += node_list
1258 processed[tgt.name] = {'inc': inc_var, 'src': src_var, 'dep': dep_var, 'tgt': tgt_var, 'func': tgt_func}
1259 name_map[tgt.cmake_name] = tgt.name
1260
1261 def process_custom_target(tgt: ConverterCustomTarget) -> None:
1262 # CMake allows to specify multiple commands in a custom target.
1263 # To map this to meson, a helper script is used to execute all
1264 # commands in order. This additionally allows setting the working
1265 # directory.
1266
1267 detect_cycle(tgt)
1268 tgt_var = tgt.name
1269
1270 def resolve_source(x: T.Union[str, ConverterTarget, ConverterCustomTarget, CustomTargetReference]) -> T.Union[str, IdNode, IndexNode]:
1271 if isinstance(x, ConverterTarget):
1272 if x.name not in processed:
1273 process_target(x)
1274 return extract_tgt(x)
1275 if isinstance(x, ConverterCustomTarget):
1276 if x.name not in processed:
1277 process_custom_target(x)
1278 return extract_tgt(x)
1279 elif isinstance(x, CustomTargetReference):
1280 if x.ctgt.name not in processed:
1281 process_custom_target(x.ctgt)
1282 return resolve_ctgt_ref(x)
1283 else:
1284 return x
1285
1286 # Generate the command list
1287 command: T.List[T.Union[str, IdNode, IndexNode]] = []
1288 command += mesonlib.get_meson_command()
1289 command += ['--internal', 'cmake_run_ctgt']
1290 command += ['-o', '@OUTPUT@']
1291 if tgt.original_outputs:
1292 command += ['-O'] + [x.as_posix() for x in tgt.original_outputs]
1293 command += ['-d', tgt.working_dir.as_posix()]
1294
1295 # Generate the commands. Subcommands are separated by ';;;'
1296 for cmd in tgt.command:
1297 command += [resolve_source(x) for x in cmd] + [';;;']
1298
1299 tgt_kwargs: TYPE_mixed_kwargs = {
1300 'input': [resolve_source(x) for x in tgt.inputs],
1301 'output': tgt.outputs,
1302 'command': command,
1303 'depends': [resolve_source(x) for x in tgt.depends],
1304 }
1305
1306 root_cb.lines += [assign(tgt_var, function('custom_target', [tgt.name], tgt_kwargs))]
1307 processed[tgt.name] = {'inc': None, 'src': None, 'dep': None, 'tgt': tgt_var, 'func': 'custom_target'}
1308 name_map[tgt.cmake_name] = tgt.name
1309
1310 # Now generate the target function calls
1311 for ctgt in self.custom_targets:
1312 if ctgt.name not in processed:
1313 process_custom_target(ctgt)
1314 for tgt in self.targets:
1315 if tgt.name not in processed:
1316 process_target(tgt)
1317
1318 self.generated_targets = processed
1319 self.internal_name_map = name_map
1320 return root_cb
1321
1322 def target_info(self, target: str) -> T.Optional[T.Dict[str, str]]:
1323 # Try resolving the target name
1324 # start by checking if there is a 100% match (excluding the name prefix)
1325 prx_tgt = _sanitize_cmake_name(target)
1326 if prx_tgt in self.generated_targets:
1327 return self.generated_targets[prx_tgt]
1328 # check if there exists a name mapping
1329 if target in self.internal_name_map:
1330 target = self.internal_name_map[target]
1331 assert target in self.generated_targets
1332 return self.generated_targets[target]
1333 return None
1334
1335 def target_list(self) -> T.List[str]:
1336 return list(self.internal_name_map.keys())