Debian Codegraph @

mesonbuild/dependencies/base.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2018 The Meson development team
3 # Copyright © 2024-2025 Intel Corporation
4
5 # This file contains the detection logic for external dependencies.
6 # Custom logic for several other packages are in separate files.
7
8 from __future__ import annotations
9 import copy
10 import dataclasses
11 import os
12 import collections
13 import itertools
14 import typing as T
15 import uuid
16 from enum import Enum
17
18 from .. import mlog, mesonlib
19 from ..compilers import clib_langs
20 from ..mesonlib import LibType, MachineChoice, MesonException, HoldableObject, version_compare_many
21 from ..options import OptionKey
22 #from ..interpreterbase import FeatureDeprecated, FeatureNew
23
24 if T.TYPE_CHECKING:
25 from typing_extensions import Literal, Required, Self, TypedDict, TypeAlias
26
27 from ..compilers.compilers import Language, Compiler
28 from ..environment import Environment
29 from ..interpreterbase import FeatureCheckBase
30 from ..build import (
31 CustomTarget, IncludeDirs, CustomTargetIndex, LinkableTargetTypes,
32 StaticLibrary, ExtractedObjects, TargetSources
33 )
34 from ..interpreter.type_checking import PkgConfigDefineType
35
36 IncludeType: TypeAlias = Literal['system', 'non-system', 'preserve']
37
38 class DependencyObjectKWs(TypedDict, total=False):
39
40 """Keyword arguments that the Dependency IR object accepts.
41
42 This is different than the arguments as taken by the Interpreter, since
43 it is expected to be clean.
44 """
45
46 cmake_args: T.List[str]
47 cmake_module_path: T.List[str]
48 cmake_package_version: str
49 components: T.List[str]
50 include_type: IncludeType
51 language: T.Optional[Language]
52 main: bool
53 method: DependencyMethods
54 modules: T.List[str]
55 native: Required[MachineChoice]
56 optional_modules: T.List[str]
57 private_headers: bool
58 required: bool
59 static: T.Optional[bool]
60 version: T.List[str]
61
62 # Only in the python dependency
63 embed: bool
64
65 # Only passed internally, not part of the DSL API
66 paths: T.List[str]
67 returncode_value: int
68 silent: bool
69 tools: T.List[str]
70 version_arg: str
71 build_config: str
72
73 _MissingCompilerBase = Compiler
74 else:
75 _MissingCompilerBase = object
76
77
78 DepType = T.TypeVar('DepType', bound='ExternalDependency', covariant=True)
79
80 class DependencyException(MesonException):
81 '''Exceptions raised while trying to find dependencies'''
82
83
84 class MissingCompiler(_MissingCompilerBase):
85 """Represent a None Compiler - when no tool chain is found.
86 replacing AttributeError with DependencyException"""
87
88 # These are needed in type checking mode to avoid errors, but we don't want
89 # the extra overhead at runtime
90 if T.TYPE_CHECKING:
91 def __init__(self) -> None:
92 pass
93
94 def get_optimization_args(self, optimization_level: str) -> T.List[str]:
95 return []
96
97 def get_output_args(self, outputname: str) -> T.List[str]:
98 return []
99
100 def _sanity_check_source_code(self) -> str:
101 return ''
102
103 def __getattr__(self, item: str) -> T.Any:
104 if item.startswith('__'):
105 raise AttributeError()
106 raise DependencyException('no toolchain found')
107
108 def __bool__(self) -> bool:
109 return False
110
111
112 class DependencyMethods(Enum):
113 # Auto means to use whatever dependency checking mechanisms in whatever order meson thinks is best.
114 AUTO = 'auto'
115 PKGCONFIG = 'pkg-config'
116 CMAKE = 'cmake'
117 # The dependency is provided by the standard library and does not need to be linked
118 BUILTIN = 'builtin'
119 # Just specify the standard link arguments, assuming the operating system provides the library.
120 SYSTEM = 'system'
121 # This is only supported on OSX - search the frameworks directory by name.
122 EXTRAFRAMEWORK = 'extraframework'
123 # Detect using the sysconfig module.
124 SYSCONFIG = 'sysconfig'
125 # Specify using a "program"-config style tool
126 CONFIG_TOOL = 'config-tool'
127 # Misc
128 DUB = 'dub'
129
130
131 DependencyTypeName = T.NewType('DependencyTypeName', str)
132
133
134 class Dependency(HoldableObject):
135
136 type_name: DependencyTypeName
137
138 def __init__(self, kwargs: DependencyObjectKWs) -> None:
139 # This allows two Dependencies to be compared even after being copied.
140 # The purpose is to allow the name to be changed, but still have a proper comparison
141 self._id = uuid.uuid4().int
142 self.name = f'dep{self._id}'
143 self.version: T.Optional[str] = None
144 self.language: T.Optional[Language] = kwargs.get('language') # None means C-like
145 self.is_found = False
146 self.compile_args: T.List[str] = []
147 self.link_args: T.List[str] = []
148 # Raw -L and -l arguments without manual library searching
149 # If None, self.link_args will be used
150 self.raw_link_args: T.Optional[T.List[str]] = None
151 self.sources: T.List[TargetSources] = []
152 self.extra_files: T.List[mesonlib.File] = []
153 self.include_type = kwargs.get('include_type', 'preserve')
154 self.ext_deps: T.List[Dependency] = []
155 self.d_features: T.DefaultDict[str, T.List[T.Any]] = collections.defaultdict(list)
156 self.featurechecks: T.List['FeatureCheckBase'] = []
157 self.feature_since: T.Optional[T.Tuple[str, str]] = None
158 self.meson_variables: T.List[str] = []
159
160 def __eq__(self, other: object) -> bool:
161 if not isinstance(other, Dependency):
162 return NotImplemented
163 return self._id == other._id
164
165 def __hash__(self) -> int:
166 return self._id
167
168 def __repr__(self) -> str:
169 return f'<{self.__class__.__name__} {self.name}: {self.is_found}>'
170
171 def is_built(self) -> bool:
172 return False
173
174 def is_named(self) -> bool:
175 if self.name is None:
176 return False
177 return self.name != f'dep{self._id}'
178
179 def summary_value(self) -> T.Union[str, mlog.AnsiDecorator, mlog.AnsiText]:
180 if not self.found():
181 return mlog.red('NO')
182 if not self.version:
183 return mlog.green('YES')
184 return mlog.AnsiText(mlog.green('YES'), ' ', mlog.cyan(self.version))
185
186 def get_compile_args(self) -> T.List[str]:
187 if self.include_type == 'system':
188 converted = []
189 for i in self.compile_args:
190 if i.startswith('-I') or i.startswith('/I'):
191 converted += ['-isystem' + i[2:]]
192 else:
193 converted += [i]
194 return converted
195 if self.include_type == 'non-system':
196 converted = []
197 for i in self.compile_args:
198 if i.startswith('-isystem'):
199 converted += ['-I' + i[8:]]
200 else:
201 converted += [i]
202 return converted
203 return self.compile_args
204
205 def get_all_compile_args(self) -> T.List[str]:
206 """Get the compile arguments from this dependency and its sub dependencies."""
207 return list(itertools.chain(self.get_compile_args(),
208 *(d.get_all_compile_args() for d in self.ext_deps)))
209
210 def get_link_args(self, language: T.Optional[Language] = None, raw: bool = False) -> T.List[str]:
211 if raw and self.raw_link_args is not None:
212 return self.raw_link_args
213 return self.link_args
214
215 def get_all_link_args(self) -> T.List[str]:
216 """Get the link arguments from this dependency and its sub dependencies."""
217 return list(itertools.chain(self.get_link_args(),
218 *(d.get_all_link_args() for d in self.ext_deps)))
219
220 def found(self) -> bool:
221 return self.is_found
222
223 def get_sources(self) -> T.List[TargetSources]:
224 """Source files that need to be added to the target.
225 As an example, gtest-all.cc when using GTest."""
226 return self.sources
227
228 def get_extra_files(self) -> T.List[mesonlib.File]:
229 """Mostly for introspection and IDEs"""
230 return self.extra_files
231
232 def get_name(self) -> str:
233 return self.name
234
235 def get_version(self) -> str:
236 if self.version:
237 return self.version
238 else:
239 return 'unknown'
240
241 def get_include_dirs(self) -> T.List['IncludeDirs']:
242 return []
243
244 def get_include_type(self) -> str:
245 return self.include_type
246
247 def get_exe_args(self, compiler: 'Compiler') -> T.List[str]:
248 return []
249
250 def get_partial_dependency(self, *, compile_args: bool = False,
251 link_args: bool = False, links: bool = False,
252 includes: bool = False, sources: bool = False) -> 'Dependency':
253 """Create a new dependency that contains part of the parent dependency.
254
255 The following options can be inherited:
256 links -- all link_with arguments
257 includes -- all include_directory and -I/-isystem calls
258 sources -- any source, header, or generated sources
259 compile_args -- any compile args
260 link_args -- any link args
261
262 Additionally the new dependency will have the version parameter of its
263 parent (if any) and the requested values of any dependencies will be
264 added as well.
265 """
266 raise RuntimeError('Unreachable code in partial_dependency called')
267
268 def _add_sub_dependency(self, deplist: T.Iterable[T.Callable[[], 'Dependency']]) -> bool:
269 """Add an internal dependency from a list of possible dependencies.
270
271 This method is intended to make it easier to add additional
272 dependencies to another dependency internally.
273
274 Returns true if the dependency was successfully added, false
275 otherwise.
276 """
277 for d in deplist:
278 dep = d()
279 if dep.is_found:
280 self.ext_deps.append(dep)
281 return True
282 return False
283
284 def get_variable(self, *, cmake: T.Optional[str] = None, pkgconfig: T.Optional[str] = None,
285 configtool: T.Optional[str] = None, internal: T.Optional[str] = None,
286 system: T.Optional[str] = None, default_value: T.Optional[str] = None,
287 pkgconfig_define: PkgConfigDefineType = None) -> str:
288 if default_value is not None:
289 return default_value
290 raise DependencyException(f'No default provided for dependency {self!r}, which is not pkg-config, cmake, or config-tool based.')
291
292 def generate_system_dependency(self, include_type: IncludeType) -> 'Dependency':
293 new_dep = copy.deepcopy(self)
294 new_dep.include_type = include_type
295 return new_dep
296
297 def get_as_static(self, recursive: bool) -> Dependency:
298 """Used as base case for internal_dependency"""
299 return self
300
301 def get_as_shared(self, recursive: bool) -> Dependency:
302 """Used as base case for internal_dependency"""
303 return self
304
305 class InternalDependency(Dependency):
306
307 type_name = DependencyTypeName('internal')
308
309 def __init__(self, version: str, incdirs: T.Optional[T.List['IncludeDirs']] = None,
310 compile_args: T.Optional[T.List[str]] = None,
311 link_args: T.Optional[T.List[str]] = None,
312 libraries: T.Optional[T.List[LinkableTargetTypes]] = None,
313 whole_libraries: T.Optional[T.List[T.Union[StaticLibrary, CustomTarget, CustomTargetIndex]]] = None,
314 sources: T.Optional[T.Sequence[TargetSources]] = None,
315 extra_files: T.Optional[T.Sequence[mesonlib.File]] = None,
316 ext_deps: T.Optional[T.List[Dependency]] = None, variables: T.Optional[T.Dict[str, str]] = None,
317 d_module_versions: T.Optional[T.List[T.Union[str, int]]] = None,
318 d_import_dirs: T.Optional[T.List['IncludeDirs']] = None,
319 objects: T.Optional[T.List['ExtractedObjects']] = None,
320 name: T.Optional[str] = None):
321 super().__init__({'native': MachineChoice.HOST}) # TODO: does the native key actually matter
322 self.version = version
323 self.is_found = True
324 self.include_directories = incdirs or []
325 self.compile_args = compile_args or []
326 self.link_args = link_args or []
327 self.libraries = libraries or []
328 self.whole_libraries = whole_libraries or []
329 self.sources = list(sources or [])
330 self.extra_files = list(extra_files or [])
331 self.ext_deps = ext_deps or []
332 self.variables = variables or {}
333 self.objects = objects or []
334 if d_module_versions:
335 self.d_features['versions'] = d_module_versions
336 if d_import_dirs:
337 self.d_features['import_dirs'] = d_import_dirs
338 if name:
339 self.name = name
340
341 def __deepcopy__(self, memo: T.Dict[int, 'InternalDependency']) -> 'InternalDependency':
342 result = self.__class__.__new__(self.__class__)
343 assert isinstance(result, InternalDependency)
344 memo[id(self)] = result
345 for k, v in self.__dict__.items():
346 if k in {'libraries', 'whole_libraries'}:
347 setattr(result, k, copy.copy(v))
348 else:
349 setattr(result, k, copy.deepcopy(v, memo))
350 return result
351
352 def summary_value(self) -> mlog.AnsiDecorator:
353 # Omit the version. Most of the time it will be just the project
354 # version, which is uninteresting in the summary.
355 return mlog.green('YES')
356
357 def is_built(self) -> bool:
358 if self.sources or self.libraries or self.whole_libraries:
359 return True
360 return any(d.is_built() for d in self.ext_deps)
361
362 def get_partial_dependency(self, *, compile_args: bool = False,
363 link_args: bool = False, links: bool = False,
364 includes: bool = False, sources: bool = False,
365 extra_files: bool = False) -> Self:
366 final_compile_args = self.compile_args.copy() if compile_args else []
367 final_link_args = self.link_args.copy() if link_args else []
368 final_libraries = self.libraries.copy() if links else []
369 final_whole_libraries = self.whole_libraries.copy() if links else []
370 final_sources = self.sources.copy() if sources else []
371 final_extra_files = self.extra_files.copy() if extra_files else []
372 final_includes = self.include_directories.copy() if includes else []
373 final_deps = [d.get_partial_dependency(
374 compile_args=compile_args, link_args=link_args, links=links,
375 includes=includes, sources=sources) for d in self.ext_deps]
376 return type(self)(
377 self.version, final_includes, final_compile_args,
378 final_link_args, final_libraries, final_whole_libraries,
379 final_sources, final_extra_files, final_deps, self.variables, [], [], [], self.name)
380
381 def get_include_dirs(self) -> T.List['IncludeDirs']:
382 return self.include_directories
383
384 def get_variable(self, *, cmake: T.Optional[str] = None, pkgconfig: T.Optional[str] = None,
385 configtool: T.Optional[str] = None, internal: T.Optional[str] = None,
386 system: T.Optional[str] = None, default_value: T.Optional[str] = None,
387 pkgconfig_define: PkgConfigDefineType = None) -> str:
388 val = self.variables.get(internal, default_value)
389 if val is not None:
390 return val
391 raise DependencyException(f'Could not get an internal variable and no default provided for {self!r}')
392
393 def generate_link_whole_dependency(self) -> Dependency:
394 from ..build import SharedLibrary, CustomTarget, CustomTargetIndex
395 new_dep = copy.deepcopy(self)
396 for x in new_dep.libraries:
397 if isinstance(x, SharedLibrary):
398 raise MesonException('Cannot convert a dependency to link_whole when it contains a '
399 'SharedLibrary')
400 elif isinstance(x, (CustomTarget, CustomTargetIndex)) and x.links_dynamically():
401 raise MesonException('Cannot convert a dependency to link_whole when it contains a '
402 'CustomTarget or CustomTargetIndex which is a shared library')
403
404 # Mypy doesn't understand that the above is a TypeGuard
405 new_dep.whole_libraries += T.cast('T.List[T.Union[StaticLibrary, CustomTarget, CustomTargetIndex]]',
406 new_dep.libraries)
407 new_dep.libraries = []
408 return new_dep
409
410 def get_as_static(self, recursive: bool) -> InternalDependency:
411 new_dep = copy.copy(self)
412 new_dep.libraries = [lib.get('static', recursive) for lib in self.libraries]
413 if recursive:
414 new_dep.ext_deps = [dep.get_as_static(True) for dep in self.ext_deps]
415 return new_dep
416
417 def get_as_shared(self, recursive: bool) -> InternalDependency:
418 new_dep = copy.copy(self)
419 new_dep.libraries = [lib.get('shared', recursive) for lib in self.libraries]
420 if recursive:
421 new_dep.ext_deps = [dep.get_as_shared(True) for dep in self.ext_deps]
422 return new_dep
423
424 class ExternalDependency(Dependency):
425 def __init__(self, name: str, environment: 'Environment', kwargs: DependencyObjectKWs):
426 Dependency.__init__(self, kwargs)
427 self.env = environment
428 self.name = name
429 self.is_found = False
430 self.version_reqs = kwargs.get('version', [])
431 self.required = kwargs.get('required', True)
432 self.silent = kwargs.get('silent', False)
433 static = kwargs.get('static')
434 if static is None:
435 static = T.cast('bool', self.env.coredata.optstore.get_value_for(OptionKey('prefer_static')))
436 self.static = static
437 self.libtype = LibType.STATIC if self.static else LibType.PREFER_SHARED
438 # Is this dependency to be run on the build platform?
439 self.for_machine = kwargs['native']
440 self.clib_compiler = detect_compiler(self.name, environment, self.for_machine, self.language)
441
442 def get_compiler(self) -> T.Union['MissingCompiler', 'Compiler']:
443 return self.clib_compiler
444
445 def get_partial_dependency(self, *, compile_args: bool = False,
446 link_args: bool = False, links: bool = False,
447 includes: bool = False, sources: bool = False) -> Dependency:
448 new = copy.copy(self)
449 new._id = uuid.uuid4().int
450 if not compile_args:
451 new.compile_args = []
452 if not link_args:
453 new.link_args = []
454 if not sources:
455 new.sources = []
456 if not includes:
457 pass # TODO maybe filter compile_args?
458 if not sources:
459 new.sources = []
460
461 return new
462
463 def log_details(self) -> str:
464 return ''
465
466 def log_info(self) -> str:
467 return ''
468
469 # Check if dependency version meets the requirements
470 def _check_version(self) -> None:
471 if not self.is_found:
472 return
473
474 if self.version_reqs:
475 for_msg = ['for', mlog.bold(self.for_machine.get_lower_case_name()), 'machine']
476
477 # an unknown version can never satisfy any requirement
478 if not self.version:
479 self.is_found = False
480 found_msg: mlog.TV_LoggableList = []
481 found_msg.extend(['Dependency', mlog.bold(self.name)])
482 found_msg.extend(for_msg)
483 found_msg.append('found:')
484 found_msg.extend([str(mlog.red('NO')) + '.', 'Unknown version, but need:', self.version_reqs])
485 mlog.log(*found_msg)
486
487 if self.required:
488 m = f'Unknown version, but need {self.version_reqs!r}.'
489 raise DependencyException(m)
490
491 else:
492 (self.is_found, not_found, found) = \
493 version_compare_many(self.version, self.version_reqs)
494 if not self.is_found:
495 found_msg = ['Dependency', mlog.bold(self.name)]
496 found_msg.extend(for_msg)
497 found_msg.append('found:')
498 found_msg += [str(mlog.red('NO')) + '.',
499 'Found', mlog.normal_cyan(self.version), 'but need:',
500 mlog.bold(', '.join([f"'{e}'" for e in not_found]))]
501 if found:
502 found_msg += ['; matched:',
503 ', '.join([f"'{e}'" for e in found])]
504 mlog.log(*found_msg)
505
506 if self.required:
507 m = 'Invalid version, need {!r} {!r} found {!r}.'
508 raise DependencyException(m.format(self.name, not_found, self.version))
509 return
510
511
512 class NotFoundDependency(Dependency):
513
514 type_name = DependencyTypeName('not-found')
515
516 def __init__(self, name: str, environment: 'Environment') -> None:
517 super().__init__({'native': MachineChoice.HOST}) # TODO: does this actually matter?
518 self.env = environment
519 self.name = name
520 self.is_found = False
521
522 def get_partial_dependency(self, *, compile_args: bool = False,
523 link_args: bool = False, links: bool = False,
524 includes: bool = False, sources: bool = False) -> 'NotFoundDependency':
525 new = copy.copy(self)
526 new._id = uuid.uuid4().int
527 return new
528
529
530 class ExternalLibrary(ExternalDependency):
531
532 type_name = DependencyTypeName('library')
533
534 def __init__(self, name: str, link_args: T.List[str], environment: 'Environment',
535 language: Language, for_machine: MachineChoice, silent: bool = False) -> None:
536 super().__init__(name, environment, {'language': language, 'native': for_machine})
537 self.is_found = False
538 if link_args:
539 self.is_found = True
540 self.link_args = link_args
541 if not silent:
542 if self.is_found:
543 mlog.log('Library', mlog.bold(name), 'found:', mlog.green('YES'))
544 else:
545 mlog.log('Library', mlog.bold(name), 'found:', mlog.red('NO'))
546
547 def get_link_args(self, language: T.Optional[Language] = None, raw: bool = False) -> T.List[str]:
548 '''
549 External libraries detected using a compiler must only be used with
550 compatible code. For instance, Vala libraries (.vapi files) cannot be
551 used with C code, and not all Rust library types can be linked with
552 C-like code. Note that C++ libraries *can* be linked with C code with
553 a C++ linker (and vice-versa).
554 '''
555 # Using a vala library in a non-vala target, or a non-vala library in a vala target
556 # XXX: This should be extended to other non-C linkers such as Rust
557 if (self.language == 'vala' and language != 'vala') or \
558 (language == 'vala' and self.language != 'vala'):
559 return []
560 return super().get_link_args(language=language, raw=raw)
561
562 def get_partial_dependency(self, *, compile_args: bool = False,
563 link_args: bool = False, links: bool = False,
564 includes: bool = False, sources: bool = False) -> 'ExternalLibrary':
565 # External library only has link_args, so ignore the rest of the
566 # interface.
567 new = copy.copy(self)
568 new._id = uuid.uuid4().int
569 if not link_args:
570 new.link_args = []
571 return new
572
573
574 def get_leaf_external_dependencies(deps: T.List[Dependency]) -> T.List[Dependency]:
575 if not deps:
576 # Ensure that we always return a new instance
577 return deps.copy()
578 final_deps = []
579 while deps:
580 next_deps = []
581 for d in mesonlib.listify(deps):
582 if not isinstance(d, Dependency) or d.is_built():
583 raise DependencyException('Dependencies must be external dependencies')
584 final_deps.append(d)
585 next_deps.extend(d.ext_deps)
586 deps = next_deps
587 return final_deps
588
589
590 def sort_libpaths(libpaths: T.List[str], refpaths: T.List[str]) -> T.List[str]:
591 """Sort <libpaths> according to <refpaths>
592
593 It is intended to be used to sort -L flags returned by pkg-config.
594 Pkg-config returns flags in random order which cannot be relied on.
595 """
596 if len(refpaths) == 0:
597 return list(libpaths)
598
599 def key_func(libpath: str) -> T.Tuple[int, int]:
600 common_lengths: T.List[int] = []
601 for refpath in refpaths:
602 try:
603 common_path: str = os.path.commonpath([libpath, refpath])
604 except ValueError:
605 common_path = ''
606 common_lengths.append(len(common_path))
607 max_length = max(common_lengths)
608 max_index = common_lengths.index(max_length)
609 reversed_max_length = len(refpaths[max_index]) - max_length
610 return (max_index, reversed_max_length)
611 return sorted(libpaths, key=key_func)
612
613 def strip_system_libdirs(environment: 'Environment', for_machine: MachineChoice, link_args: T.List[str]) -> T.List[str]:
614 """Remove -L<system path> arguments.
615
616 leaving these in will break builds where a user has a version of a library
617 in the system path, and a different version not in the system path if they
618 want to link against the non-system path version.
619 """
620 exclude = {f'-L{p}' for p in environment.get_compiler_system_lib_dirs(for_machine)}
621 return [l for l in link_args if l not in exclude]
622
623 def strip_system_includedirs(environment: 'Environment', for_machine: MachineChoice, include_args: T.List[str]) -> T.List[str]:
624 """Remove -I<system path> arguments.
625
626 leaving these in will break builds where user want dependencies with system
627 include-type used in rust.bindgen targets as if will cause system headers
628 to not be found.
629 """
630
631 exclude = {f'-I{p}' for p in environment.get_compiler_system_include_dirs(for_machine)}
632 return [i for i in include_args if i not in exclude]
633
634 def process_method_kw(possible: T.Iterable[DependencyMethods], kwargs: DependencyObjectKWs) -> T.List[DependencyMethods]:
635 method = kwargs.get('method', DependencyMethods.AUTO)
636
637 # Set the detection method. If the method is set to auto, use any available method.
638 # If method is set to a specific string, allow only that detection method.
639 if method == DependencyMethods.AUTO:
640 # annotated for https://github.com/python/mypy/issues/19894
641 methods: T.List[DependencyMethods] = list(possible)
642 elif method in possible:
643 methods = [method]
644 else:
645 raise DependencyException(
646 'Unsupported detection method: {}, allowed methods are {}'.format(
647 method.value,
648 mlog.format_list([x.value for x in [DependencyMethods.AUTO] + list(possible)])))
649
650 return methods
651
652 def detect_compiler(name: str, env: 'Environment', for_machine: MachineChoice,
653 language: T.Optional[Language]) -> T.Union['MissingCompiler', 'Compiler']:
654 """Given a language and environment find the compiler used."""
655 compilers = env.coredata.compilers[for_machine]
656
657 # Set the compiler for this dependency if a language is specified,
658 # else try to pick something that looks usable.
659 if language:
660 if language not in compilers:
661 m = name.capitalize() + ' requires a {0} compiler, but ' \
662 '{0} is not in the list of project languages'
663 raise DependencyException(m.format(language.capitalize()))
664 return compilers[language]
665 else:
666 # https://github.com/python/mypy/issues/18826
667 # However, we need to support versions of mypy that cannot deduce the
668 # tuple.
669 for lang in T.cast('T.Tuple[Language, ...]', clib_langs):
670 try:
671 return compilers[lang]
672 except KeyError:
673 continue
674 return MissingCompiler()
675
676
677 class SystemDependency(ExternalDependency):
678
679 """Dependency base for System type dependencies."""
680
681 type_name = DependencyTypeName('system')
682
683
684 class BuiltinDependency(ExternalDependency):
685
686 """Dependency base for Builtin type dependencies."""
687
688 type_name = DependencyTypeName('builtin')
689
690
691 @dataclasses.dataclass
692 class DependencyCandidate(T.Generic[DepType]):
693
694 callable: T.Union[T.Type[DepType], T.Callable[[str, Environment, DependencyObjectKWs], DepType]]
695 name: str
696 method: str
697 modules: T.Optional[T.List[str]] = None
698 arguments: T.Optional[T.Tuple[Environment, DependencyObjectKWs]] = dataclasses.field(default=None)
699
700 def __call__(self) -> DepType:
701 if self.arguments is None:
702 raise mesonlib.MesonBugException('Attempted to instantiate a candidate before setting its arguments')
703 env, kwargs = self.arguments
704 if self.modules is not None:
705 kwargs['modules'] = self.modules.copy()
706 return self.callable(self.name, env, kwargs)
707
708 @classmethod
709 def from_dependency(cls, name: str, dep: T.Type[DepType],
710 args: T.Optional[T.Tuple[Environment, DependencyObjectKWs]] = None,
711 modules: T.Optional[T.List[str]] = None,
712 ) -> DependencyCandidate[DepType]:
713 tried = str(dep.type_name)
714
715 # fixup the cases where type_name and log tried don't match
716 if tried in {'extraframeworks', 'appleframeworks'}:
717 tried = 'framework'
718 elif tried == 'pkgconfig':
719 tried = 'pkg-config'
720
721 return cls(dep, name, tried, modules, arguments=args)