Debian Codegraph @

mesonbuild/dependencies/__init__.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2017 The Meson development team
3
4
5 from .base import Dependency, InternalDependency, ExternalDependency, NotFoundDependency, MissingCompiler
6 from .base import (
7 ExternalLibrary, DependencyException, DependencyMethods,
8 BuiltinDependency, SystemDependency, get_leaf_external_dependencies)
9 from .detect import find_external_dependency, get_dep_identifier, packages, _packages_accept_language
10
11 __all__ = [
12 'Dependency',
13 'InternalDependency',
14 'ExternalDependency',
15 'SystemDependency',
16 'BuiltinDependency',
17 'NotFoundDependency',
18 'ExternalLibrary',
19 'DependencyException',
20 'DependencyMethods',
21 'MissingCompiler',
22
23 'find_external_dependency',
24 'get_dep_identifier',
25 'get_leaf_external_dependencies',
26 ]
27
28 """Dependency representations and discovery logic.
29
30 Meson attempts to largely abstract away dependency discovery information, and
31 to encapsulate that logic itself so that the DSL doesn't have too much direct
32 information. There are some cases where this is impossible/undesirable, such
33 as the `get_variable()` method.
34
35 Meson has four primary dependency types:
36 1. pkg-config
37 2. apple frameworks
38 3. CMake
39 4. system
40
41 Plus a few more niche ones.
42
43 When a user calls `dependency('foo')` Meson creates a list of candidates, and
44 tries those candidates in order to find one that matches the criteria
45 provided by the user (such as version requirements, or optional components
46 that are required.)
47
48 Except to work around bugs or handle odd corner cases, pkg-config and CMake
49 generally just work™, though there are exceptions. Most of this package is
50 concerned with dependencies that don't (always) provide CMake and/or
51 pkg-config files.
52
53 For these cases one needs to write a `system` dependency. These dependencies
54 descend directly from `ExternalDependency`, in their constructor they
55 manually set up the necessary link and compile args (and additional
56 dependencies as necessary).
57
58 For example, imagine a dependency called Foo, it uses an environment variable
59 called `$FOO_ROOT` to point to its install root, which looks like this:
60 ```txt
61 $FOOROOT
62 → include/
63 → lib/
64 ```
65 To use Foo, you need its include directory, and you need to link to
66 `lib/libfoo.ext`.
67
68 You could write code that looks like:
69
70 ```python
71 class FooSystemDependency(ExternalDependency):
72
73 def __init__(self, name: str, environment: 'Environment', kwargs: T.Dict[str, T.Any]):
74 super().__init__(name, environment, kwargs)
75 root = os.environ.get('FOO_ROOT')
76 if root is None:
77 mlog.debug('$FOO_ROOT is unset.')
78 self.is_found = False
79 return
80
81 lib = self.clib_compiler.find_library('foo', [os.path.join(root, 'lib')])
82 if lib is None:
83 mlog.debug('Could not find lib.')
84 self.is_found = False
85 return
86
87 self.compile_args.append(f'-I{os.path.join(root, "include")}')
88 self.link_args.append(lib)
89 self.is_found = True
90 ```
91
92 This code will look for `FOO_ROOT` in the environment, handle `FOO_ROOT` being
93 undefined gracefully, then set its `compile_args` and `link_args` gracefully.
94 It will also gracefully handle not finding the required lib (hopefully that
95 doesn't happen, but it could if, for example, the lib is only static and
96 shared linking is requested).
97
98 There are a couple of things about this that still aren't ideal. For one, we
99 don't want to be reading random environment variables at this point. Those
100 should actually be added to `envconfig.Properties` and read in
101 `environment.Environment._set_default_properties_from_env` (see how
102 `BOOST_ROOT` is handled). We can also handle the `static` keyword and the
103 `prefer_static` built-in option. So now that becomes:
104
105 ```python
106 class FooSystemDependency(ExternalDependency):
107
108 def __init__(self, name: str, environment: 'Environment', kwargs: T.Dict[str, T.Any]):
109 super().__init__(name, environment, kwargs)
110 root = environment.properties[self.for_machine].foo_root
111 if root is None:
112 mlog.debug('foo_root is unset.')
113 self.is_found = False
114 return
115
116 get_option = environment.coredata.get_option
117 static_opt = kwargs['static'] if kwargs.get('static') is not None else get_option(Mesonlib.OptionKey('prefer_static')
118 static = Mesonlib.LibType.STATIC if static_opt else Mesonlib.LibType.SHARED
119 lib = self.clib_compiler.find_library(
120 'foo', environment, [os.path.join(root, 'lib')], libtype=static)
121 if lib is None:
122 mlog.debug('Could not find lib.')
123 self.is_found = False
124 return
125
126 self.compile_args.append(f'-I{os.path.join(root, "include")}')
127 self.link_args.append(lib)
128 self.is_found = True
129 ```
130
131 This is nicer in a couple of ways. First we can properly cross compile as we
132 are allowed to set `FOO_ROOT` for both the build and host machines, it also
133 means that users can override this in their machine files, and if that
134 environment variables changes during a Meson reconfigure Meson won't re-read
135 it, this is important for reproducibility. Finally, Meson will figure out
136 whether it should be finding `libfoo.so` or `libfoo.a` (or the platform
137 specific names). Things are looking pretty good now, so it can be added to
138 the `packages` dict below:
139
140 ```python
141 packages.update({
142 'foo': FooSystemDependency,
143 })
144 ```
145
146 Now, what if foo also provides pkg-config, but it's only shipped on Unices,
147 or only included in very recent versions of the dependency? We can use the
148 `DependencyFactory` class:
149
150 ```python
151 foo_factory = DependencyFactory(
152 'foo',
153 [DependencyMethods.PKGCONFIG, DependencyMethods.SYSTEM],
154 system=FooSystemDependency,
155 )
156 ```
157
158 This is a helper function that will generate a default pkg-config based
159 dependency, and use the `FooSystemDependency` as well. It can also handle
160 custom finders for pkg-config and cmake based dependencies that need some
161 extra help. You would then add the `foo_factory` to packages instead of
162 `FooSystemDependency`:
163
164 ```python
165 packages.update({
166 'foo': foo_factory,
167 })
168 ```
169
170 If you have a dependency that is very complicated, (such as having multiple
171 implementations) you may need to write your own factory function. There are a
172 number of examples in this package.
173
174 _Note_ before we moved to factory functions it was common to use an
175 `ExternalDependency` class that would instantiate different types of
176 dependencies and hold the one it found. There are a number of drawbacks to
177 this approach, and no new dependencies should do this.
178 """
179
180 # This is a dict where the keys should be strings, and the values must be one
181 # of:
182 # - An ExternalDependency subclass
183 # - A DependencyFactory object
184 # - A callable with a signature of (Environment, MachineChoice, Dict[str, Any]) -> List[Callable[[], ExternalDependency]]
185 #
186 # The internal "defaults" attribute contains a separate dictionary mapping
187 # for lazy imports. The values must be:
188 # - a string naming the submodule that should be imported from `mesonbuild.dependencies` to populate the dependency
189 packages.defaults.update({
190 # From dev:
191 'gtest': 'dev',
192 'gmock': 'dev',
193 'llvm': 'dev',
194 'valgrind': 'dev',
195 'zlib': 'dev',
196 'jni': 'dev',
197 'jdk': 'dev',
198 'diasdk': 'dev',
199
200 'boost': 'boost',
201 'cuda': 'cuda',
202
203 # per-file
204 'coarray': 'coarrays',
205 'hdf5': 'hdf5',
206 'mpi': 'mpi',
207 'scalapack': 'scalapack',
208
209 # From misc:
210 'blocks': 'misc',
211 'curses': 'misc',
212 'netcdf': 'misc',
213 'openmp': 'misc',
214 'threads': 'misc',
215 'pcap': 'misc',
216 'cups': 'misc',
217 'libwmf': 'misc',
218 'libgcrypt': 'misc',
219 'gpgme': 'misc',
220 'shaderc': 'misc',
221 'iconv': 'misc',
222 'intl': 'misc',
223 'atomic': 'misc',
224 'dl': 'misc',
225 'openssl': 'misc',
226 'libcrypto': 'misc',
227 'libssl': 'misc',
228 'objfw': 'misc',
229
230 # From platform:
231 'appleframeworks': 'platform',
232
233 # from python:
234 'numpy': 'python',
235 'python3': 'python',
236 'pybind11': 'python',
237
238 # From ui:
239 'gl': 'ui',
240 'gnustep': 'ui',
241 'sdl2': 'ui',
242 'wxwidgets': 'ui',
243 'vulkan': 'ui',
244
245 # from qt
246 'qt4': 'qt',
247 'qt5': 'qt',
248 'qt6': 'qt',
249 })
250 _packages_accept_language.update({
251 'hdf5',
252 'mpi',
253 'netcdf',
254 'openmp',
255 })