Debian Codegraph @

mesonbuild/compilers/compilers.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2022 The Meson development team
3 # Copyright © 2023-2025 Intel Corporation
4
5 from __future__ import annotations
6
7 import abc
8 import contextlib, os.path, re
9 import enum
10 import itertools
11 import typing as T
12 from dataclasses import dataclass, field
13 from functools import lru_cache
14
15 from .. import mlog
16 from .. import mesonlib
17 from .. import options
18 from ..mesonlib import (
19 HoldableObject, SimpleABC,
20 EnvironmentException, MesonBugException, MesonException,
21 Popen_safe_logged, LibType, TemporaryDirectoryWinProof,
22 )
23 from ..options import OptionKey
24 from ..arglist import CompilerArgs
25
26 if T.TYPE_CHECKING:
27 from typing_extensions import Literal, TypeAlias
28
29 from .. import build
30 from .. import coredata
31 from ..build import BuildTarget, DFeatures
32 from ..options import MutableKeyedOptionDictType
33 from ..envconfig import MachineInfo
34 from ..environment import Environment
35 from ..linkers import RSPFileSyntax
36 from ..linkers.linkers import DynamicLinker
37 from ..mesonlib import MachineChoice
38 from ..dependencies import Dependency
39
40 # See the comment on `lang_suffixes` if modifying this list.
41 Language = Literal[
42 'c', 'cpp', 'cuda', 'fortran', 'd', 'objc', 'objcpp', 'rust', 'vala',
43 'cs', 'swift', 'java', 'cython', 'nasm', 'masm', 'linearasm'
44 ]
45 CompilerDict: TypeAlias = T.Dict[Language, 'Compiler']
46
47 _T = T.TypeVar('_T')
48
49 """This file contains the data files of all compilers Meson knows
50 about. To support a new compiler, add its information below.
51 Also add corresponding autodetection code in detect.py."""
52
53 header_suffixes = {'h', 'hh', 'hpp', 'hxx', 'H', 'ipp', 'moc', 'vapi', 'di', 'pxd', 'pxi'}
54 obj_suffixes = {'o', 'obj', 'res'}
55 # To the emscripten compiler, .js files are libraries
56 lib_suffixes = {'a', 'lib', 'dll', 'dll.a', 'dylib', 'so', 'js'}
57 # Mapping of language to suffixes of files that should always be in that language
58 # This means we can't include .h headers here since they could be C, C++, ObjC, etc.
59 # First suffix is the language's default.
60
61 # Don't forget to update the Language if adding new keys, as well as
62 # docs/yaml/functions/project.yaml
63 lang_suffixes: T.Mapping[Language, T.Tuple[str, ...]] = {
64 'c': ('c',),
65 'cpp': ('cpp', 'cppm', 'cc', 'cp', 'cxx', 'c++', 'hh', 'hp', 'hpp', 'ipp', 'hxx', 'h++', 'ino', 'ixx', 'CPP', 'C', 'HPP', 'H'),
66 'cuda': ('cu',),
67 # f90, f95, f03, f08 are for free-form fortran ('f90' recommended)
68 # f, for, ftn, fpp are for fixed-form fortran ('f' or 'for' recommended)
69 'fortran': ('f90', 'f95', 'f03', 'f08', 'f', 'for', 'ftn', 'fpp'),
70 'd': ('d', 'di'),
71 'objc': ('m',),
72 'objcpp': ('mm',),
73 'rust': ('rs',),
74 'vala': ('vala', 'vapi', 'gs'),
75 'cs': ('cs',),
76 'swift': ('swift',),
77 'java': ('java',),
78 'cython': ('pyx', ),
79 'nasm': ('asm', 'nasm',),
80 'masm': ('masm',),
81 'linearasm': ('sa',),
82 }
83 # Some compilers only recognize files with specific suffixes.
84 compiler_suffixes: T.Mapping[str, T.Tuple[str, ...]] = {
85 'msvc': ('c', 'cc', 'cxx', 'cpp', 'obj', 'lib', 'def'),
86 }
87 all_languages: mesonlib.OrderedSet[Language] = mesonlib.OrderedSet(sorted(lang_suffixes))
88 c_cpp_suffixes = {'h'}
89 cpp_suffixes = set(lang_suffixes['cpp']) | c_cpp_suffixes
90 c_suffixes = set(lang_suffixes['c']) | c_cpp_suffixes
91 assembler_suffixes = {'s', 'S', 'sx', 'asm', 'masm'}
92 llvm_ir_suffixes = {'ll'}
93 all_suffixes = set(itertools.chain(*lang_suffixes.values(), assembler_suffixes, llvm_ir_suffixes, c_cpp_suffixes))
94 source_suffixes = all_suffixes - header_suffixes
95 # List of languages that by default consume and output libraries following the
96 # C ABI; these can generally be used interchangeably
97 # This must be sorted, see sort_clink().
98 clib_langs = ('objcpp', 'cpp', 'objc', 'c', 'nasm', 'fortran')
99 # List of languages that can be linked with C code directly by the linker
100 # used in build.py:process_compilers() and build.py:get_dynamic_linker()
101 # This must be sorted, see sort_clink().
102 clink_langs = ('rust', 'd', 'cuda') + clib_langs
103
104 SUFFIX_TO_LANG: T.Mapping[str, Language] = dict(itertools.chain(*(
105 [(suffix, lang) for suffix in v] for lang, v in lang_suffixes.items())))
106
107 # Languages that should use LDFLAGS arguments when linking.
108 LANGUAGES_USING_LDFLAGS = {'objcpp', 'cpp', 'objc', 'c', 'fortran', 'd', 'cuda'}
109 # Languages that should use CPPFLAGS arguments when linking.
110 LANGUAGES_USING_CPPFLAGS = {'c', 'cpp', 'objc', 'objcpp'}
111 soregex = re.compile(r'.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$')
112
113 # Environment variables that each lang uses.
114 CFLAGS_MAPPING: T.Mapping[Language, str] = {
115 'c': 'CFLAGS',
116 'cpp': 'CXXFLAGS',
117 'cuda': 'CUFLAGS',
118 'objc': 'OBJCFLAGS',
119 'objcpp': 'OBJCXXFLAGS',
120 'fortran': 'FFLAGS',
121 'd': 'DFLAGS',
122 'vala': 'VALAFLAGS',
123 'rust': 'RUSTFLAGS',
124 'cython': 'CYTHONFLAGS',
125 'cs': 'CSFLAGS', # This one might not be standard.
126 }
127
128 # All these are only for C-linkable languages; see `clink_langs` above.
129
130 def sort_clink(lang: Language) -> int:
131 '''
132 Sorting function to sort the list of languages according to
133 reversed(compilers.clink_langs) and append the unknown langs in the end.
134 The purpose is to prefer C over C++ for files that can be compiled by
135 both such as assembly, C, etc. Also applies to ObjC, ObjC++, etc.
136 '''
137 if lang not in clink_langs:
138 return 1
139 return -clink_langs.index(lang)
140
141 def is_header(fname: 'mesonlib.FileOrString') -> bool:
142 if isinstance(fname, mesonlib.File):
143 fname = fname.fname
144 suffix = fname.split('.')[-1]
145 return suffix in header_suffixes
146
147 def is_source_suffix(suffix: str) -> bool:
148 return suffix in source_suffixes
149
150 @lru_cache(maxsize=None)
151 def cached_is_source_by_name(fname: str) -> bool:
152 suffix = fname.split('.')[-1].lower()
153 return is_source_suffix(suffix)
154
155 def is_source(fname: 'mesonlib.FileOrString') -> bool:
156 if isinstance(fname, mesonlib.File):
157 fname = fname.fname
158 return cached_is_source_by_name(fname)
159
160 def is_assembly(fname: 'mesonlib.FileOrString') -> bool:
161 if isinstance(fname, mesonlib.File):
162 fname = fname.fname
163 suffix = fname.split('.')[-1]
164 return suffix in assembler_suffixes
165
166 def is_java(fname: mesonlib.FileOrString) -> bool:
167 if isinstance(fname, mesonlib.File):
168 fname = fname.fname
169 suffix = fname.split('.')[-1]
170 return suffix in lang_suffixes['java']
171
172 def is_separate_compile(fname: mesonlib.FileOrString) -> bool:
173 return not fname.endswith('.rs')
174
175 def is_llvm_ir(fname: 'mesonlib.FileOrString') -> bool:
176 if isinstance(fname, mesonlib.File):
177 fname = fname.fname
178 suffix = fname.split('.')[-1]
179 return suffix in llvm_ir_suffixes
180
181 @lru_cache(maxsize=None)
182 def cached_is_object_by_name(fname: str) -> bool:
183 suffix = fname.split('.')[-1]
184 return suffix in obj_suffixes
185
186 def is_object(fname: 'mesonlib.FileOrString') -> bool:
187 if isinstance(fname, mesonlib.File):
188 fname = fname.fname
189 return cached_is_object_by_name(fname)
190
191 @lru_cache(maxsize=None)
192 def cached_is_library_by_name(fname: str) -> bool:
193 if soregex.match(fname):
194 return True
195
196 suffix = fname.split('.')[-1]
197 return suffix in lib_suffixes
198
199 def is_library(fname: 'mesonlib.FileOrString') -> bool:
200 if isinstance(fname, mesonlib.File):
201 fname = fname.fname
202 return cached_is_library_by_name(fname)
203
204 def is_known_suffix(fname: 'mesonlib.FileOrString') -> bool:
205 if isinstance(fname, mesonlib.File):
206 fname = fname.fname
207 suffix = fname.split('.')[-1]
208
209 return suffix in all_suffixes
210
211
212 class CompileCheckMode(enum.Enum):
213
214 PREPROCESS = 'preprocess'
215 COMPILE = 'compile'
216 LINK = 'link'
217
218
219 gnu_winlibs = ['-lkernel32', '-luser32', '-lgdi32', '-lwinspool', '-lshell32',
220 '-lole32', '-loleaut32', '-luuid', '-lcomdlg32', '-ladvapi32']
221
222 msvc_winlibs = ['kernel32.lib', 'user32.lib', 'gdi32.lib',
223 'winspool.lib', 'shell32.lib', 'ole32.lib', 'oleaut32.lib',
224 'uuid.lib', 'comdlg32.lib', 'advapi32.lib']
225
226 clike_optimization_args: T.Dict[str, T.List[str]] = {
227 'plain': [],
228 '0': [],
229 'g': [],
230 '1': ['-O1'],
231 '2': ['-O2'],
232 '3': ['-O3'],
233 's': ['-Os'],
234 }
235
236 clike_debug_args: T.Dict[bool, T.List[str]] = {
237 False: [],
238 True: ['-g']
239 }
240
241
242 def option_enabled(boptions: T.Set[OptionKey],
243 target: 'BuildTarget',
244 env: 'Environment',
245 option: T.Union[str, OptionKey]) -> bool:
246 if isinstance(option, str):
247 option = OptionKey(option)
248 try:
249 if option not in boptions:
250 return False
251 ret = env.coredata.get_option_for_target(target, option)
252 assert isinstance(ret, bool), 'must return bool' # could also be str
253 return ret
254 except KeyError:
255 return False
256
257
258 def get_option_value_for_target(env: 'Environment', target: 'BuildTarget', opt: OptionKey, fallback: '_T') -> '_T':
259 """Get the value of an option, or the fallback value."""
260 try:
261 v = env.coredata.get_option_for_target(target, opt)
262 except (KeyError, AttributeError):
263 return fallback
264
265 assert isinstance(v, type(fallback)), f'Should have {type(fallback)!r} but was {type(v)!r}'
266 # Mypy doesn't understand that the above assert ensures that v is type _T
267 return v
268
269
270 def are_asserts_disabled(target: 'BuildTarget', env: 'Environment') -> bool:
271 """Should debug assertions be disabled
272
273 :param target: a target to check for
274 :param env: the environment
275 :return: whether to disable assertions or not
276 """
277 return (env.coredata.get_option_for_target(target, 'b_ndebug') == 'true' or
278 (env.coredata.get_option_for_target(target, 'b_ndebug') == 'if-release' and
279 env.coredata.get_option_for_target(target, 'buildtype') in {'release', 'plain'}))
280
281
282 def are_asserts_disabled_for_subproject(subproject: str, env: 'Environment') -> bool:
283 key = OptionKey('b_ndebug', subproject)
284 return (env.coredata.optstore.get_value_for(key) == 'true' or
285 (env.coredata.optstore.get_value_for(key) == 'if-release' and
286 env.coredata.optstore.get_value_for(key.evolve(name='buildtype')) in {'release', 'plain'}))
287
288
289 def get_base_compile_args(target: 'BuildTarget', compiler: 'Compiler', env: 'Environment') -> T.List[str]:
290 args: T.List[str] = []
291 lto = False
292 try:
293 if env.coredata.get_option_for_target(target, 'b_lto'):
294 num_threads = get_option_value_for_target(env, target, OptionKey('b_lto_threads'), 0)
295 ltomode = get_option_value_for_target(env, target, OptionKey('b_lto_mode'), 'default')
296 args.extend(compiler.get_lto_compile_args(
297 target=target,
298 threads=num_threads,
299 mode=ltomode))
300 lto = True
301 except (KeyError, AttributeError):
302 pass
303 try:
304 clrout = env.coredata.get_option_for_target(target, 'b_colorout')
305 assert isinstance(clrout, str)
306 args += compiler.get_colorout_args(clrout)
307 except KeyError:
308 pass
309 try:
310 sanitize = env.coredata.get_option_for_target(target, 'b_sanitize')
311 assert isinstance(sanitize, list)
312 if sanitize == ['none']:
313 sanitize = []
314 sanitize_args = compiler.sanitizer_compile_args(target, sanitize)
315 # We consider that if there are no sanitizer arguments returned, then
316 # the language doesn't support them.
317 if sanitize_args:
318 if not compiler.has_multi_arguments(sanitize_args)[0]:
319 raise MesonException(f'Compiler {compiler.name_string()} does not support sanitizer arguments {sanitize_args}')
320 args.extend(sanitize_args)
321 except KeyError:
322 pass
323 try:
324 pgo_val = env.coredata.get_option_for_target(target, 'b_pgo')
325 if pgo_val == 'generate':
326 args.extend(compiler.get_profile_generate_args())
327 elif pgo_val == 'use':
328 args.extend(compiler.get_profile_use_args())
329 except (KeyError, AttributeError):
330 pass
331 try:
332 if env.coredata.get_option_for_target(target, 'b_coverage'):
333 args += compiler.get_coverage_args()
334 except (KeyError, AttributeError):
335 pass
336 try:
337 args += compiler.get_assert_args(are_asserts_disabled(target, env))
338 except KeyError:
339 pass
340 # This does not need a try...except
341 bitcode = option_enabled(compiler.base_options, target, env, 'b_bitcode')
342 args.extend(compiler.get_embed_bitcode_args(bitcode, lto))
343 try:
344 crt_val = env.coredata.get_option_for_target(target, 'b_vscrt')
345 assert isinstance(crt_val, str)
346 try:
347 args += compiler.get_crt_compile_args(crt_val)
348 except EnvironmentException:
349 pass
350 except KeyError:
351 pass
352 return args
353
354 def get_base_link_args(target: 'BuildTarget',
355 linker: 'Compiler',
356 env: 'Environment') -> T.List[str]:
357 args: T.List[str] = []
358 build_dir = env.get_build_dir()
359 if env.coredata.get_option_for_target(target, 'werror'):
360 args.extend(linker.get_linker_fatal_warnings())
361 try:
362 if env.coredata.get_option_for_target(target, 'b_lto'):
363 if env.coredata.get_option_for_target(target, 'werror'):
364 args.extend(linker.get_werror_args())
365
366 thinlto_cache_dir = None
367 cachedir_key = OptionKey('b_thinlto_cache')
368 if get_option_value_for_target(env, target, cachedir_key, False):
369 thinlto_cache_dir = get_option_value_for_target(env, target, OptionKey('b_thinlto_cache_dir'), '')
370 if thinlto_cache_dir == '':
371 thinlto_cache_dir = os.path.join(build_dir, 'meson-private', 'thinlto-cache')
372 os.makedirs(thinlto_cache_dir, exist_ok=True)
373 num_threads = get_option_value_for_target(env, target, OptionKey('b_lto_threads'), 0)
374 lto_mode = get_option_value_for_target(env, target, OptionKey('b_lto_mode'), 'default')
375 args.extend(linker.get_lto_link_args(
376 target=target,
377 threads=num_threads,
378 mode=lto_mode,
379 thinlto_cache_dir=thinlto_cache_dir))
380 obj_cache_path = os.path.join('@PRIVATE_DIR@', "lto.o")
381 args.extend(linker.get_lto_obj_cache_path(obj_cache_path))
382 except (KeyError, AttributeError):
383 pass
384 try:
385 sanitizer = env.coredata.get_option_for_target(target, 'b_sanitize')
386 assert isinstance(sanitizer, list)
387 if sanitizer == ['none']:
388 sanitizer = []
389 sanitizer_args = linker.sanitizer_link_args(target, sanitizer)
390 # We consider that if there are no sanitizer arguments returned, then
391 # the language doesn't support them.
392 if sanitizer_args:
393 if not linker.has_multi_link_arguments(sanitizer_args, False)[0]:
394 raise MesonException(f'Linker {linker.name_string()} does not support sanitizer arguments {sanitizer_args}')
395 args.extend(sanitizer_args)
396 except KeyError:
397 pass
398 try:
399 pgo_val = env.coredata.get_option_for_target(target, 'b_pgo')
400 if pgo_val == 'generate':
401 args.extend(linker.get_profile_generate_args())
402 elif pgo_val == 'use':
403 args.extend(linker.get_profile_use_args())
404 except (KeyError, AttributeError):
405 pass
406 try:
407 if env.coredata.get_option_for_target(target, 'b_coverage'):
408 args += linker.get_coverage_link_args()
409 except (KeyError, AttributeError):
410 pass
411
412 as_needed = option_enabled(linker.base_options, target, env, 'b_asneeded')
413 bitcode = option_enabled(linker.base_options, target, env, 'b_bitcode')
414 # Shared modules cannot be built with bitcode_bundle because
415 # -bitcode_bundle is incompatible with -undefined and -bundle
416 if bitcode and not target.typename == 'shared module':
417 args.extend(linker.bitcode_args())
418 elif as_needed:
419 # -Wl,-dead_strip_dylibs is incompatible with bitcode
420 args.extend(linker.get_asneeded_args())
421
422 # Apple's ld (the only one that supports bitcode) does not like -undefined
423 # arguments or -headerpad_max_install_names when bitcode is enabled
424 if not bitcode:
425 from ..build import SharedModule
426 args.extend(linker.headerpad_args())
427 if (not isinstance(target, SharedModule) and
428 option_enabled(linker.base_options, target, env, 'b_lundef')):
429 args.extend(linker.no_undefined_link_args())
430 else:
431 args.extend(linker.get_allow_undefined_link_args())
432
433 try:
434 crt_val = env.coredata.get_option_for_target(target, 'b_vscrt')
435 assert isinstance(crt_val, str)
436 try:
437 crtargs = linker.get_crt_link_args(crt_val)
438 assert isinstance(crtargs, list)
439 args += crtargs
440 except EnvironmentException:
441 pass
442 except KeyError:
443 pass
444 return args
445
446
447 class CrossNoRunException(MesonException):
448 pass
449
450 @dataclass
451 class RunResult(HoldableObject):
452 compiled: bool
453 returncode: int = 999
454 stdout: str = 'UNDEFINED'
455 stderr: str = 'UNDEFINED'
456 cached: bool = False
457
458
459 class LinkerOptionStyle(metaclass=abc.ABCMeta):
460 @abc.abstractmethod
461 def wrap(self, group: T.List[str]) -> T.List[str]:
462 ...
463
464
465 @dataclass
466 class PrefixArgumentLinkerOptionStyle(LinkerOptionStyle):
467 """
468 Represents a linker option style where each linker argument is preceded by a separate argument representing
469 the compiler's pass-through option, like Clang: ['-Xlinker', 'arg1', '-Xlinker', 'arg2'] passes ['arg1', 'arg2'] to the
470 linker.
471 """
472
473 prefix_arg: str
474
475 def wrap(self, group: T.List[str]) -> T.List[str]:
476 return [compiler_arg for linker_arg in group for compiler_arg in [self.prefix_arg, linker_arg]]
477
478
479 @dataclass
480 class SimplePrefixLinkerOptionStyle(LinkerOptionStyle):
481 """
482 Represents a linker option style where each linker argument is prefixed with the compiler's pass-through
483 option as part of the same argument, like DMD: ['-L=arg1', '-L=arg2'] passes ['arg1', 'arg2'] to the linker.
484 """
485
486 prefix: str
487
488 def wrap(self, group: T.List[str]) -> T.List[str]:
489 return [self.prefix + linker_arg for linker_arg in group]
490
491
492 class LinkerArgumentWrapException(MesonException):
493 pass
494
495
496 @dataclass
497 class ManyInOneLinkerOptionStyle(LinkerOptionStyle):
498 """
499 Represents a linker option style where multiple linker arguments are passed as a single argument to the
500 compiler combined with a prefix, like GCC: ['-Wl,arg1,arg2'] passes ['arg1', 'arg2'] to the linker.
501 """
502
503 prefix: str
504 separator: str
505
506 fallback: T.Optional[LinkerOptionStyle] = None
507
508 def wrap(self, group: T.List[str]) -> T.List[str]:
509 for el in group:
510 if self.separator not in el:
511 continue
512
513 if self.fallback is not None:
514 return self.fallback.wrap(group)
515
516 full = ''
517 if len(group) > 1:
518 full = f' (part of arguments list {group!r})'
519 stripped = f'{self.prefix}{el}'
520 raise LinkerArgumentWrapException(f'Cannot wrap linker argument {el!r}{full} for compiler interface: '
521 f'would result in {stripped!r}, which the compiler would interpret as '
522 f'multiple linker arguments since it treats {self.separator!r} as the '
523 'separator.')
524
525 return [self.prefix + self.separator.join(group)]
526
527
528 @dataclass
529 class CompileResult(HoldableObject):
530
531 """The result of Compiler.compiles (and friends)."""
532
533 stdout: str
534 stderr: str
535 command: T.List[str]
536 returncode: int
537 input_name: str
538 output_name: T.Optional[str] = field(default=None, init=False)
539 cached: bool = field(default=False, init=False)
540
541 class Compiler(HoldableObject, metaclass=SimpleABC):
542
543 # Libraries to ignore in find_library() since they are provided by the
544 # compiler or the C library. Currently only used for MSVC.
545 ignore_libs: T.List[str] = []
546 # Libraries that are internal compiler implementations, and must not be
547 # manually searched.
548 internal_libs: T.List[str] = []
549
550 LINKER_OPTION_STYLE: T.Optional[LinkerOptionStyle] = None
551
552 # If the compiler is used to fire a separate linking step, environment
553 # variables like CFLAGS have to be passed to the linking step as well.
554 # They do not have to be passed if the linker is invoked directly (such
555 # as for Visual Studio's LINK.EXE) or if the compilation and linking
556 # steps are one and the same (such as for Rust).
557 USED_FOR_SEPARATE_LINKING_STEP = True
558
559 language: Language
560 id: str
561 warn_args: T.Dict[str, T.List[str]]
562 mode = 'COMPILER'
563
564 def __init__(self, ccache: T.List[str], exelist: T.List[str], version: str,
565 for_machine: MachineChoice, environment: Environment,
566 linker: T.Optional['DynamicLinker'] = None,
567 full_version: T.Optional[str] = None):
568 self.exelist = ccache + exelist
569 self.exelist_no_ccache = exelist
570 self.file_suffixes = lang_suffixes[self.language]
571 self.can_compile_suffixes = set(self.file_suffixes)
572 self.default_suffix = self.file_suffixes[0]
573 self.version = version
574 self.full_version = full_version
575 self.for_machine = for_machine
576 self.base_options: T.Set[OptionKey] = set()
577 self.linker = linker
578 self.environment = environment
579 self.is_cross = environment.is_cross_build(for_machine)
580 self.modes: T.List[Compiler] = []
581
582 @property
583 def info(self) -> MachineInfo:
584 # This must be fetched dynamically because it may be re-evaluated later,
585 # and we could end up with a stale copy
586 # see :class:`Interpreter._redetect_machines()`
587 return self.environment.machines[self.for_machine]
588
589 def init_from_options(self) -> None:
590 """Initializer compiler attributes that require options to be set."""
591
592 def __repr__(self) -> str:
593 repr_str = "<{0}: v{1} `{2}`>"
594 return repr_str.format(self.__class__.__name__, self.version,
595 ' '.join(self.exelist))
596
597 @lru_cache(maxsize=None)
598 def can_compile(self, src: 'mesonlib.FileOrString') -> bool:
599 if isinstance(src, mesonlib.File):
600 src = src.fname
601 suffix = os.path.splitext(src)[1]
602 if suffix != '.C':
603 suffix = suffix.lower()
604 return bool(suffix) and suffix[1:] in self.can_compile_suffixes
605
606 def get_id(self) -> str:
607 return self.id
608
609 def get_modes(self) -> T.List[Compiler]:
610 return self.modes
611
612 def get_exe(self) -> str:
613 return self.exelist[0]
614
615 def get_exe_args(self) -> T.List[str]:
616 return self.exelist[1:]
617
618 def get_linker_id(self) -> str:
619 # There is not guarantee that we have a dynamic linker instance, as
620 # some languages don't have separate linkers and compilers. In those
621 # cases return the compiler id
622 try:
623 return self.linker.id
624 except AttributeError:
625 return self.id
626
627 def get_version_string(self) -> str:
628 details = [self.id, self.version]
629 if self.full_version:
630 details += ['"%s"' % (self.full_version)]
631 return '(%s)' % (' '.join(details))
632
633 def get_language(self) -> Language:
634 return self.language
635
636 @classmethod
637 def get_display_language(cls) -> str:
638 return cls.language.capitalize()
639
640 def get_default_suffix(self) -> str:
641 return self.default_suffix
642
643 def get_define(self, dname: str, prefix: str,
644 extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
645 dependencies: T.List['Dependency'],
646 disable_cache: bool = False) -> T.Tuple[str, bool]:
647 raise EnvironmentException('%s does not support get_define ' % self.get_id())
648
649 def compute_int(self, expression: str, low: T.Optional[int], high: T.Optional[int],
650 guess: T.Optional[int], prefix: str, *,
651 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
652 dependencies: T.Optional[T.List['Dependency']]) -> int:
653 raise EnvironmentException('%s does not support compute_int ' % self.get_id())
654
655 def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str],
656 build_dir: str) -> T.List[str]:
657 raise EnvironmentException('%s does not support compute_parameters_with_absolute_paths ' % self.get_id())
658
659 def has_members(self, typename: str, membernames: T.List[str], prefix: str, *,
660 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
661 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
662 raise EnvironmentException('%s does not support has_member(s) ' % self.get_id())
663
664 def has_type(self, typename: str, prefix: str,
665 extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]]], *,
666 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
667 raise EnvironmentException('%s does not support has_type ' % self.get_id())
668
669 def symbols_have_underscore_prefix(self) -> bool:
670 raise EnvironmentException('%s does not support symbols_have_underscore_prefix ' % self.get_id())
671
672 def get_exelist(self, ccache: bool = True) -> T.List[str]:
673 return self.exelist.copy() if ccache else self.exelist_no_ccache.copy()
674
675 def get_linker_exelist(self) -> T.List[str]:
676 return self.linker.get_exelist() if self.linker else self.get_exelist()
677
678 @abc.abstractmethod
679 def get_output_args(self, outputname: str) -> T.List[str]:
680 pass
681
682 def get_linker_output_args(self, outputname: str) -> T.List[str]:
683 return self.linker.get_output_args(outputname)
684
685 def get_linker_search_args(self, dirname: str) -> T.List[str]:
686 return self.linker.get_search_args(dirname)
687
688 def get_builtin_define(self, define: str) -> T.Optional[str]:
689 raise EnvironmentException('%s does not support get_builtin_define.' % self.id)
690
691 def has_builtin_define(self, define: str) -> bool:
692 raise EnvironmentException('%s does not support has_builtin_define.' % self.id)
693
694 def get_always_args(self) -> T.List[str]:
695 return []
696
697 def can_linker_accept_rsp(self) -> bool:
698 """
699 Determines whether the linker can accept arguments using the @rsp syntax.
700 """
701 return self.linker.get_accepts_rsp()
702
703 def get_linker_always_args(self) -> T.List[str]:
704 return self.linker.get_always_args() if self.linker else []
705
706 def get_linker_lib_prefix(self) -> str:
707 return self.linker.get_lib_prefix()
708
709 def gen_import_library_args(self, implibname: str) -> T.List[str]:
710 """
711 Used only on Windows for libraries that need an import library.
712 This currently means C, C++, Fortran.
713 """
714 return []
715
716 def gen_export_dynamic_link_args(self) -> T.List[str]:
717 raise MesonException('Language %s does not support export_dynamic.' % self.get_display_language())
718
719 def make_option_name(self, key: OptionKey) -> str:
720 return f'{self.language}_{key.name}'
721
722 def get_options(self) -> 'MutableKeyedOptionDictType':
723 return {}
724
725 def get_option_compile_args(self, target: 'BuildTarget', subproject: T.Optional[str] = None) -> T.List[str]:
726 return []
727
728 def get_option_std_args(self, target: BuildTarget, subproject: T.Optional[str] = None) -> T.List[str]:
729 return []
730
731 def get_option_link_args(self, target: 'BuildTarget', subproject: T.Optional[str] = None) -> T.List[str]:
732 return self.linker.get_option_link_args(target, subproject)
733
734 def check_header(self, hname: str, prefix: str, *,
735 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
736 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
737 """Check that header is usable.
738
739 Returns a two item tuple of bools. The first bool is whether the
740 check succeeded, the second is whether the result was cached (True)
741 or run fresh (False).
742 """
743 raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language())
744
745 def has_header(self, hname: str, prefix: str, *,
746 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
747 dependencies: T.Optional[T.List['Dependency']] = None,
748 disable_cache: bool = False) -> T.Tuple[bool, bool]:
749 """Check that header is exists.
750
751 This check will return true if the file exists, even if it contains:
752
753 ```c
754 # error "You thought you could use this, LOLZ!"
755 ```
756
757 Use check_header if your header only works in some cases.
758
759 Returns a two item tuple of bools. The first bool is whether the
760 check succeeded, the second is whether the result was cached (True)
761 or run fresh (False).
762 """
763 raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language())
764
765 def has_header_symbol(self, hname: str, symbol: str, prefix: str, *,
766 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
767 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
768 raise EnvironmentException('Language %s does not support header symbol checks.' % self.get_display_language())
769
770 def run(self, code: 'mesonlib.FileOrString',
771 extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]], None] = None,
772 dependencies: T.Optional[T.List['Dependency']] = None,
773 run_env: T.Optional[T.Dict[str, str]] = None,
774 run_cwd: T.Optional[str] = None) -> RunResult:
775 need_exe_wrapper = self.environment.need_exe_wrapper(self.for_machine)
776 if need_exe_wrapper and not self.environment.has_exe_wrapper():
777 raise CrossNoRunException('Can not run test applications in this cross environment.')
778 with self._build_wrapper(code, extra_args, dependencies, mode=CompileCheckMode.LINK, want_output=True) as p:
779 if p.returncode != 0:
780 mlog.debug(f'Could not compile test file {p.input_name}: {p.returncode}\n')
781 return RunResult(False)
782 if need_exe_wrapper:
783 cmdlist = self.environment.exe_wrapper.get_command() + [p.output_name]
784 else:
785 cmdlist = [p.output_name]
786 try:
787 pe, so, se = mesonlib.Popen_safe(cmdlist, env=run_env, cwd=run_cwd)
788 except Exception as e:
789 mlog.debug(f'Could not run: {cmdlist} (error: {e})\n')
790 return RunResult(False)
791
792 mlog.debug('Program stdout:\n')
793 mlog.debug(so)
794 mlog.debug('Program stderr:\n')
795 mlog.debug(se)
796 return RunResult(True, pe.returncode, so, se)
797
798 # Caching run() in general seems too risky (no way to know what the program
799 # depends on), but some callers know more about the programs they intend to
800 # run.
801 # For now we just accept code as a string, as that's what internal callers
802 # need anyway. If we wanted to accept files, the cache key would need to
803 # include mtime.
804 def cached_run(self, code: str, *,
805 extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]], None] = None,
806 dependencies: T.Optional[T.List['Dependency']] = None) -> RunResult:
807 run_check_cache = self.environment.coredata.run_check_cache
808 args = self.build_wrapper_args(extra_args, dependencies, CompileCheckMode('link'))
809 key = (code, tuple(args))
810 if key in run_check_cache:
811 p = run_check_cache[key]
812 p.cached = True
813 mlog.debug('Using cached run result:')
814 mlog.debug('Code:\n', code)
815 mlog.debug('Args:\n', extra_args)
816 mlog.debug('Cached run returncode:\n', p.returncode)
817 mlog.debug('Cached run stdout:\n', p.stdout)
818 mlog.debug('Cached run stderr:\n', p.stderr)
819 else:
820 p = self.run(code, extra_args=extra_args, dependencies=dependencies)
821 run_check_cache[key] = p
822 return p
823
824 def sizeof(self, typename: str, prefix: str, *,
825 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
826 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[int, bool]:
827 raise EnvironmentException('Language %s does not support sizeof checks.' % self.get_display_language())
828
829 def alignment(self, typename: str, prefix: str, *,
830 extra_args: T.Optional[T.List[str]] = None,
831 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[int, bool]:
832 raise EnvironmentException('Language %s does not support alignment checks.' % self.get_display_language())
833
834 def has_function(self, funcname: str, prefix: str, *,
835 extra_args: T.Optional[T.List[str]] = None,
836 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
837 """See if a function exists.
838
839 Returns a two item tuple of bools. The first bool is whether the
840 check succeeded, the second is whether the result was cached (True)
841 or run fresh (False).
842 """
843 raise EnvironmentException('Language %s does not support function checks.' % self.get_display_language())
844
845 @classmethod
846 def _unix_args_to_native(cls, args: T.List[str], info: MachineInfo) -> T.List[str]:
847 "Always returns a copy that can be independently mutated"
848 return args.copy()
849
850 def unix_args_to_native(self, args: T.List[str]) -> T.List[str]:
851 return self._unix_args_to_native(args, self.info)
852
853 @classmethod
854 def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]:
855 "Always returns a copy that can be independently mutated"
856 return args.copy()
857
858 def find_library(self, libname: str, extra_dirs: T.List[str], libtype: LibType = LibType.PREFER_SHARED,
859 lib_prefix_warning: bool = True, ignore_system_dirs: bool = False,
860 skip_link_check: bool = False) -> T.Optional[T.List[str]]:
861 raise EnvironmentException(f'Language {self.get_display_language()} does not support library finding.')
862
863 def get_library_naming(self, libtype: LibType, strict: bool = False) -> T.Optional[T.Tuple[str, ...]]:
864 raise EnvironmentException(
865 'Language {} does not support get_library_naming.'.format(
866 self.get_display_language()))
867
868 def get_program_dirs(self) -> T.List[str]:
869 return []
870
871 def has_multi_arguments(self, args: T.List[str]) -> T.Tuple[bool, bool]:
872 """Checks if the compiler has all of the arguments.
873
874 :returns:
875 A tuple of (bool, bool). The first value is whether the check
876 succeeded, and the second is whether it was retrieved from a cache
877 """
878 raise EnvironmentException(
879 'Language {} does not support has_multi_arguments.'.format(
880 self.get_display_language()))
881
882 def has_multi_link_arguments(self, args: T.List[str], to_host_args: bool = True) -> T.Tuple[bool, bool]:
883 """Checks if the linker has all of the arguments.
884
885 to_host_args is False if the arguments were returned by this same Compiler object.
886
887 :returns:
888 A tuple of (bool, bool). The first value is whether the check
889 succeeded, and the second is whether it was retrieved from a cache
890 """
891 return self.linker.has_multi_arguments(args)
892
893 def _get_compile_output(self, dirname: str, mode: CompileCheckMode) -> str:
894 assert mode != CompileCheckMode.PREPROCESS, 'In pre-processor mode, the output is sent to stdout and discarded'
895 # Extension only matters if running results; '.exe' is
896 # guaranteed to be executable on every platform.
897 if mode == CompileCheckMode.LINK:
898 suffix = 'exe'
899 else:
900 suffix = 'obj'
901 return os.path.join(dirname, 'output.' + suffix)
902
903 def get_compiler_args_for_mode(self, mode: CompileCheckMode) -> T.List[str]:
904 args: T.List[str] = []
905 args += self.get_always_args()
906 if mode is CompileCheckMode.COMPILE:
907 args += self.get_compile_only_args()
908 elif mode is CompileCheckMode.PREPROCESS:
909 args += self.get_preprocess_only_args()
910 else:
911 assert mode is CompileCheckMode.LINK
912 args += self.get_linker_always_args()
913 return args
914
915 def compiler_args(self, args: T.Optional[T.Iterable[str]] = None) -> CompilerArgs:
916 """Return an appropriate CompilerArgs instance for this class."""
917 return CompilerArgs(self, args)
918
919 @contextlib.contextmanager
920 def compile(self, code: 'mesonlib.FileOrString',
921 extra_args: T.Union[None, CompilerArgs, T.List[str]] = None,
922 *, mode: CompileCheckMode = CompileCheckMode.LINK, want_output: bool = False,
923 temp_dir: T.Optional[str] = None) -> T.Iterator[CompileResult]:
924 # TODO: there isn't really any reason for this to be a contextmanager
925
926 if mode == CompileCheckMode.PREPROCESS:
927 assert not want_output, 'In pre-processor mode, the output is sent to stdout and discarded'
928
929 if extra_args is None:
930 extra_args = []
931
932 with TemporaryDirectoryWinProof(dir=temp_dir if temp_dir else None) as tmpdirname:
933 no_ccache = False
934 if isinstance(code, str):
935 srcname = os.path.join(tmpdirname,
936 'testfile.' + self.default_suffix)
937 with open(srcname, 'w', encoding='utf-8') as ofile:
938 ofile.write(code)
939 if not code.endswith('\n'):
940 ofile.write('\n')
941 # ccache would result in a cache miss
942 no_ccache = True
943 code_debug = f'Code:\n{code}'
944 else:
945 srcname = code.fname
946 code_debug = f'Source file: {srcname}'
947
948 compiler_id = self.get_id()
949 suffixes = compiler_suffixes.get(compiler_id)
950 if suffixes:
951 suffix = os.path.splitext(srcname)[1]
952 if suffix and suffix[1:] not in suffixes:
953 err = f'Unrecognized filename suffix for "{srcname}", will be ignored by {compiler_id}'
954 mlog.error(err)
955 yield CompileResult('', err, [], 1, srcname)
956 return
957
958 # Construct the compiler command-line
959 commands = self.compiler_args()
960 commands.append(srcname)
961
962 # Preprocess mode outputs to stdout, so no output args
963 if mode != CompileCheckMode.PREPROCESS:
964 output = self._get_compile_output(tmpdirname, mode)
965 commands += self.get_output_args(output)
966 commands.extend(self.get_compiler_args_for_mode(CompileCheckMode(mode)))
967
968 # extra_args must be last because it could contain '/link' to
969 # pass args to VisualStudio's linker. In that case everything
970 # in the command line after '/link' is given to the linker.
971 if extra_args:
972 commands += extra_args
973 # Generate full command-line with the exelist
974 command_list = self.get_exelist(ccache=not no_ccache) + commands.to_native()
975 mlog.debug('Running compile:')
976 mlog.debug('Working directory: ', tmpdirname)
977 mlog.debug(code_debug)
978 os_env = os.environ.copy()
979 os_env['LC_ALL'] = 'C'
980 if no_ccache:
981 os_env['CCACHE_DISABLE'] = '1'
982 p, stdo, stde = Popen_safe_logged(command_list, msg='Command line', cwd=tmpdirname, env=os_env)
983
984 result = CompileResult(stdo, stde, command_list, p.returncode, input_name=srcname)
985 if want_output:
986 result.output_name = output
987 yield result
988
989 @contextlib.contextmanager
990 def cached_compile(self, code: 'mesonlib.FileOrString', *,
991 extra_args: T.Union[None, T.List[str], CompilerArgs] = None,
992 mode: CompileCheckMode = CompileCheckMode.LINK,
993 temp_dir: T.Optional[str] = None) -> T.Iterator[CompileResult]:
994 # TODO: There's isn't really any reason for this to be a context manager
995
996 # Calculate the key
997 textra_args: T.Tuple[str, ...] = tuple(extra_args) if extra_args is not None else tuple()
998 key: coredata.CompilerCheckCacheKey = (tuple(self.exelist), self.version, code, textra_args, mode)
999
1000 # Check if not cached, and generate, otherwise get from the cache
1001 cache = self.environment.coredata.compiler_check_cache
1002 if key in cache:
1003 p = cache[key]
1004 p.cached = True
1005 mlog.debug('Using cached compile:')
1006 mlog.debug('Cached command line: ', ' '.join(p.command), '\n')
1007 mlog.debug('Code:\n', code)
1008 mlog.debug('Cached compiler stdout:\n', p.stdout)
1009 mlog.debug('Cached compiler stderr:\n', p.stderr)
1010 yield p
1011 else:
1012 with self.compile(code, extra_args=extra_args, mode=mode, want_output=False, temp_dir=temp_dir) as p:
1013 cache[key] = p
1014 yield p
1015
1016 def get_colorout_args(self, colortype: str) -> T.List[str]:
1017 # TODO: colortype can probably be an emum
1018 return []
1019
1020 # Some compilers (msvc) write debug info to a separate file.
1021 # These args specify where it should be written.
1022 def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> T.List[str]:
1023 return []
1024
1025 def should_link_pch_object(self) -> bool:
1026 return False
1027
1028 def get_link_debugfile_name(self, targetfile: str) -> T.Optional[str]:
1029 return self.linker.get_debugfile_name(targetfile)
1030
1031 def get_link_debugfile_args(self, targetfile: str) -> T.List[str]:
1032 return self.linker.get_debugfile_args(targetfile)
1033
1034 def get_std_link_args(self, env: Environment, is_thin: bool) -> T.List[str]:
1035 raise MesonBugException("get_std_link_args() not implemented; if needs_static_linker() is False it needs to be")
1036
1037 def get_std_shared_lib_link_args(self) -> T.List[str]:
1038 return self.linker.get_std_shared_lib_args()
1039
1040 def get_std_shared_module_link_args(self, target: 'BuildTarget') -> T.List[str]:
1041 return self.linker.get_std_shared_module_args(target)
1042
1043 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
1044 return self.linker.get_link_whole_for(args)
1045
1046 def get_allow_undefined_link_args(self) -> T.List[str]:
1047 return self.linker.get_allow_undefined_args()
1048
1049 def no_undefined_link_args(self) -> T.List[str]:
1050 return self.linker.no_undefined_args()
1051
1052 def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]:
1053 """Compiler arguments needed to enable the given instruction set.
1054
1055 Return type ay be an empty list meaning nothing needed or None
1056 meaning the given set is not supported.
1057 """
1058 return None
1059
1060 def build_rpath_args(self, build_dir: str, from_dir: str, target: BuildTarget,
1061 extra_paths: T.Optional[T.List[str]] = None
1062 ) -> T.Tuple[T.List[str], T.Set[bytes]]:
1063 return self.linker.build_rpath_args(build_dir, from_dir, target, extra_paths)
1064
1065 def get_archive_name(self, filename: str) -> str:
1066 return self.linker.get_archive_name(filename)
1067
1068 def get_command_to_archive_shlib(self) -> T.List[str]:
1069 if not self.linker:
1070 return []
1071 return self.linker.get_command_to_archive_shlib()
1072
1073 def thread_flags(self) -> T.List[str]:
1074 return []
1075
1076 def thread_link_flags(self) -> T.List[str]:
1077 return self.linker.thread_flags()
1078
1079 def openmp_flags(self) -> T.List[str]:
1080 raise EnvironmentException('Language %s does not support OpenMP flags.' % self.get_display_language())
1081
1082 def openmp_link_flags(self) -> T.List[str]:
1083 return self.openmp_flags()
1084
1085 def language_stdlib_only_link_flags(self) -> T.List[str]:
1086 return []
1087
1088 def gnu_symbol_visibility_args(self, vistype: str) -> T.List[str]:
1089 return []
1090
1091 def get_win_subsystem_args(self, value: str) -> T.List[str]:
1092 # By default the dynamic linker is going to return an empty
1093 # array in case it either doesn't support Windows subsystems
1094 # or does not target Windows
1095 return self.linker.get_win_subsystem_args(value)
1096
1097 def has_func_attribute(self, name: str) -> T.Tuple[bool, bool]:
1098 raise EnvironmentException(
1099 f'Language {self.get_display_language()} does not support function attributes.')
1100
1101 def get_pic_args(self) -> T.List[str]:
1102 m = 'Language {} does not support position-independent code'
1103 raise EnvironmentException(m.format(self.get_display_language()))
1104
1105 def get_pie_args(self) -> T.List[str]:
1106 m = 'Language {} does not support position-independent executable'
1107 raise EnvironmentException(m.format(self.get_display_language()))
1108
1109 def get_pie_link_args(self) -> T.List[str]:
1110 return self.linker.get_pie_args()
1111
1112 @staticmethod
1113 def get_argument_syntax() -> str:
1114 """Returns the argument family type.
1115
1116 Compilers fall into families if they try to emulate the command line
1117 interface of another compiler. For example, clang is in the GCC family
1118 since it accepts most of the same arguments as GCC. ICL (ICC on
1119 windows) is in the MSVC family since it accepts most of the same
1120 arguments as MSVC.
1121 """
1122 return 'other'
1123
1124 def get_profile_generate_args(self) -> T.List[str]:
1125 raise EnvironmentException(
1126 '%s does not support get_profile_generate_args ' % self.get_id())
1127
1128 def get_profile_use_args(self) -> T.List[str]:
1129 raise EnvironmentException(
1130 '%s does not support get_profile_use_args ' % self.get_id())
1131
1132 def remove_linkerlike_args(self, args: T.List[str]) -> T.List[str]:
1133 rm_exact = ('-headerpad_max_install_names',)
1134 rm_prefixes = ('-Wl,', '-L',)
1135 rm_next = ('-L', '-framework',)
1136 ret: T.List[str] = []
1137 iargs = iter(args)
1138 for arg in iargs:
1139 # Remove this argument
1140 if arg in rm_exact:
1141 continue
1142 # If the argument starts with this, but is not *exactly* this
1143 # f.ex., '-L' should match ['-Lfoo'] but not ['-L', 'foo']
1144 if arg.startswith(rm_prefixes) and arg not in rm_prefixes:
1145 continue
1146 # Ignore this argument and the one after it
1147 if arg in rm_next:
1148 next(iargs)
1149 continue
1150 ret.append(arg)
1151 return ret
1152
1153 def get_embed_bitcode_args(self, bitcode: bool, lto: bool) -> T.List[str]:
1154 return []
1155
1156 def get_lto_compile_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
1157 mode: str = 'default') -> T.List[str]:
1158 return []
1159
1160 def get_lto_link_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0,
1161 mode: str = 'default', thinlto_cache_dir: T.Optional[str] = None) -> T.List[str]:
1162 return self.linker.get_lto_args()
1163
1164 def get_lto_obj_cache_path(self, path: str) -> T.List[str]:
1165 return self.linker.get_lto_obj_cache_path(path)
1166
1167 def sanitizer_compile_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]:
1168 return []
1169
1170 def sanitizer_link_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]:
1171 return self.linker.sanitizer_args(value)
1172
1173 def get_asneeded_args(self) -> T.List[str]:
1174 return self.linker.get_asneeded_args()
1175
1176 def headerpad_args(self) -> T.List[str]:
1177 return self.linker.headerpad_args()
1178
1179 def bitcode_args(self) -> T.List[str]:
1180 return self.linker.bitcode_args()
1181
1182 def get_optimization_link_args(self, optimization_level: str) -> T.List[str]:
1183 return self.linker.get_optimization_link_args(optimization_level)
1184
1185 def get_linker_fatal_warnings(self) -> T.List[str]:
1186 return self.linker.fatal_warnings()
1187
1188 def get_soname_args(self, prefix: str, shlib_name: str, suffix: str, soversion: str,
1189 darwin_versions: T.Tuple[str, str]) -> T.List[str]:
1190 return self.linker.get_soname_args(
1191 prefix, shlib_name, suffix, soversion,
1192 darwin_versions)
1193
1194 def get_build_link_args(self, target: BuildTarget, build: build.Build) -> T.List[str]:
1195 # Link args added using add_global_link_arguments() override
1196 # per-project link arguments. Link args added from the env (LDFLAGS)
1197 # override all the defaults but not the per-target link args.
1198 return build.get_project_link_args(self, target) \
1199 + build.get_global_link_args(self, target) \
1200 + self.environment.coredata.get_external_link_args(self.for_machine, self.get_language())
1201
1202 def get_target_link_args(self, target: 'BuildTarget') -> T.List[str]:
1203 return target.link_args
1204
1205 def get_target_link_early_args(self, target: 'BuildTarget') -> T.List[str]:
1206 return target.link_early_args
1207
1208 def get_dependency_compile_args(self, dep: 'Dependency') -> T.List[str]:
1209 return dep.get_compile_args()
1210
1211 def get_dependency_link_args(self, dep: 'Dependency') -> T.List[str]:
1212 return dep.get_link_args(self.get_language())
1213
1214 @classmethod
1215 def use_linker_args(cls, linker: str, version: str) -> T.List[str]:
1216 """Get a list of arguments to pass to the compiler to set the linker.
1217 """
1218 return []
1219
1220 def get_coverage_args(self) -> T.List[str]:
1221 return []
1222
1223 def get_coverage_link_args(self) -> T.List[str]:
1224 return self.linker.get_coverage_args()
1225
1226 def gen_vs_module_defs_args(self, defsfile: str) -> T.List[str]:
1227 return self.linker.gen_vs_module_defs_args(defsfile)
1228
1229 def get_assert_args(self, disable: bool) -> T.List[str]:
1230 """Get arguments to enable or disable assertion.
1231
1232 :param disable: Whether to disable assertions
1233 :return: A list of string arguments for this compiler
1234 """
1235 return []
1236
1237 def get_crt_val(self, crt_val: str) -> str:
1238 if crt_val in options.MSCRT_VALS:
1239 return crt_val
1240 assert crt_val in {'from_buildtype', 'static_from_buildtype'}
1241
1242 dbg = 'mdd'
1243 rel = 'md'
1244 if crt_val == 'static_from_buildtype':
1245 dbg = 'mtd'
1246 rel = 'mt'
1247
1248 # Match what build type flags used to do.
1249 buildtype = self.environment.coredata.optstore.get_value_for('buildtype')
1250 assert isinstance(buildtype, str), 'for mypy'
1251 if buildtype == 'plain':
1252 return 'none'
1253 elif buildtype == 'debug':
1254 return dbg
1255 elif buildtype in {'debugoptimized', 'release', 'minsize'}:
1256 return rel
1257 else:
1258 assert buildtype == 'custom'
1259 raise EnvironmentException('Requested C runtime based on buildtype, but buildtype is "custom".')
1260
1261 def get_crt_compile_args(self, crt_val: str) -> T.List[str]:
1262 raise EnvironmentException('This compiler does not support Windows CRT selection')
1263
1264 def get_crt_link_args(self, crt_val: str) -> T.List[str]:
1265 raise EnvironmentException('This compiler does not support Windows CRT selection')
1266
1267 def get_compile_only_args(self) -> T.List[str]:
1268 return []
1269
1270 def get_preprocess_only_args(self) -> T.List[str]:
1271 raise EnvironmentException('This compiler does not have a preprocessor')
1272
1273 def get_preprocess_to_file_args(self) -> T.List[str]:
1274 return self.get_preprocess_only_args()
1275
1276 def get_default_include_dirs(self) -> T.List[str]:
1277 # TODO: This is a candidate for returning an immutable list
1278 return []
1279
1280 def get_largefile_args(self) -> T.List[str]:
1281 '''Enable transparent large-file-support for 32-bit UNIX systems'''
1282 if not (self.get_argument_syntax() == 'msvc' or self.info.is_darwin()):
1283 # Enable large-file support unconditionally on all platforms other
1284 # than macOS and MSVC. macOS is now 64-bit-only so it doesn't
1285 # need anything special, and MSVC doesn't have automatic LFS.
1286 # You must use the 64-bit counterparts explicitly.
1287 # glibc, musl, and uclibc, and all BSD libcs support this. On Android,
1288 # support for transparent LFS is available depending on the version of
1289 # Bionic: https://github.com/android/platform_bionic#32-bit-abi-bugs
1290 # https://code.google.com/p/android/issues/detail?id=64613
1291 #
1292 # If this breaks your code, fix it! It's been 20+ years!
1293 return ['-D_FILE_OFFSET_BITS=64']
1294 # We don't enable -D_LARGEFILE64_SOURCE since that enables
1295 # transitionary features and must be enabled by programs that use
1296 # those features explicitly.
1297 return []
1298
1299 def get_library_dirs(self, elf_class: T.Optional[int] = None) -> T.List[str]:
1300 return []
1301
1302 def get_return_value(self,
1303 fname: str,
1304 rtype: str,
1305 prefix: str,
1306 extra_args: T.Optional[T.List[str]],
1307 dependencies: T.Optional[T.List['Dependency']]) -> T.Union[str, int]:
1308 raise EnvironmentException(f'{self.id} does not support get_return_value')
1309
1310 def find_framework(self,
1311 name: str,
1312 extra_dirs: T.List[str],
1313 allow_system: bool = True) -> T.Optional[T.List[str]]:
1314 raise EnvironmentException(f'{self.id} does not support find_framework')
1315
1316 def find_framework_paths(self) -> T.List[str]:
1317 raise EnvironmentException(f'{self.id} does not support find_framework_paths')
1318
1319 def attribute_check_func(self, name: str) -> str:
1320 raise EnvironmentException(f'{self.id} does not support attribute checks')
1321
1322 def get_pch_suffix(self) -> str:
1323 raise EnvironmentException(f'{self.id} does not support pre compiled headers')
1324
1325 def get_pch_name(self, name: str) -> str:
1326 raise EnvironmentException(f'{self.id} does not support pre compiled headers')
1327
1328 def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]:
1329 raise EnvironmentException(f'{self.id} does not support pre compiled headers')
1330
1331 def get_has_func_attribute_extra_args(self, name: str) -> T.List[str]:
1332 raise EnvironmentException(f'{self.id} does not support function attributes')
1333
1334 def name_string(self) -> str:
1335 return ' '.join(self.exelist)
1336
1337 def sanity_check(self, work_dir: str) -> None:
1338 """Check that this compiler actually works.
1339
1340 This should provide a simple compile/link test. Something as simple as:
1341 ```python
1342 main(): return 0
1343 ```
1344 is good enough here.
1345
1346 :param work_dir: A directory to put temporary artifacts
1347 :raises mesonlib.EnvironmentException: If building the binary fails
1348 :raises mesonlib.EnvironmentException: If running the binary is attempted and fails
1349 """
1350 sourcename, transpiled, binname = self._sanity_check_filenames()
1351
1352 with open(os.path.join(work_dir, sourcename), 'w', encoding='utf-8') as f:
1353 f.write(self._sanity_check_source_code())
1354
1355 if transpiled:
1356 cmdlist, linker_args = self._sanity_check_compile_args(sourcename, transpiled)
1357 cmdlist.extend(linker_args)
1358 pc, stdo, stde = mesonlib.Popen_safe(cmdlist, cwd=work_dir)
1359 mlog.debug('Sanity check transpiler command line:', mesonlib.join_args(cmdlist))
1360 mlog.debug('Sanity check transpiler stdout:')
1361 mlog.debug(stdo)
1362 mlog.debug('-----\nSanity check transpiler stderr:')
1363 mlog.debug(stde)
1364 mlog.debug('-----')
1365 if pc.returncode != 0:
1366 raise mesonlib.EnvironmentException(f'Compiler {self.name_string()} cannot transpile programs.')
1367
1368 comp_lang = SUFFIX_TO_LANG[transpiled.rsplit('.', maxsplit=1)[1]]
1369 comp = self.environment.coredata.compilers[self.for_machine].get(comp_lang)
1370 if not comp:
1371 raise mesonlib.MesonBugException(f'Need a {comp_lang} compiler for {self.language} compiler test, but one doesnt exist')
1372
1373 cmdlist, linker_args = self._transpiled_sanity_check_compile_args(comp, transpiled, binname)
1374
1375 mlog.debug('checking compilation of transpiled source:')
1376 else:
1377 cmdlist, linker_args = self._sanity_check_compile_args(sourcename, binname)
1378
1379 cmdlist.extend(linker_args)
1380 pc, stdo, stde = mesonlib.Popen_safe(cmdlist, cwd=work_dir)
1381 mlog.debug('Sanity check compiler command line:', mesonlib.join_args(cmdlist))
1382 mlog.debug('Sanity check compile stdout:')
1383 mlog.debug(stdo)
1384 mlog.debug('-----\nSanity check compile stderr:')
1385 mlog.debug(stde)
1386 mlog.debug('-----')
1387 if pc.returncode != 0:
1388 raise mesonlib.EnvironmentException(f'Compiler {self.name_string()} cannot compile programs.')
1389
1390 self._run_sanity_check([os.path.join(work_dir, binname)], work_dir)
1391
1392 def _sanity_check_filenames(self) -> T.Tuple[str, T.Optional[str], str]:
1393 """Generate the name of the source and binary file for the sanity check.
1394
1395 The returned names should be just the names of the files with
1396 extensions, but no paths.
1397
1398 The return value consists of a source name, a transpiled source name (if
1399 there is one), and the final binary name.
1400
1401 :return: A tuple of (sourcename, transpiled, binaryname)
1402 """
1403 default_ext = lang_suffixes[self.language][0]
1404 template = f'sanity_check_for_{self.language}'
1405 sourcename = f'{template}.{default_ext}'
1406 cross_or_not = "_cross" if self.is_cross else ""
1407 binaryname = f'{template}{cross_or_not}.exe'
1408 return sourcename, None, binaryname
1409
1410 def _transpiled_sanity_check_compile_args(
1411 self, compiler: Compiler, sourcename: str, binname: str
1412 ) -> T.Tuple[T.List[str], T.List[str]]:
1413 """Get arguments to run compiler for sanity check.
1414
1415 By default this will just return the compile arguments for the compiler in question.
1416
1417 Linker arguments are separated from compiler arguments because some
1418 compilers do not allow linker and compiler arguments to be mixed together
1419
1420 Overriding this is useful when needing to change the kind of output
1421 produced, or adding extra arguments.
1422
1423 :param compiler: The :class:`Compiler` that is used for compiling the transpiled sources
1424 :param sourcename: the name of the source file to generate
1425 :param binname: the name of the binary file to generate
1426 :return: a tuple of arguments, the first is the executable and compiler
1427 arguments, the second is linker arguments
1428 """
1429 return compiler._sanity_check_compile_args(sourcename, binname)
1430
1431 def _sanity_check_compile_args(self, sourcename: str, binname: str
1432 ) -> T.Tuple[T.List[str], T.List[str]]:
1433 """Get arguments to run compiler for sanity check.
1434
1435 Linker arguments are separated from compiler arguments because some
1436 compilers do not allow linker and compiler arguments to be mixed together
1437
1438 :param sourcename: the name of the source file to generate
1439 :param binname: the name of the binary file to generate
1440 :return: a tuple of arguments, the first is the executable and compiler
1441 arguments, the second is linker arguments
1442 """
1443 cargs = list(self.environment.coredata.get_external_args(self.for_machine, self.language))
1444 largs = list(self.environment.coredata.get_external_link_args(self.for_machine, self.language))
1445 return self.exelist_no_ccache + self.get_always_args() + self.get_output_args(binname) + [sourcename] + cargs, largs
1446
1447 @abc.abstractmethod
1448 def _sanity_check_source_code(self) -> str:
1449 """Get the source code to run for a sanity check
1450
1451 :return: A string to be written into a file and ran.
1452 """
1453
1454 def _sanity_check_run_with_exe_wrapper(self, command: T.List[str]) -> T.List[str]:
1455 """Wrap the binary to run in the test with the exe_wrapper if necessary
1456
1457 Languages that do no want to use an exe_wrapper (or always want to use
1458 some kind of wrapper) should override this method
1459
1460 :param command: The string list of commands to run
1461 :return: The list of commands wrapped by the exe_wrapper if it is needed, otherwise the original commands
1462 """
1463 if self.is_cross and (exe_wrapper := self.environment.get_exe_wrapper()):
1464 return exe_wrapper.get_command() + command
1465 return command
1466
1467 def _run_sanity_check(self, cmdlist: T.List[str], work_dir: str) -> None:
1468 """Run a sanity test binary
1469
1470 :param cmdlist: A list of strings to pass to :func:`subprocess.run` or equivalent to run the test
1471 :param work_dir: A directory to place temporary artifacts
1472 :raises mesonlib.EnvironmentException: If the binary cannot be run or if it returns a non-zero exit code
1473 """
1474 # Can't check binaries, so we have to assume they work
1475 if self.is_cross and not self.environment.has_exe_wrapper():
1476 mlog.debug('Cannot run cross check')
1477 return
1478
1479 cmdlist = self._sanity_check_run_with_exe_wrapper(cmdlist)
1480 mlog.debug('Sanity check built target output for', self.for_machine, self.language, 'compiler')
1481 mlog.debug(' -- Running test binary command: ', mesonlib.join_args(cmdlist))
1482 try:
1483 pe, stdo, stde = Popen_safe_logged(cmdlist, 'Sanity check', cwd=work_dir)
1484 mlog.debug(' -- stdout:\n', stdo)
1485 mlog.debug(' -- stderr:\n', stde)
1486 mlog.debug(' -- returncode:', pe.returncode)
1487 except Exception as e:
1488 raise mesonlib.EnvironmentException(f'Could not invoke sanity check executable: {e!s}.')
1489
1490 if pe.returncode != 0:
1491 raise mesonlib.EnvironmentException(f'Executables created by {self.language} compiler {self.name_string()} are not runnable.')
1492
1493 def split_shlib_to_parts(self, fname: str) -> T.Tuple[T.Optional[str], str]:
1494 return None, fname
1495
1496 def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]:
1497 return []
1498
1499 def get_std_exe_link_args(self) -> T.List[str]:
1500 # TODO: is this a linker property?
1501 return []
1502
1503 def get_include_args(self, path: str, is_system: bool) -> T.List[str]:
1504 return []
1505
1506 def get_depfile_format(self) -> str:
1507 return 'msvc' if self.get_argument_syntax() == 'msvc' else 'gcc'
1508
1509 def depfile_for_object(self, objfile: str) -> T.Optional[str]:
1510 return objfile + '.' + self.get_depfile_suffix()
1511
1512 def get_depfile_suffix(self) -> str:
1513 raise EnvironmentException(f'{self.id} does not implement get_depfile_suffix')
1514
1515 def get_no_stdinc_args(self) -> T.List[str]:
1516 """Arguments to turn off default inclusion of standard libraries."""
1517 return []
1518
1519 def get_no_stdlib_link_args(self) -> T.List[str]:
1520 """Arguments to turn off default linking to standard libraries."""
1521 return []
1522
1523 def get_warn_args(self, level: str) -> T.List[str]:
1524 return []
1525
1526 def get_werror_args(self) -> T.List[str]:
1527 return []
1528
1529 def get_cpp_modules_args(self) -> T.List[str]:
1530 return []
1531
1532 @abc.abstractmethod
1533 def get_optimization_args(self, optimization_level: str) -> T.List[str]:
1534 pass
1535
1536 def get_module_incdir_args(self) -> T.Tuple[str, ...]:
1537 raise EnvironmentException(f'{self.id} does not implement get_module_incdir_args')
1538
1539 def get_module_outdir_args(self, path: str) -> T.List[str]:
1540 raise EnvironmentException(f'{self.id} does not implement get_module_outdir_args')
1541
1542 def module_name_to_filename(self, module_name: str) -> str:
1543 raise EnvironmentException(f'{self.id} does not implement module_name_to_filename')
1544
1545 def get_compiler_check_args(self, mode: CompileCheckMode) -> T.List[str]:
1546 """Arguments to pass the compiler and/or linker for checks.
1547
1548 The default implementation turns off optimizations.
1549
1550 Examples of things that go here:
1551 - extra arguments for error checking
1552 - Arguments required to make the compiler exit with a non-zero status
1553 when something is wrong.
1554 """
1555 return self.get_no_optimization_args()
1556
1557 def get_no_optimization_args(self) -> T.List[str]:
1558 """Arguments to the compiler to turn off all optimizations."""
1559 return []
1560
1561 def build_wrapper_args(self,
1562 extra_args: T.Union[None, CompilerArgs, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
1563 dependencies: T.Optional[T.List['Dependency']],
1564 mode: CompileCheckMode = CompileCheckMode.COMPILE) -> CompilerArgs:
1565 """Arguments to pass the build_wrapper helper.
1566
1567 This generally needs to be set on a per-language basis. It provides
1568 a hook for languages to handle dependencies and extra args. The base
1569 implementation handles the most common cases, namely adding the
1570 check_arguments, unwrapping dependencies, and appending extra args.
1571 """
1572 if callable(extra_args):
1573 extra_args = extra_args(mode)
1574 if extra_args is None:
1575 extra_args = []
1576 if dependencies is None:
1577 dependencies = []
1578
1579 # Collect compiler arguments
1580 args = self.compiler_args(self.get_compiler_check_args(mode))
1581 for d in dependencies:
1582 # Add compile flags needed by dependencies
1583 args += d.get_compile_args()
1584 if mode is CompileCheckMode.LINK:
1585 # Add link flags needed to find dependencies
1586 args += d.get_link_args()
1587
1588 if mode is CompileCheckMode.COMPILE:
1589 # Add DFLAGS from the env
1590 args += self.environment.coredata.get_external_args(self.for_machine, self.language)
1591 elif mode is CompileCheckMode.LINK:
1592 # Add LDFLAGS from the env
1593 args += self.environment.coredata.get_external_link_args(self.for_machine, self.language)
1594 # extra_args must override all other arguments, so we add them last
1595 args += extra_args
1596 return args
1597
1598 @contextlib.contextmanager
1599 def _build_wrapper(self, code: 'mesonlib.FileOrString',
1600 extra_args: T.Union[None, CompilerArgs, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
1601 dependencies: T.Optional[T.List['Dependency']] = None,
1602 mode: CompileCheckMode = CompileCheckMode.COMPILE, want_output: bool = False,
1603 disable_cache: bool = False) -> T.Iterator[CompileResult]:
1604 """Helper for getting a cached value when possible.
1605
1606 This method isn't meant to be called externally, it's mean to be
1607 wrapped by other methods like compiles() and links().
1608 """
1609 args = self.build_wrapper_args(extra_args, dependencies, mode)
1610 if disable_cache or want_output:
1611 with self.compile(code, extra_args=args, mode=mode, want_output=want_output, temp_dir=self.environment.scratch_dir) as r:
1612 yield r
1613 else:
1614 with self.cached_compile(code, extra_args=args, mode=mode, temp_dir=self.environment.scratch_dir) as r:
1615 yield r
1616
1617 def compiles(self, code: 'mesonlib.FileOrString', *,
1618 extra_args: T.Union[None, T.List[str], CompilerArgs, T.Callable[[CompileCheckMode], T.List[str]]] = None,
1619 dependencies: T.Optional[T.List['Dependency']] = None,
1620 mode: CompileCheckMode = CompileCheckMode.COMPILE,
1621 disable_cache: bool = False) -> T.Tuple[bool, bool]:
1622 """Run a compilation or link test to see if code can be compiled/linked.
1623
1624 :returns:
1625 A tuple of (bool, bool). The first value is whether the check
1626 succeeded, and the second is whether it was retrieved from a cache
1627 """
1628 with self._build_wrapper(code, extra_args, dependencies, mode, disable_cache=disable_cache) as p:
1629 return p.returncode == 0, p.cached
1630
1631 def links(self, code: 'mesonlib.FileOrString', *,
1632 compiler: T.Optional['Compiler'] = None,
1633 extra_args: T.Union[None, T.List[str], CompilerArgs, T.Callable[[CompileCheckMode], T.List[str]]] = None,
1634 dependencies: T.Optional[T.List['Dependency']] = None,
1635 disable_cache: bool = False) -> T.Tuple[bool, bool]:
1636 if compiler:
1637 with compiler._build_wrapper(code, dependencies=dependencies, want_output=True) as r:
1638 objfile = mesonlib.File.from_absolute_file(r.output_name)
1639 return self.compiles(objfile, extra_args=extra_args,
1640 dependencies=dependencies, mode=CompileCheckMode.LINK, disable_cache=True)
1641
1642 return self.compiles(code, extra_args=extra_args,
1643 dependencies=dependencies, mode=CompileCheckMode.LINK, disable_cache=disable_cache)
1644
1645 def get_feature_args(self, kwargs: DFeatures, build_to_src: str) -> T.List[str]:
1646 """Used by D for extra language features."""
1647 # TODO: using a TypeDict here would improve this
1648 raise EnvironmentException(f'{self.id} does not implement get_feature_args')
1649
1650 def get_prelink_args(self, prelink_name: str, obj_list: T.List[str]) -> T.Tuple[T.List[str], T.List[str]]:
1651 raise EnvironmentException(f'{self.id} does not know how to do prelinking.')
1652
1653 def get_prelink_append_compile_args(self) -> bool:
1654 """Controls whether compile args have to be used for prelinking or not"""
1655 return False
1656
1657 def rsp_file_syntax(self) -> 'RSPFileSyntax':
1658 """The format of the RSP file that this compiler supports.
1659
1660 If `self.can_linker_accept_rsp()` returns True, then this needs to
1661 be implemented
1662 """
1663 return self.linker.rsp_file_syntax()
1664
1665 def get_debug_args(self, is_debug: bool) -> T.List[str]:
1666 """Arguments required for a debug build."""
1667 return []
1668
1669 def needs_static_linker(self) -> bool:
1670 raise NotImplementedError(f'There is no static linker for {self.language}')
1671
1672 def get_preprocessor(self) -> Compiler:
1673 """Get compiler's preprocessor.
1674 """
1675 raise EnvironmentException(f'{self.get_id()} does not support preprocessor')
1676
1677 def form_compileropt_key(self, basename: str) -> OptionKey:
1678 return OptionKey(f'{self.language}_{basename}', machine=self.for_machine)
1679
1680 def get_compileropt_value(self,
1681 key: T.Union[str, OptionKey],
1682 target: T.Optional[BuildTarget],
1683 subproject: T.Optional[str] = None
1684 ) -> options.ElementaryOptionValues:
1685 if isinstance(key, str):
1686 key = self.form_compileropt_key(key)
1687 if target:
1688 return self.environment.coredata.get_option_for_target(target, key)
1689 else:
1690 return self.environment.coredata.optstore.get_value_for(key.evolve(subproject=subproject))
1691
1692 def _update_language_stds(self, opts: MutableKeyedOptionDictType, value: T.List[str]) -> None:
1693 key = self.form_compileropt_key('std')
1694 std = opts[key]
1695 assert isinstance(std, (options.UserStdOption, options.UserComboOption)), 'for mypy'
1696 if 'none' not in value:
1697 value = ['none'] + value
1698 std.choices = value
1699
1700 def get_crt_static(self) -> bool:
1701 """Is this target using static CRT?"""
1702 raise EnvironmentException(f'{self.get_id()} does not support static CRT')
1703
1704 def get_target_libdir(self) -> str:
1705 """Where is the libdir for the current machine located"""
1706 raise EnvironmentException(f'{self.get_id()} does not support Rust target libdir')
1707
1708 def get_show_dep_args(self) -> T.List[str]:
1709 """Arguments for printing depfile information in MSVC compatible format"""
1710 return []